In android 4.4, swiping app out of recent tasks permanently kills application with its service . Any idea why?

狂风中的少年 提交于 2019-11-27 04:00:39

Got it. Its a bug in 4.4. I tried this and it worked perfectly fine(its a dirty workout though).

Just override this method -:

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

From this issue Foreground service killed when receiving broadcast after acitivty swiped away in task list

Here is the solution

In the foreground service:

@Override
public void onTaskRemoved( Intent rootIntent ) {
   Intent intent = new Intent( this, DummyActivity.class );
   intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
   startActivity( intent );
}

In the manifest:

<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"
/> 

In DummyActivity.java:

public class DummyActivity extends Activity {
    @Override
    public void onCreate( Bundle icicle ) {
        super.onCreate( icicle );
        finish();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!