发送接收广播过程
1,程序中调用Context的sendBroadcast(Iintent)方法
2,intent启动intent中的广播名 intent.setAction("com.song.123");
3,Manifest中找到哪个Receiver(广播接收器)接收此广播名<action android:name="com.song.123"/>,就把广播发送给那个接收器
程序效果:点击按钮,显示一条toast的广播信息
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.song"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".C48_Broadcast2Activity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver1">
<intent-filter >
<action android:name="com.song.123"/>
</intent-filter>
</receiver>
</application>
</manifest>
主Activity
package com.song;
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 C48_Broadcast2Activity extends Activity {
/** Called when the activity is first created. */
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//创建Intent对象
Intent intent=new Intent();
//设置Intent的Action属性
intent.setAction("com.song.123");
//如果只传一个bundle的信息,可以不包bundle,直接放在intent里
intent.putExtra("a","aaa");
//发送广播
sendBroadcast(intent);
}
});
}
}
广播接收器BroadcastReceiver
package com.song;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver1 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//只有一个bundle的消息,用intent.getStringExtra(key)取值就行
System.out.println("receiver1");
Toast.makeText(context,
"接收到的Intent的Action为:"+intent.getAction()
+"\n消息的内容是:"+intent.getStringExtra("a"),
5000).show();
System.out.println("接收到的Intent的Action为:"+intent.getAction()
+"\n消息的内容是:"+intent.getStringExtra("a"));
}
}
程序效果
