本文共 3080 字,大约阅读时间需要 10 分钟。
系统开始重启会发送开机重启广播,电量低的时候会发送电量低的广播,广播注册有2种:系统说明文件xml注册和Java代码注册,前者是静态注册(全局注册)后者是动态注册(依赖于当时组建,组件销毁就收不到广播了)。
Activity.java
package com.sxt.day07_04;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;public class MainActivity extends Activity { MyReceiver2 mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerReceiver(); setListener(); } private void setListener() { sendBroadcast1ClickListener(); sendBroadcast2ClickListener(); } private void sendBroadcast2ClickListener() { findViewById(R.id.btnSendBroadcast_2).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent("com.sxt.day07_04.MyReceiver2");// intent.putExtra("key", "hello android!"); sendBroadcast(intent); } }); } private void sendBroadcast1ClickListener() { findViewById(R.id.btnSendBroadcast_1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent("com.sxt.day07_04.MyReceiver1"); intent.putExtra("key", "hello java!"); sendBroadcast(intent); } }); } //java类注册的广播接收者 private void registerReceiver() { mReceiver=new MyReceiver2(); IntentFilter filter=new IntentFilter();//意图过滤器 filter.addAction("com.sxt.day07_04.MyReceiver2");//广播的字符串 registerReceiver(mReceiver, filter); } class MyReceiver2 extends BroadcastReceiver{ @Override //收到广播执行的方法 public void onReceive(Context context, Intent intent) { Log.i("main","MyReceiver2.onReceive():"+intent.getStringExtra("key")); } } @Override protected void onDestroy() { super.onDestroy(); //Activity退出的时候取消广播的注册,释放资源. unregisterReceiver(mReceiver); }}
广播1.java
package com.sxt.day07_04;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class MyReceiver1 extends BroadcastReceiver { @Override //收到广播后执行的方法 public void onReceive(Context context, Intent intent) { Log.i("main","MyReceiver1.onReceive():"+intent.getStringExtra("key")); }}
系统描述文件:
注册全局广播接收者 广播接收者类 广播的字符串是这个就可以接收广播
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/4890767.html,如需转载请自行联系原作者