首页 > 代码库 > BroadcastReceive学习例程

BroadcastReceive学习例程

BroadcastReceive是Android四大核心组件之一,本质上是一种全局的监听器,用于监听系统全局的广播消息。

它用于接收程序所发出的Broadcast Intent,程序启动它只需两步:

(1)创建需要启动的ReceivecastReceiver的Intent

(2)调用Context的sendBroadcast()或sendOrderedBroastcast()方法来启动指定的BroadcastReceiver

当应用程序发出一个Broadcast Intent之后,所有匹配该Intent的BroadcastReceive都可能被启动

例程:

TestActivity.java  主页面Activity

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 TestActivity extends Activity {

	private Button sendButton;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		sendButton = (Button)findViewById(R.id.sendButton);
		sendButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_EDIT);
				TestActivity.this.sendBroadcast(intent);
				
			}
		});
		
	}
}
TestReceiver.java   重写BroadcastReceiver的onReceive方法

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class TestReceiver extends BroadcastReceiver {
	
	public TestReceiver(){
		System.out.println("TestReceive");
	}
	@Override
	public void onReceive(Context context, Intent intent) {
		System.out.println("onReceive");
		
	}

}

AndriodManifest.xml  配置指定BroadcastReceiver能匹配的Intent

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="mars.testbc.TestActivity"
            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 = ".TestReceiver">
            <intent-filter >
                <action android:name="android.intent.action.EDIT"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

结果:点击主页面的Button(两次)



onReceive()方法执行完后,BroadcastReceive的实例就会被销毁。

BroadcastReceive学习例程