Service not restarting using START_STICKY on devices above API Level 25(Nougat)

我们两清 提交于 2021-02-08 07:45:22

问题


I have got a service in my app which needs to be restarted after app removed from recent task list. Service restarts for API level 25 and below but not for 25 and above versions.Please help me with this issue and would like to know the best way to restart a service which is compatible to all OS versions.

public class XMPPMainService extends Service {

    private static final String TAG = "XMPPMainService";

    private static final int RECONNECT_TRY_INTERVAL_MS = 900; // 5 Seconds

    private PendingIntent pendingIntent;


    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, " onCreate ");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.LOGD(TAG, "onDestroy: ");
        XMPPManager.shutdown();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        XMPPManager.getInstance(getApplicationContext());
        return START_STICKY;
    }
}

Manifest file:

<service
        android:name="com.chatmodule.xmpp.XMPPMainService"
        android:enabled="true"
        android:stopWithTask="false"
        android:exported="false" />`

回答1:


Add this code in your service class:-

@Override
public void onTaskRemoved(Intent rootIntent){
    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);
}


来源:https://stackoverflow.com/questions/45347884/service-not-restarting-using-start-sticky-on-devices-above-api-level-25nougat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!