标签:
BroadcastReceiver的两种注册方式:
1.静态注册:
(1)新建MyBroadcastReceiver.java文件,继承于BroadcastReceiver,重写onReceive方法即可,代码如下
public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String msg=intent.getStringExtra("msg"); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } }
(2)在AndroidManifest.xml文件中注册
<receiver android:name=".MyBroadcastReceiver" android:exported="false"> <intent-filter>
<action android:name="com.example.static" /> </intent-filter> </receiver>
(3)在MainActivity.java文件中
((Button)findViewById(R.id.btn)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setAction("com.example.static"); intent.putExtra("msg", "接收静态注册广播成功"); sendBroadcast(intent); } });
自此我们就完成了广播的静态注册
2.动态注册:
(1)在MainActivity.java文件中进行动态注册广播的定义
标签:
原文地址:http://www.cnblogs.com/grein/p/5596621.html