In questo tutorial vedremo come avviare un Service al boot in Android.
Naturalmente, come primo passo, abbiamo bisogno del Service da avviare:
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.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:
2) registrare il Service:
3) registrare il nostro BroadcastReceiver affinché riceva l’evento di boot completed:
android:name=".BootCompletedReceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

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!
Very simple and efficient tutorial
Well done!
Great! Thankyou for the post.