每当应用被杀死时服务停止

LEG*_*TAL 1 android android-service android-studio

START_STICKY每当我杀死我的应用程序后就无法在我的设备上工作,而服务无法再次启动,我的设备名称为Redmi Note 3 Pro,但是每当我在android模拟器中运行相同的应用程序时,当我杀死该应用程序并服务直到我通过stopService()方法将其停止时才停止

请帮帮我

问题解决了

完成此操作:

设置>权限>自动启动, 然后打开我的应用程序的开关,然后完成!

我在此链接中找到了解决方案:解决方案链接

Viv*_*mar 7

您需要在服务属性下的清单中添加“android:process=:any_name”。

例如,

      <service android:name=".MyService"
        android:process=":MyService"
        android:enabled="true"/>
Run Code Online (Sandbox Code Playgroud)

下面是我的服务类的代码。

public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public void onCreate() {
    super.onCreate();
    Log.e("onCreate", "onCreate");
    Toast.makeText(AppController.getInstance(),"Created",Toast.LENGTH_SHORT).show();
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("servicedestroy", "servicedestroy");
    Toast.makeText(AppController.getInstance(),"service destroy",Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
                              @Override
                              public void run() {

                                  new Handler(Looper.getMainLooper()).post(new Runnable() {
                                      @Override
                                      public void run() {
                                          Toast.makeText(AppController.getInstance(),"Running",Toast.LENGTH_SHORT).show();
                                      }
                                  });


                              }

                          },
            0,
            5000);

    return START_STICKY;
}

@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);
}
Run Code Online (Sandbox Code Playgroud)

}


Dav*_*ser 5

在某些设备(尤其是小米,华为,联想)上,您需要将您的应用添加到“受保护的应用”或“允许在后台运行的应用”列表中。如果您的应用程序不在列表中,Android将不会自动重启你的Service,即使你已经返回START_STICKYonStartCommand()。不幸的是,这是一个“省电功能”,给开发人员带来了很多问题!

在电源管理,安全性或应用程序下的Android设置中查找这些设置。

也可以看看:

还请解释“杀死我的应用程序”的含义。如果您强行关闭应用程序,则ServiceAndroid不会重新启动。这是故意的,并且如果您强制关闭应用程序,也不会在模拟器上重新启动它。

  • 谢谢,我的工作正常,我已通过**设置&gt;权限&gt;自动启动**启用了自动启动功能,我在此链接中获得了解决方案:[解决方案链接](/sf/answers/2748866641/) (2认同)