![](/img/trans.png)
[英]broadcastreceiver within android activity is not receiving intents after a while
[英]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.