栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android中的广播和广播接收器代码实例

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android中的广播和广播接收器代码实例

BroadcastReceiver不仅可以接收系统广播,也可接收自定义的广播
 
1.定义一个广播接收器
复制代码 代码如下:
public class MyReceiver extends BroadcastReceiver
{
         public MyReceiver()
         {
                   Log.i(TAG,"MyReceiver");
         }
       
         //可用Intent的getAction()区分接收到的不同广播
         @Override
         public void onReceive(Context arg0, Intent arg1)
         {
                   String action=intent.getAction();
                   //TO-DO LIST
         }
 
}

 
2.发送广播,定义好action标志,用Intent发送
复制代码 代码如下:
//实例化该BroadcastReceiver
MyReceiver mReceiver=new MyReceiver();
//设置唯一action,用Intent发送
Intent intent=new Intent();
intent.setAction(str);
sendBroadcast(intent);

3.注册只接收指定action的广播接收器
复制代码 代码如下:
IntentFilter filter1=new IntentFilter();
filter1.addAction(str);
registerReceiver(mReceiver,filter1);

4.取消该广播接收器
复制代码 代码如下:
unregisterReceiver(mReceiver);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/164394.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号