keeping background service alive after user exit app

假装没事ソ 提交于 2019-12-17 18:38:20

问题


I'm trying to create a service that will do background jobs for me even after the user closes the app from the running processes menu(by shifting process out of the screen).

What I tried to do is create service in a different process by declaring it like this:

  <service
        android:name=".service.Service"
        android:enabled="true"
        android:icon="@drawable/ic_launcher"
        android:process=":my_process" >
  </service>

and the onStartCommand() is:

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

回答1:


According to the Android documentation you can achieve this behavior by using the attribute:

 android:isolatedProcess="true"

By the way, I know that it's not answering the question but it might help some people as well - lately, I found out about a great third-party lib that Evernote developers have created. Its name is Android-Job and its aim is to create jobs that run on different processes and can become active again even after a device reboot, it's amazing.




回答2:


Actually there are different kinds of services you can implement. Use a Service instead of IntentService. There you need to look at START_STICKY , START_NOT_STICKY and START_REDELIVER_INTENT you can keep your service running in background even if your activity dies. Android services also look at AIDL services




回答3:


For this you can use Handler and Runnable class

   @Override
    public void onCreate()
    {

        Toast.makeText(context, "SMS SERVICE START", Toast.LENGTH_SHORT).show();


        handler=new Handler();
        runnable=new Runnable() {
            @Override
            public void run()
            {

                    TASK();
                    handler.postDelayed(runnable,180000);
// 3min delay
            }
        };

        handler.postDelayed(runnable,180000);
        super.onCreate();
    }

This task run continuously 3min

public void TASK()
{
     //your task 

}



回答4:


Services were designed to run in the background, no need for a different process.

From the services documentation:

Once started, a service can run in the background indefinitely, even if the component that started it, is destroyed.

The service however, should stop itself, when its work is done. IntentService is the easiest way to start implementing a service.



来源:https://stackoverflow.com/questions/17767767/keeping-background-service-alive-after-user-exit-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!