与之前的版本不同,在4.4中,即使正在运行后台服务,从最近的任务中滑动应用程序会永久杀死应用程序及其服务(如强制停止)。它显示0个进程1服务,但服务也不起作用。理想情况下,它不应该杀死后台服务,它不会在4.3之前的版本中。知道为什么会发生在4.4?
答案 0 :(得分:26)
知道了。这是4.4中的一个错误。我试过这个并且它工作得非常好(虽然这是一个肮脏的锻炼)。
只需覆盖此方法 - :
public void onTaskRemoved(Intent rootIntent) {
Log.e("FLAGX : ", ServiceInfo.FLAG_STOP_WITH_TASK + "");
Intent restartServiceIntent = new Intent(getApplicationContext(),
this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(
getApplicationContext(), 1, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
答案 1 :(得分:3)
从这个问题Foreground service killed when receiving broadcast after acitivty swiped away in task list
这是解决方案
在前台服务中:
@Override
public void onTaskRemoved( Intent rootIntent ) {
Intent intent = new Intent( this, DummyActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( intent );
}
在清单中:
<activity
android:name=".DummyActivity"
android:theme="@android:style/Theme.NoDisplay"
android:enabled="true"
android:allowTaskReparenting="true"
android:noHistory="true"
android:excludeFromRecents="true"
android:alwaysRetainTaskState="false"
android:stateNotNeeded="true"
android:clearTaskOnLaunch="true"
android:finishOnTaskLaunch="true"
/>
在 DummyActivity.java中:
public class DummyActivity extends Activity {
@Override
public void onCreate( Bundle icicle ) {
super.onCreate( icicle );
finish();
}
}