How to run android service permanently like system service?

心不动则不痛 提交于 2020-01-06 12:17:22

问题


I want to run my Android service(real-time notification service) after application installed and force it to work even application closed. This service responsible for listening my real-time notification server, when notification received I create Android notification and maybe run my app, if it is closed. I assume that my way is not correct for this case and there is another way working with real-time notification. I will be grateful if you give some link or a small explanation.


回答1:


the better approach to listening my real-time notification server, you've to use GCM. here you can start reading about GCM. and if you want to implement it yourself you have to write a service yourself. ex:

    public class ListenerService extends Service{
     @Override
     public void onStartCommand(Intent intent, int flags, int startId){


       return START_STICKY; //this will restart your service even though the system kills
      }

   // you can write other listener service method inside the service
    }

but still I recommend you to use GCM or other cloud messaging services instead of writing your own.




回答2:


Extend the Android Service class in your class which you want to run in background always.Override the following method and return START_STICKY which makes your service to always run in background until you stop it.

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

If you need to do any long running task than create a seperate thread for it and use it inside the service because service runs on main thread.



来源:https://stackoverflow.com/questions/33991480/how-to-run-android-service-permanently-like-system-service

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