1、MainActivity.java
package com.t20.broadcastdemo; import com.example.broadcastdemo.R; import android.os.Bundle; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * 发送自定义全局广播 * @param v */ public void send(View v){ //1、准备意图 Intent intent=new Intent("com.t20.broadcast1"); //2、传值 String msg="同学们,9:30分下课!"; intent.putExtra("msg", msg);//第一个参数是key键,第二个是值 //3、发送广播 //无序广播 //sendBroadcast(intent); //有序广播 sendOrderedBroadcast(intent, null, null,null, 0, msg, null); //--------------------意图---权限--指定接收者------什么时候发广播--初始码---广播内容--一次性传大量数据 } /** * 定义一个静态广播接收器类,用于接收广播内容 * @author Administrator * */ public static class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub Log.i("本地广播器(自己)", "收到广播:"+getResultData()); } } }
2、AndroidMenifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.t20.broadcastdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 内部类广播(本地广播)BroadcastReceiver的静态注册(AndroidManifest.xml) --> <receiver android:name="com.t20.broadcastdemo.MainActivity$MyReceiver"> <!-- 注意是$符号,表示内部类 --> <intent-filter android:priority="1000"> <!-- 有序广播设置优先级:priority表示优先级(0-1000),默认是500 ,1000的优先级最高--> <action android:name="com.t20.broadcast1" /> </intent-filter> </receiver> </application> </manifest>