Android 在API级别25(牛轧糖)以上的设备上未使用START_STICKY重新启动服务

Android 在API级别25(牛轧糖)以上的设备上未使用START_STICKY重新启动服务,android,service,android-7.1-nougat,Android,Service,Android 7.1 Nougat,我的应用程序中有一个服务,在应用程序从最近的任务列表中删除后需要重新启动。API级别25及以下的服务将重新启动,但不适用于25及以上版本。请帮助我解决此问题,并想知道重新启动与所有操作系统版本兼容的服务的最佳方法 public class XMPPMainService extends Service { private static final String TAG = "XMPPMainService"; private static final int RECONNEC

我的应用程序中有一个服务,在应用程序从最近的任务列表中删除后需要重新启动。API级别25及以下的服务将重新启动,但不适用于25及以上版本。请帮助我解决此问题,并想知道重新启动与所有操作系统版本兼容的服务的最佳方法

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;
    }
}
清单文件:

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

在您的服务类中添加此代码:-

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

在服务类中添加以下代码:-

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