Come avviare un servizio al boot in Android

In questo tutorial vedremo come avviare un Service al boot in Android.
Naturalmente, come primo passo, abbiamo bisogno del Service da avviare:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class StartAtBootService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
                // codice da eseguire quando il service viene creato
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
                // codice da eseguire quando il service viene fatto partire
    }

        @Override
    public void onDestroy() {
        super.onDestroy();
                // codice da eseguire quando il service viene distrutto
    }
}

Successivamente, creiamo il BroadcastReceiver in cui verrà richiamato il metodo onReceive al completamento del boot.
Al suo interno, lanciamo il Service che abbiamo precedentemente creato:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootCompletedReceiver extends BroadcastReceiver{
     @Override
     public void onReceive(Context context, Intent intent) {
             Intent serviceIntent = new Intent(context, StartAtBootService.class);
         context.startService(serviceIntent);
     }
}

Ora dobbiamo apportare alcune modifiche al file AndroidManifest.xml…

1) aggiungere il permesso che ci permette di ricevere l’evento di boot completato:

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

2) registrare il Service:

<service android:name=".StartAtBootService" ></service>

3) registrare il nostro BroadcastReceiver affinché riceva l’evento di boot completed:

<receiver
       android:name=".BootCompletedReceiver"
       android:enabled="true"
       android:exported="false" >
       <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
       </intent-filter>
</receiver>
android-tutorial , ,

3 responses to Come avviare un servizio al boot in Android


  1. Mat

    My brother suggested I would possibly like this blog. He was entirely right. This put up truly made my day. You cann’t imagine just how so much time I had spent for this information! Thanks!

  2. Patrick

    Very simple and efficient tutorial :)
    Well done!

  3. michael

    Great! Thankyou for the post.

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *

È possibile utilizzare questi tag ed attributi XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>