Friday, 7 June 2013

Start Activity or Service on boot Android


Hi  guys,

We have number of situations in our development that we want our service or our app should be run as soon as  Device Start, or after Boot Completed.

After boot completes the Android system broadcasts an intent with the action android.intent.action.BOOT_COMPLETED. And now all we need is an IntentReceiver, called a BroadcastReceiver, to listen and act on it.

So here is simple example where you can run your  Activity or Service as soon as device Start.
first create simple activity as  our favorite activity MainActivity :P

public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

       }
      

}


and Here its XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="156dp"
        android:text="App Main Page"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>


 And create simple service to show messages as it created and running etc

TestService.java

public class TestService extends Service {
       public TestService() {
       }

       @Override
       public IBinder onBind(Intent intent) {
              // TODO: Return the communication channel to the service.
              throw new UnsupportedOperationException("Not yet implemented");
       }
       @Override
       public void onCreate() {
              // TODO Auto-generated method stub
       Toast.makeText(getApplicationContext(), "Service Created",1).show();
              super.onCreate();
       }
      
      
       @Override
       public void onDestroy() {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Destroy",1).show();
              super.onDestroy();
       }
      
       @Override
       public int onStartCommand(Intent intent, int flags, int startId) {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Working",1).show();
              return super.onStartCommand(intent, flags, startId);
       }
}



Now when the device finishes booting up, our BroadcastReceiver will receive the BOOT_COMPLETED action in the onReceive() method which is where we’ll start our service


public class BootStartUpReciever extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {
              // TODO: This method is called when the BroadcastReceiver is receiving

              // Start Service On Boot Start Up
              Intent service = new Intent(context, TestService.class);
              context.startService(service);
             
              //Start App On Boot Start Up
              Intent App = new Intent(context, MainActivity.class);
              App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              context.startActivity(App);


       }
}


AndroidManifest.xml

Now we have to modify the AndroidManifest.xml file:

1) adding the permission to capture che event of the boot completed:
2) registering the Service:
3) And The receiver needs to be declared in the manifest, e.g. with the following entry:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bootstart"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bootstart.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
         <service
            android:name="com.example.bootstart.TestService"
            android:enabled="true"
            android:exported="true" >
        </service>

        <receiver
            android:name="com.example.bootstart.BootStartUpReciever"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

You can download complete example Here 

 Happy Codddding :)



No comments:

Post a Comment