允许服务在后台永久运行

时间:2014-12-09 03:55:35

标签: android service wakelock background-service

我有一个基于webscokets的消息传递应用程序,它依赖于后台服务来发送和接收消息。一旦服务启动,我需要它在后台无限期运行,即使应用程序关闭以及手机进入睡眠模式。

在应用程序中,服务就像用户登录时一样启动,而onCreate方法则为startService(new Intent(LoggingIn.this, MessagingService.class));

如何设置我的服务以在后台永久运行?

private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service. Because we have bound to a explicit
            // service that we know is running in our own process, we can
            // cast its IBinder to a concrete class and directly access it.
            imService = ((MessagingService.IMBinder) service).getService();

            if (imService.isUserAuthenticated() == true) {
                // Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
                Intent i = new Intent(LoggingIn.this, MainActivity.class);
                startActivity(i);
                LoggingIn.this.finish();
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
            imService = null;
            Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /*
         * Start and bind the imService
         */
        startService(new Intent(LoggingIn.this, MessagingService.class));

...etc

2 个答案:

答案 0 :(得分:0)

在服务中的onStartCommand()方法中使用startForeground()

答案 1 :(得分:0)

你需要在onStartCommand中使用START_STICKY: http://developer.android.com/reference/android/app/Service.html#START_STICKY

然后您可以阅读此线程以在启动期间启动您的服务: Android -Starting Service at Boot Time

您需要在清单中为服务定义一个名称,使其在不同的线程中运行:android:process=":my_process"如果您关闭应用程序,它将继续在后台运行