用于监听全局的广播消息
启动BroadcastReceiver的方法
Context的sendBroadcast() 发送普通广播
启动BroadcastReceiver的方法
Context的sendBroadcast() 发送普通广播
Context的sendOrderedBroadcast() 发送有序广播
public class MainActivity extends Activity
{
Button send;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取程序界面中的按钮
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// 创建Intent对象
Intent intent = new Intent();
// 设置Intent的Action属性
intent.setAction("org.crazyit.action.CRAZY_BROADCAST");
intent.putExtra("msg" , "简单的消息");
// 发送广播
sendBroadcast(intent);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="send" />
</LinearLayout>
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context , "接收到的Intent的Action为:"
+ intent.getAction()
+ "\n消息内容是:" + intent.getStringExtra("msg")
, 5000)
.show();
}
}
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="org.crazyit.action.CRAZY_BROADCAST" />
</intent-filter>
</receiver>
点击发送后
执行onReceiver()