我的 IntentService 有问题。每次我启动服务时,只要服务空闲,就会调用 onDestroy() 方法。我将我的服务设置为在前台运行,尽管如此,该服务仍然被立即杀死。我的应用程序中只有一个其他活动,它没有调用 stopService()。
阅读开发人员文档给我的印象是调用 startForeground() 将允许您的服务持续存在,即使在空闲时,除非对内存有非常高的需求,还是我读错了?
我的代码如下:
public class FileMonitorService extends IntentService {
public int mNotifyId = 273;
public FileMonitorService(){
super("FileMonitorService");
}
@Override
protected void onHandleIntent(Intent arg0) {
}
@Override
public void onDestroy() {
Toast.makeText(this, getText(R.string.toast_service_stop), Toast.LENGTH_SHORT).show();
stopForeground(true);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new Notification(R.drawable.icon, getText(R.string.notification_short), System.currentTimeMillis());
notification.flags|=Notification.FLAG_NO_CLEAR;
Intent notificationIntent = new Intent(this, FileMonitorActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_short),getText(R.string.notification_long), pendingIntent);
startForeground(mNotifyId, notification);
Toast.makeText(this, getText(R.string.toast_service_start), Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
}