繁体   English   中英

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

[英]Why my BroadcastReceiver stop receiving after a while

我有一个做长期工作的IntentService ,大约需要15分钟。 这是从我的服务器获取新数据的同步过程。

当这个服务启动时,我也开始一个活动,以显示该进程。

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

如果我让应用程序完成它的工作,一段时间后SO关闭屏幕。

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

问题是,在此消息中,我再次启动主要活动,让用户再次使用该应用程序。

我怎么解决这个问题?

广播接收器不能进行长时间的工作。

广播接收器的寿命大约持续10-15秒。

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

  • 开始服务
  • 显示祝酒词
  • 开始活动

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

我解决了这个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);
        }
    }
}

我的活动

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);
            }
        });
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM