IntentServiceに問題があります。サービスを開始するたびに、サービスがアイドル状態になるとすぐにonDestroy()メソッドが呼び出されます。フォアグラウンドで実行するようにサービスを設定しましたが、それにもかかわらず、サービスはすぐに強制終了されます。アプリケーションには他に1つのアクティビティしかなく、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);
}
}