Monday, February 6, 2012

Start Activity from Broadcast Recevier


Some time we need to start an Activity from Broadcast Receiver..
how can we achieve this i am going to write step by step.

So lets create a small App to do this things 

-------------------------------------------
App Name: BReceiver2Activity
Package Name: com.rdc
Android SDK: Android SDK 2.2 / API 8
-------------------------------------------

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) {

Toast.makeText(context, "MyReceiver Started",
Toast.LENGTH_SHORT).show();
Log.v("Info Message", "in Broadcast receiver");
Intent myIntent=new Intent(context,MyActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}

}



MyActivity.java
package com.rdc;

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

public class MyActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

}
}


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"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:layout_weight="0.14" />
</LinearLayout>


AndroidManifest.xml
<?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="8" />

<application
android:icon="@drawable/icon"
android:label="@string/app_name">

<activity
android:enabled="true"
android:name=".MyActivity">
<intent-filter>
<action android:name="com.rdc.MyActivity">
</action>
</intent-filter>
</activity>

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

</application>
</manifest>

Now Reboot Emulator, Activity will appear on start-up.

You can download source code here: BReceiver2Activity

cheers!!

I'd love to hear your thoughts!!

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home