我需要一个只能由用户停止的长时间运行服务。我为前台服务编写代码,一段时间后它停止工作。我注意到的一件事是,当其他应用程序(信使,通知)使用手机网络时它会停止工作。
服务是什么,它从网络获取信息,并在出现所需数据时发出通知。
以下是代码片段:
的onCreate
public void onCreate() {
// The service is being created
MyService.noticedModes.clear();
broadcaster = LocalBroadcastManager.getInstance(this);
Notification.Builder builder = new Notification.Builder(this)
// ....
Notification notification;
Intent targetIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
if (Build.VERSION.SDK_INT < 16)
notification = builder.getNotification();
else
notification = builder.build();
startForeground(1244, notification);
}
onStartCommand
public int onStartCommand(Intent intent, int flags, int startId) {
try {
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
//AsyncTask starts
}
});
}
}, 0, CHECK_INTERVAL);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WAKELOCK_TAG");
wl.acquire();
return START_REDELIVER_INTENT;
}catch (Exception e){
return START_REDELIVER_INTENT;
}
}
的onDestroy
public void onDestroy() {
wl.release();
super.onDestroy();
}
* UPD:* 它会自动停止工作,不会抛出任何东西。可能Android正在扼杀它。所以,我需要帮助才能找到让它永远运行的方法,直到用户自己停止它为止。
此外,在终止后它甚至不通过onDestroy()