应用程序被终止后 Android 服务停止

2023-12-02

我想创建一个service即使应用程序从任务管理器关闭,它也会运行。我创建了一个服务,然后记录一条消息以检查它是否正在运行,我注意到它仅在应用程序正在运行或在前台运行时才有效。

服务等级:

public class CallService extends Service {

    private final LocalBinder mBinder = new LocalBinder();
    protected Handler handler;

    public class LocalBinder extends Binder {
        public CallService getService() {
            return CallService .this;
        }
    }

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

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TESTINGSERVICE", "Service is running");
    }
}

从我的 MainActivity 启动服务:

@Override
protected void onCreate(Bundle savedInstanceState) {
   ...
   startService(new Intent(this, CallService.class));

Manifest

<application>
   ...
   <service
      android:name=".activities.services.CallService">
   </service>
</application>

我必须做出哪些改变?谢谢各位


在您的服务中,添加以下代码。

@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);
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

应用程序被终止后 Android 服务停止 的相关文章

随机推荐