gpt4 book ai didi

java - Fragment 和 BroadcastReceiver 在几秒钟后卡住应用程序

转载 作者:行者123 更新时间:2023-12-02 11:52:15 24 4
gpt4 key购买 nike

这里是应用程序的完整代码,它在工作几秒钟后卡住(UI)。

这里有危险吗?

谢谢!

public class FragmentOne extends Fragment {

private Context _context;
private View view;
private BroadcastReceiver broadcastReceiver;

public FragmentOne() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

view = inflater.inflate(R.layout.fragment_fragment_one, container, false);
setup();
return view;
}

@Override
public void onAttach(Context context)
{
super.onAttach(context);
_context = context;
}

private void setup()
{
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent i)
{
try
{
DLocation dLocation = (DLocation) i.getExtras().get("coordinates");

if (dLocation != null) {
Log.d("Первый фрагмент", "Применение параметров шир. сообщения к контролам окна");

TextView textLon = (TextView)view.findViewById(R.id.textLon);
textLon.setText(dLocation.Longitude);

TextView textLat = (TextView)view.findViewById(R.id.textLat);
textLat.setText(dLocation.Latitude);

TextView textTime = (TextView)view.findViewById(R.id.textTime);
textTime.setText(dLocation.TimeOfRequest);

TextView textErrors = (TextView)view.findViewById(R.id.textErrors);
textErrors.setText(dLocation.Errors);
}
}
catch (Exception ex)
{
Toast.makeText(getActivity(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
};

_context.registerReceiver(broadcastReceiver, new IntentFilter("location_update"));


}

@Override
public void onResume() {
super.onResume();
}

@Override
public void onPause() {
super.onPause();
}

@Override
public void onDestroy() {
super.onDestroy();

if (broadcastReceiver != null) {
_context.unregisterReceiver(broadcastReceiver);
}
}
}

最佳答案

根本原因

我认为您正在使用第三方库来检测位置。图书馆正在以非常高的速率接收 GPS 坐标。然后,您的广播接收器会接收这些坐标。您的广播接收器正在 UI 线程上完成工作。您的应用程序卡住的原因是 UI 线程正在以非常高的速率工作。

解决方案

您的问题的解决方案在于绑定(bind)服务。您可以在 android 开发人员文档 Bound Services 中找到代码示例.

对于像音乐播放器这样的用例,其中媒体在后台线程中播放,但播放音乐的持续时间显示在 UI 上,绑定(bind)服务可能很有用。我希望这能让您朝着正确的方向前进。

关于java - Fragment 和 BroadcastReceiver 在几秒钟后卡住应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47809481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com