Android start service using broadcast receiver

Spike picture Spike · Jun 11, 2013 · Viewed 10.7k times · Source

I am implementing the following code, in which I want to start a service using broadcast receiver. The toast in the broadcast receiver is working fine but the service is not executing. Can anyone tell me where I went wrong?

MyReceiver.class
public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        //Toast.makeText(arg0, "Service", Toast.LENGTH_LONG).show();
        Intent myIntent = new Intent(arg0,MyS.class);
        arg0.startService(myIntent);
    }
}


MyS.class
public class MyS extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }
}


AndroidManifest.xml

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
       <service android:enabled="true"
           android:name=".MyS" >
           <intent-filter>
               <action android:name="com.test.p.MyS" >
               </action>
           </intent-filter>
       </service>

       <receiver android:enabled="true"
           android:name=".MyReceiver" >
           <intent-filter>
               <action android:name="android.intent.action.BOOT_COMPLETED"/>
           </intent-filter>
       </receiver>
    </application>

</manifest>

Answer

nesimtunc picture nesimtunc · Jun 12, 2013

In your activity, create a BroadcastReceiver variable

    private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
               // start your service right here... 
        }
    };

and onCreate or onResume events of Activity you should register for that BroadcastReceiver

super.registerReceiver(mBootCompletedReceiver, new IntentFilter("android.intent.action.BOOT_COMPLETED"));

and onDestory or onStop or onPause whatever you in situation should unregister this BroadcastReceiver for not receiving this updates anymore.

super.unregisterReceiver(mBootCompletedReceiver);