In Android, broadcast is a very useful function. Broadcast can notify other broadcasts to accept this event. Such as insufficient power supply and poor signal.
Below I made a simple demo, first look at the activity
- package com.android.broadcasttest;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
-
- public class BroadcastTest extends Activity {
- public static final String NEW_LIFEFORM_DETECTED =
- "com.android.broadcasttest.NEW_LIFEFORM";
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- Button btn0 = (Button)findViewById(R.id.btn0);
- btn0.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- Intent it = new Intent(NEW_LIFEFORM_DETECTED);
- sendBroadcast(it);
- }
- });
- }
- }
A button is generated in this activity. When the button is pressed, a broadcast is sent through sendbroadcast.
Let's look at the broadcast receiver code:
- Package com. Android. broadcasttest;
-
- Import Android. content. broadcastreceiver;
- Import Android. content. context;
- Import Android. content. intent;
- Import Android. util. log;
- Import Android. widget. Toast;
-
- Public class mybroadcastreceiver extends broadcastreceiver {
- Public static final string burn =
- "Com. paad. Alien. Action. burn_it_with_fire ";
- Public mybroadcastreceiver (){
- Log. V ("broadcast_tag", "mybroadcast ");
- }
- @ Override
- Public void onreceive (context, intent ){
- // Todo auto-generated method stub
- Toast. maketext (context, "successfully received broadcast:", Toast. length_long). Show ();
- }
-
- }
In onreceive (), an action is performed when the broadcast is received.
We also need to register the handler in androidmanifest. xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.broadcasttest"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".BroadcastTest"
- 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=".MyBroadcastReceiver">
- <intent-filter>
- <action android:name="com.android.broadcasttest.NEW_LIFEFORM" />
- </intent-filter>
- </receiver>
- </application>
- <uses-sdk android:minSdkVersion="8" />
- </manifest>
The operator's Action defines the broadcast that the receiver can accept.