私はasynctaskのライフサイクルをテストするためにこのコードを使用しています。私がしたいのは、アプリケーションがユーザーによって強制的に閉じられていてもasynctaskを終了させることです。毎秒進捗をインクリメントする通知を表示します。 asynctaskはフラグメントから呼び出されます。しかし、すべてのアプリを押して強制終了してアプリを強制終了すると、通知は停止し、それ以降は増分されません。以下の私のコードを見てください。Android:アプリケーションが終了してもasynctaskを維持する
これが該当するのですか、間違っていますか?
また、私がasynctaskを使用している理由は、ユーザーができる限りタスクをキャンセルできるようにするためです。 IntentServiceでこれを行うことはできないと思いますか? (私がこれに間違っているなら私を訂正してください)。
ありがとうございました。
更新:私は今、@John Wickと@Abishekの提案したフォアグラウンドサービスを試みています。しかし、私はそれが望むようにサービスを停止することはできません。停止をクリックすると、ループが始まり、停止しません。
パブリッククラスForegroundServiceは、サービスを拡張{
boolean isCancelled = false;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("Start")) {
Log.d("Action", "Start");
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction("Start");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Intent closeIntent = new Intent(this, ForegroundService.class);
closeIntent.setAction("Stop");
PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Truiton Music Player");
builder.setTicker("Truiton Music Player");
builder.setContentText("My Music");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
builder.setContentIntent(pendingIntent);
builder.addAction(android.R.drawable.ic_media_pause, "Stop", pCloseIntent);
startForeground(1, builder.build());
for (int i = 0; i < 10; i++) {
Log.d("Service", String.valueOf(i));
builder.setProgress(9, i, false);
if (isCancelled) {
builder.setContentTitle("Cancelled");
builder.setContentText("");
builder.setProgress(0, 0, false);
builder.mActions.clear();
manager.notify(1, builder.build());
} else {
if (i == 9) {
builder.setContentTitle("Done");
builder.setContentText("");
builder.setProgress(0, 0, false);
manager.notify(1, builder.build());
} else {
manager.notify(1, builder.build());
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
stopForeground(true);
} else {
Log.d("Action", "Start");
isCancelled = true;
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
}
あなたのアプリが –
近くにあり、あなたが独立してアプリの完成に努めたい場合は、サービス(ない意向サービス)が必要ですライフサイクル。 – PPartisan