2

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);
}   
  }
4

1 に答える 1

4

Serviceの代わりに通常の使用を検討する必要がありますIntentServiceIntentServiceやるべきことがある間、走り続けるように設計されています。メソッドが終了するonStartCommandと、停止しようとします。

ドキュメントを参照してください:

クライアントはstartService(Intent)呼び出しを介してリクエストを送信します。サービスは必要に応じて開始され、ワー​​カースレッドを使用して各インテントを順番に処理し、作業がなくなると自動的に停止します。

(エンファシスマイン)

于 2011-11-07T18:10:09.033 に答える