为什么我的 BroadcastReceiver 在一段时间后停止接收

Why my BroadcastReceiver stop receiving after a while

我有一个 IntentService 可以做很长时间的工作,大约需要 15 分钟才能完成。从我的服务器获取新数据是一个同步过程。

当此服务启动时,我也启动了一个 activity,以显示进程。

此 activity 创建一个 BroadcastReceiver,拦截从服务发送的有关进程进度的消息。

如果我让应用程序继续工作,SO 会在一段时间后关闭屏幕。

当我再次打开屏幕时,大约15分钟后,服务已经完成,但进度似乎过时了。 BroadcastReceiver 已停止工作,activity 未收到我​​的 END OF SYNCHRONIZATION 消息。

问题是,在这条消息中,我再次启动主程序 activity,让用户再次使用该应用程序。

我该如何解决这个问题?

广播接收器不是用来做长时间工作的。

广播接收器的生命周期大约为 10-15 秒。

广播接收器的推荐或典型用途是

  • 启动服务
  • 祝酒
  • 开始Activity

在你的情况下,你应该从你的广播接收器启动一个服务,并在该服务中完成所有工作。

我用这个 http://developer.android.com/intl/pt-br/guide/components/services.html#Foreground 解决了。

我的服务

public class MyService extends Service {

    public interface MyCallback {
        void onProgress(int progress);
    }

    public class MyBinder {
        public MyService getService() {
            return MyService.this;
        }
    }

    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public void make(MyCallback callback) {

        Notification n = new Notification.Builder(this)
            .setContentTitle("Processing")
            .getNotification();

        startForeground(666 /*some ID*/, n);
        try {
            callback.onProgress(0);
            // do the hard sutff and report progress
            callback.onProgress(100); // report 100%
        } finally {
            stopForeground(true);
        }
    }
}

我的activity

public MyActivity extends Activity implements ServiceConnection, MyService.MyCallback {

    @Override
    protected onStart() {
        super.onStart();
        // 1 - bind service to this activity
        Intent i = new Intent(this, MyService.class);
        this.bindService(i, this, BIND_AUTO_CREATE);
    }

    @Override
    public void onServiceConnected(ComponentName componentName, final IBinder iBinder) {
        // 2 - when the service was binded, starts the process asynchronous
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                ((MyService.MyBinder) iBinder).getService().make(MyActivity.this);
                return null;
            }
        }.execute();
    }

    @Override
    public void onProgress(int progress) {
        // 3 - when to callback is fired, update the UI progress bar
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // call ProgressBar.setProgress(progress);
            }
        });
    }

}