【发布时间】:2016-12-03 00:28:16
【问题描述】:
我正在尝试保持对屏幕开/关变化做出反应的服务。该服务会在一段时间内完美运行,但最终它会被杀死。我现在正在尝试使用 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;
}
}
【问题讨论】:
-
我有类似的问题,在我的情况下,我不得不保持闪光灯亮着,但它在几秒钟内停止了,我发现唯一可行的选择是在意图服务中使用另一个服务并运行它服务作为前台服务,这解决了问题。如果您希望我发布更多详细信息,请告诉我
-
嗨@user2548816,我知道已经有一段时间了,但我很想听听您的解决方案。你能详细说明一下吗?
标签: android