zoukankan      html  css  js  c++  java
  • Android开发--Service和Activity通过广播传递消息

      Android的Service也运行在主线程,但是在服务里面是没法直接调用更改UI,如果需要服务传递消息给Activity,通过广播是其中的一种方法:

      一、在服务里面发送广播

        通过intent传送数据、通过setAction 设置Activity接收广播时要过滤的动作名   

     Intent intent = new Intent();
     intent.putExtra("key", "test");
     intent.setAction("location.reportsucc");
     sendBroadcast(intent);

      

      二、在Activity中创建内部类做为广播接收器,需实现BroadcastReceiver

     //内部类,实现BroadcastReceiver
        public class LocationReceiver extends BroadcastReceiver {
            //必须要重载的方法,用来监听是否有广播发送
            @Override
            public void onReceive(Context context, Intent intent) {
                String intentAction = intent.getAction();
                if (intentAction.equals("location.reportsucc")) {
                    
                }
            }
        }

      三、在Activity创建时注册广播接收器,

    filter.addAction值必须和服务里面注册的Action名称一致
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
    
     
            locationReceiver = new LocationReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("location.reportsucc");
            registerReceiver(locationReceiver, filter);
        }

      四、最后记住在不需要广播接收器的时候,卸载广播接收器。例如在Activity销毁时卸载广播接收器

      

        @Override
        protected void onDestroy() {
            unregisterReceiver(locationReceiver);
            super.onDestroy();
        }

        总结:通过发送广播,是一种实现了服务和活动之间互相通信的方式。

        

  • 相关阅读:
    day40_jQuery学习笔记_01
    jQuery选择什么版本 1.x? 2.x? 3.x?
    6个关于dd命令备份Linux系统的例子
    快速掌握grep命令及正则表达式
    Linux下删除乱码或特殊字符文件
    在 Linux 中永久修改 USB 设备权限
    CentOS 7 中 hostnamectl 的使用
    申请红帽企业版Linux开发者订阅
    CentOS6 下rsync服务器配置
    Centos6下DRBD的安装配置
  • 原文地址:https://www.cnblogs.com/firebet/p/13963792.html
Copyright © 2011-2022 走看看