- package com.amaker.broadcast;
- import android.app.Activity;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- /**
- * 1,点击按钮发送一个广播
- * 2,注册广播时有两种注册:一,在配置文件中静态注册 二、在代码中动态注册
- * 注意:注册方法写在:onResume里面,注销方法写在:onPause里面
- *
- */
- public class MainActivity extends Activity {
- private Button btn_send;
- public static final String MY_ACTION = "com.amaker.broadcast.MY_ACTION";
- MyReceiver r = new MyReceiver();
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btn_send = (Button) findViewById(R.id.button1);
- btn_send.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- send();
- }
- });
- }
- //发送一个广播
- void send(){
- Intent intent = new Intent(MY_ACTION);
- String msg = "我给你发了一个广播,是否收到?";
- intent.putExtra("msg", msg);
- sendBroadcast(intent);
- }
- //动态注册广播
- @Override
- protected void onResume() {
- super.onResume();
- IntentFilter filter = new IntentFilter();
- filter.addAction(MY_ACTION);
- registerReceiver(r, filter);
- }
- //注销广播
- @Override
- protected void onPause() {
- super.onPause();
- unregisterReceiver(r);
- }
- }
- package com.amaker.broadcast;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.widget.Toast;
- public class MyReceiver extends BroadcastReceiver{
- @Override
- public void onReceive(Context context, Intent intent) {
- String msg = intent.getStringExtra("msg");
- //收到广播,简单Toast显示一下
- Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
- }
- }
AndroidManifest.xml:
- "1.0" encoding="utf-8"?>
"" - package="com.amaker.broadcast"
- android:versionCode="1"
- android:versionName="1.0">
-
"8" /> -
"@drawable/icon" android:label="@string/app_name"> -
".MainActivity" - android:label="@string/app_name">
-
-
"android.intent.action.MAIN" /> -
"android.intent.category.LAUNCHER" /> -