Fragment 和 BroadcastReceiver 在几秒钟后冻结应用程序

Fragment and BroadcastReceiver freeze app after some seconds

这是应用程序的完整代码,它在工作几秒钟后冻结 (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);
        }
    }
}

根本原因

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

解决方案

您的问题的解决方案在于绑定服务。您可以在 android 开发人员文档 Bound Services.

中找到代码示例

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