Java 如何创建始终运行的后台服务?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24077901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:03:16  来源:igfitidea点击:

How to create an always running background service?

javaandroidserviceandroid-activity

提问by user3686811

My question is how to create an always running background service. I created an IntentService which runs in background as long as the app is running. However, when app is killed, service is gone as well. What i want to create is to create a background service that always runs and posts notifications. (Similar to whatsapp, facebook or any other similar applications.)

我的问题是如何创建始终运行的后台服务。我创建了一个 IntentService,只要应用程序正在运行,它就会在后台运行。但是,当应用程序被杀死时,服务也会消失。我想要创建的是创建一个始终运行并发布通知的后台服务。(类似于 whatsapp、facebook 或任何其他类似的应用程序。)

When the notification is clicked, it should start the application as well.

单击通知时,它也应该启动应用程序。

How can i do it?

我该怎么做?

回答by busylee

You must start service using start command. And you must rewrite onStartCommmand function in service:

您必须使用 start 命令启动服务。并且您必须在服务中重写 onStartCommmand 函数:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

START_STIKYmeans that service will be restarted automamtically (http://developer.android.com/reference/android/app/Service.html#START_STICKY)

START_STIKY意味着服务将自动重启(http://developer.android.com/reference/android/app/Service.html#START_STICKY

If you use bindService function instead of startCommand, your service will stoped then all binded activitiess goes down.

如果您使用 bindService 函数而不是 startCommand,您的服务将停止,然后所有绑定的活动都将关闭。

More than that if you want to autostart your service after booting device you must implement BroadcastReceiverfor receiving ACTION_BOOT_COMPLETEDintent and handle this event for start service.

更重要的是,如果您想在启动设备后自动启动您的服务,您必须实现BroadcastReceiver接收ACTION_BOOT_COMPLETED意图并处理此事件以启动服务。

回答by Preethi Rao

the best to do this is create custom service that extends your service not intent Service. and start a separate thread in your service. start service in the launching of app One more important this dont bind it to any object cause service will be killed once your object destroyed. then onStartCommand() method return START_STICKY I will give you the sample implementation.

最好的方法是创建自定义服务来扩展您的服务而不是意图服务。并在您的服务中启动一个单独的线程。在应用程序启动时启动服务 更重要的是不要将它绑定到任何对象,因为一旦您的对象被破坏,服务就会被终止。然后 onStartCommand() 方法返回 START_STICKY 我会给你示例实现。

public class CustomService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    return START_STICKY;
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    // TODO Auto-generated method stub
     Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);

        //Restart the service once it has been killed android


        AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +100, restartServicePI);

}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    //start a separate thread and start listening to your network object
}

}

}

onTaskRemoved restarts your service after 100milli seconds once it is killed. START_STICKY doesnt work in kitkat. You have to implement onTAskRemoved. And one more thing if the user goes to app settings and stops your service then there is no way you can restart it

onTaskRemoved 在服务被终止后 100 毫秒后重新启动您的服务。START_STICKY 在 kitkat 中不起作用。您必须实现 onTAskRemoved。还有一件事,如果用户转到应用程序设置并停止您的服务,那么您将无法重新启动它

回答by Lazy Ninja

The following will do as long as your activity is around.

只要您的 Activity 存在,以下操作就会执行。

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

Unfortunately when your app is killed and the device runs out of resources it will kill it.
But if you want to keep your service running for days, make sure you are running your service in the foreground.

不幸的是,当您的应用程序被终止并且设备耗尽资源时,它将终止它。
但是,如果您想让您的服务运行数天,请确保您在前台运行您的服务。