每当应用关闭时,服务都会停止。

7
每当我杀死我的应用程序时,START_STICKY在我的设备上无法工作。我的设备名称为Redmi Note 3 Pro,但每当我在android模拟器中运行相同的应用程序时,当我杀死应用程序时,它会重新启动服务,并且服务不会停止,直到我用stopService()方法停止它。
请帮忙解决。
问题已解决:
按照以下步骤操作: 设置 > 权限 > 自启动 然后打开我的应用程序的开关,完成!
我在此链接中找到了解决方案:Solution Link

使用ServiceConnection和服务绑定来保持服务不被销毁。 - Hemanth S
@HemanthSTobi 好的,我会尝试一下,谢谢你的帮助,非常感激。 - LEGEND MORTAL
3个回答

9
你需要在服务属性中的清单文件中添加"android:process=:any_name"。
例如,
      <service android:name=".MyService"
        android:process=":MyService"
        android:enabled="true"/>

以下是我的Service类的代码。
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);
}

}


我知道这可以通过在onTaskRemoved或onDestroy中使用AlarmManager来实现,只是忘记在这里分享了,感谢你的回答。 - LEGEND MORTAL
它对我没用,进程名称只是随机的吗?! - Keivan.k
我在Redmi手机上检查了这个问题,当我移除应用程序时,前台服务被终止,但是它会在5秒后重新启动前台服务,但是当我再次打开应用程序并从最近的应用中清除时,第二次它不会启动前台服务。有什么解决办法吗? - Anwar Zahid
@VivekKumar 是的。 <service android:name=".services.FlashService" android:enabled="true" android:exported="false" android:process=":anyname" android:foregroundServiceType="camera"/> </application> - Anwar Zahid
但我认为这是电池优化的问题。 - Anwar Zahid
显示剩余4条评论

6
在某些设备上(尤其是小米、华为和联想),您需要将您的应用程序添加到“受保护的应用程序”或“允许在后台运行的应用程序”列表中。如果您的应用程序不在该列表中,则即使您从onStartCommand()返回了START_STICKY,Android也不会自动重新启动您的服务(Service)。这是一项“节电功能”,不幸的是这给开发人员带来了很多问题!
请在Android设置的“电源管理”、“安全性”或“应用程序”下查找这些设置。
另请参见:

请解释一下您所说的“杀死我的应用程序”的含义。如果您强制关闭您的应用程序,则Service将不会被Android重新启动。这是有意为之的,如果您强制关闭应用程序,模拟器也不会重新启动。


2
感谢,它奏效了,我已经通过 设置 > 权限 > 自动启动 启用了自动启动,还在此链接中找到了解决方案:解决方案链接 - LEGEND MORTAL
前台服务怎么样? - Muhammad Babar
1
@MuhammadBabar,我不理解你的问题。通常情况下,Android 不会杀死前台 Service,但是在这种情况下,我假设如果 Android 杀死了你的前台 Service(无论什么原因),除非你的应用程序被添加到此应用程序列表中,否则它仍不会重新启动。 - David Wasser
1
@DavidWasser 谢谢,你回答了我的问题。 - Muhammad Babar

-1

代码可能会帮助你,在 HourlyService 类的 onStartCommand 方法中返回 START_STICKY

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

活动内部

 private HourlyService mHourlyService;
private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) iBinder;
        mHourlyService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBound = false;
    }
};

@Override
protected void onStart() {
    super.onStart();
    // Bind to LocalService
    Intent intent = new Intent(this, HourlyService.class);
    bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(mServiceConnection);
    mBound = false;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接