Sunday, April 1, 2012

Start BroadcastReceiver from Activity

Some time we need to start a service from Android Activity..
how can we achieve this i am going to write step by step.

We will create very simple app to do this work
 -------------------------------------------
App Name: Activity2BReceiver
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------


MyActivity.java
  
package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MyActivity extends Activity {   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("Debug", "Activity has been started..");
    }
}

Then Create a Broadcast Receiver

MyReceiver.java
  
package com.rdc;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  Log.v("Debug", "SMS Broadcast Receiver has been started..");
  Toast.makeText(context, "BReceiver is watching ur message..", 
    Toast.LENGTH_SHORT).show();

 }

}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>


Don't forget to make entry in "Manifest" file for Receiver
  
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />
 <uses-permission android:name="android.permission.RECEIVE_SMS">
 </uses-permission>
 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".MyActivity"
   android:label="@string/app_name">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
  <receiver android:name="com.rdc.MyReceiver">

   <intent-filter>
  <action android:name="android.provider.Telephony.SMS_RECEIVED" />
   </intent-filter>
  </receiver>

 </application>
</manifest>

Run this app and send message from another mobile/emulator, Receiver will notify you about new sms
See below output screens tensted on Emulator and Real Device


You can download the complete source code zip file here : Activity2BReceiver


I'd love to hear your thoughts!

No comments:

Post a Comment