我为长期运行的后台任务创建了服务。它是通过HandlerThread实现的。 (下面的示例)
对于应用程序而言,重要的是,只有在前一个任务完成后才能启动新任务。
任务完成后,广播将发送到活动。只有这样,用户才能开始新任务。
到目前为止,一切正常,除非活动进入后台。 broadcastReceiver已在onPause中注销。如果在活动的下一个onResume之前发送广播,则该消息将丢失。但是在onResume中,我们必须找出是否有未完成的任务。
是否有可靠的方法来确定服务是否仍很忙?
public class LongRunningService extends Service {
private HandlerThread thread;
private LongRunningServiceHandler longRunningServiceHandler;
private class LongRunningServiceHandler extends Handler {
public LongRunningServiceHandler(Looper l) {
super(l);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
default:
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
final Intent i = new Intent(LongRunningService.class.getName());
i.putExtra("STATUS", "finished");
LocalBroadcastManager.getInstance(LongRunningService.this).sendBroadcast(i);
}
}
public LongRunningService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
this.thread = new HandlerThread("UDPHandler", Process.THREAD_PRIORITY_BACKGROUND);
this.thread.start();
this.longRunningServiceHandler = new LongRunningServiceHandler(this.thread.getLooper());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Message msg = new Message();
msg.what = 1;
this.longRunningServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
}