我正在尝试保持一项响应屏幕开/关变化的服务运行。该服务会在一段时间内完美地工作,但最终会被杀死。我现在尝试使用startForeground()来保持进程的活跃状态,但它似乎仍然会死亡。我知道没有办法永远保持进程的不间断运行,但我觉得我肯定做错了什么,因为添加startForeground()并没有为进程带来额外的生命周期。此外,顺便提一下,Logcat会抱怨有一个泄漏,因为unregisterReceiver()没有被调用(除非由用户手动按下按钮)...但是,由于我想要完成的任务性质,接收器需要一直运行,直到明确停止。
有什么建议吗?
相关代码:
public class UpdateService extends IntentService {
public UpdateService() {
super(null);
}
@Override
protected void onHandleIntent(Intent intent) {
final int myID = 1234;
Intent notificationintent = new Intent(this, Main.class);
notificationintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notificationintent, 0);
Notification notice = new Notification(R.drawable.icon_image, "***********", System.currentTimeMillis());
notice.setLatestEventInfo(this, "*************", "***********", pendIntent);
notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);
boolean screenOn = intent.getBooleanExtra("screen_state", false);
// Blah Blah Blah......
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}