Android -Starting Service at Boot Time

后端 未结 9 1762
一个人的身影
一个人的身影 2020-11-22 16:12

I need to start a service at boot time. I searched a lot. They are talking about Broadcastreceiver. As I am new to android development, I didn\'t get a clear picture about s

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 16:44

    It's possible to register your own application service for starting automatically when the device has been booted. You need this, for example, when you want to receive push events from a http server and want to inform the user as soon a new event occurs. The user doesn't have to start the activity manually before the service get started...

    It's quite simple. First give your app the permission RECEIVE_BOOT_COMPLETED. Next you need to register a BroadcastReveiver. We call it BootCompletedIntentReceiver.

    Your Manifest.xml should now look like this:

    
     
     
      
       
        
       
      
      
     
    
    

    As the last step you have to implement the Receiver. This receiver just starts your background service.

    package com.jjoe64;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    
    import com.jjoe64.BackgroundService;
    
    public class BootCompletedIntentReceiver extends BroadcastReceiver {
     @Override
     public void onReceive(Context context, Intent intent) {
      if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
       Intent pushIntent = new Intent(context, BackgroundService.class);
       context.startService(pushIntent);
      }
     }
    }
    

    From http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html

提交回复
热议问题