我有下面的代码,我用来测试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