How to launch service on boot complete android?

JackTurky picture JackTurky · Sep 27, 2012 · Viewed 7.4k times · Source

I've read some tutorial on launch service on boot. What I've done is:

In manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" >
</uses-permission>

<receiver android:name="my.package.ServiceStartup" >
   <intent-filter>
       <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
</receiver>

CODE:

public class ServiceStartup extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
           @Override
           public void run() {
               Intent dialogIntent = new Intent(getBaseContext(), MyActivity.class);
               dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
               getApplication().startActivity(dialogIntent);
           }
        }, 10000);
    }
}

In this way, if i reboot my device and go to setting in active applications, my service is not launched. What can I do? Where I make error? thanks!!

Answer

harshit picture harshit · Sep 27, 2012

You want to start activity or service. In case of service, you will have to call startService(). Like:

getApplication().startService(new Intent(this, MyService.class));