【问题标题】:Android Service stops after the app is killedAndroid 服务在应用程序被杀死后停止
【发布时间】:2017-04-09 19:18:09
【问题描述】:

我想创建一个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));

清单

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

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

【问题讨论】:

    标签: android service android-service


    【解决方案1】:

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

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

    【讨论】:

    • 我的手机太残忍了,在应用关闭的那一刻,它一直在杀死前台服务。我试过这个,这也失败了:(使用 Oppo A3S
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多