Android服务在应用程序被杀死后停止

标签 android service android-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));

list

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

关于Android服务在应用程序被杀死后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310855/

相关文章:

android - GAE 从数据存储中读取

android - onClick 函数在 android studio 中不起作用

java - 有没有一种有效的方法来重构这个 Android SQLite 数据库处理程序?

objective-c - osx - 如何实现没有可见 UI 的 OSX 服务?

android - 如何检测 Android 服务/后台应用程序中的用户 Activity/不活动?

android - 在 Android 中通过 Retrofit 库使用 API

c++ - 在模块列表中缺少应用程序的服务上进行 VS2010 C++ 远程调试

android - LocalBroadcastManager 未在 Activity 中接收广播

android - 权限拒绝 : startForeground requires android. 权限.FOREGROUND_SERVICE

android - 在纯服务应用程序中使用 SpeechRecognizer。在主线程上运行代码