Page 80

Android Programming Cookbook

72 / 143

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="This Activity does nothing at all. But an auto-start service has just â&#x2020;?started!" android:textColor="#272727" android:textSize="20dp" /> </LinearLayout>

Actually, this activity will not do anything concerning the service that starts on boot. All the logic regarding the service is explained in the next lines.

4.3

Creating the source code of the BroadcastReceiverOnBootComplete Service

Add a new Java class inside src/com.javacodegeeks.androidserviceonbootexample/ so that we are going to have the src/com.javacodegeeks.androidserviceonbootexample/BroadcastReceiverOnBootComp lete.java file and paste the code below. BroadcastReceiverOnBootComplete.java package com.javacodegeeks.androidserviceonbootexample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BroadcastReceiverOnBootComplete extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) { Intent serviceIntent = new Intent(context, AndroidServiceStartOnBoot.class); context.startService(serviceIntent); } } }

We have just created a BroadcastReceiver that will receive the ACTION_BOOT_COMPLETED intent. This means that when we boot up our device this class will "catch" the event and start the AndroidServiceStartOnBoot service.

4.4

Creating the source code of the AndroidServiceStartOnBoot Service

Add a new Java class inside src/com.javacodegeeks.androidserviceonbootexample/ so that we are going to have the src/com.javacodegeeks.androidserviceonbootexample/AndroidServiceStartOnBoot.java file and paste the code below. AndroidServiceStartOnBoot.java

SKY MAGZ  

This is Yahya Christian School Magazine

Read more
Read more
Similar to
Popular now
Just for you