`

Service联合Broadcase更新UI

    博客分类:
  • UI
阅读更多
在Android中,异步更新UI,通常我们会选用Handler启动线程,或者sendMessage的方式,那么利用Service和广播也可以更新UI的,例子如下:

我们建立一个Service:
package com.andy
import android.app.Service;//引入相关包
import android.content.BroadcastReceiver;//引入相关包
import android.content.Context;//引入相关包
import android.content.Intent;//引入相关包
import android.content.IntentFilter;//引入相关包
import android.os.IBinder;//引入相关包
//继承自Service的子类
public class MyService extends Service{
        CommandReceiver cmdReceiver;
        boolean flag;
        @Override
        public void onCreate() {//重写onCreate方法
                flag = true;
                cmdReceiver = new CommandReceiver();
                super.onCreate();
        }
        @Override
        public IBinder onBind(Intent intent) {//重写onBind方法
                // TODO Auto-generated method stub
                return null;
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {//重写onStartCommand方法
                IntentFilter filter = new IntentFilter();//创建IntentFilter对象
                filter.addAction("wyf.wpf.MyService");
                registerReceiver(cmdReceiver, filter);//注册Broadcast Receiver
                doJob();//调用方法启动线程
                return super.onStartCommand(intent, flags, startId);
        }
        //方法:
        public void doJob(){
                new Thread(){
                        public void run(){
                                while(flag){
                                        try{//睡眠一段时间
                                                Thread.sleep(1000);
                                        }
                                        catch(Exception e){
                                                e.printStackTrace();
                                        }
                                        Intent intent = new Intent();//创建Intent对象
                                        intent.setAction("wyf.wpf.Sample_3_6");
                                        intent.putExtra("data", Math.random());
                                        sendBroadcast(intent);//发送广播
                                }                                
                        }
                        
                }.start();
        }        
        private class CommandReceiver extends BroadcastReceiver{//继承自BroadcastReceiver的子类
                @Override
                public void onReceive(Context context, Intent intent) {//重写onReceive方法
                        int cmd = intent.getIntExtra("cmd", -1);//获取Extra信息
                        if(cmd == Sample_3_6.CMD_STOP_SERVICE){//如果发来的消息是停止服务                                
                                flag = false;//停止线程
                                stopSelf();//停止服务
                        }
                }                
        }
        @Override
        public void onDestroy() {//重写onDestroy方法
                this.unregisterReceiver(cmdReceiver);//取消注册的CommandReceiver
                super.onDestroy();
        }        
}

建立一个activity

package com.andy;//声明包语句
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.view.View;//引入相关包
import android.view.View.OnClickListener;//引入相关包
import android.widget.Button;//引入相关包
import android.widget.TextView;//引入相关包
//继承自Activity的子类
public class Sample_3_6 extends Activity {
        public static final int CMD_STOP_SERVICE = 0;
        Button btnStart;//开始服务Button对象应用
        Button btnStop;//停止服务Button对象应用
        TextView tv;//TextView对象应用
        DataReceiver dataReceiver;//BroadcastReceiver对象
        @Override
    public void onCreate(Bundle savedInstanceState) {//重写onCreate方法
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);//设置显示的屏幕
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        tv = (TextView)findViewById(R.id.tv);
        btnStart.setOnClickListener(new OnClickListener() {//为按钮添加点击事件监听                
                        @Override
                        public void onClick(View v) {//重写onClick方法
                                Intent myIntent = new Intent(Sample_3_6.this, wyf.wpf.MyService.class);
                                Sample_3_6.this.startService(myIntent);//发送Intent启动Service
                        }
                });
        btnStop.setOnClickListener(new OnClickListener() {//为按钮添加点击事件监听        
                        @Override
                        public void onClick(View v) {//重写onClick方法
                                Intent myIntent = new Intent();//创建Intent对象
                                myIntent.setAction("wyf.wpf.MyService");
                                myIntent.putExtra("cmd", CMD_STOP_SERVICE);
                                sendBroadcast(myIntent);//发送广播
                        }
                });
    }        
        private class DataReceiver extends BroadcastReceiver{//继承自BroadcastReceiver的子类
                @Override
                public void onReceive(Context context, Intent intent) {//重写onReceive方法
                        double data = intent.getDoubleExtra("data", 0);
                        tv.setText("Service的数据为:"+data);                        
                }                
        }
        @Override
        protected void onStart() {//重写onStart方法
                dataReceiver = new DataReceiver();
                IntentFilter filter = new IntentFilter();//创建IntentFilter对象
                filter.addAction("wyf.wpf.Sample_3_6");
                registerReceiver(dataReceiver, filter);//注册Broadcast Receiver
                super.onStart();
        }
        @Override
        protected void onStop() {//重写onStop方法
                unregisterReceiver(dataReceiver);//取消注册Broadcast Receiver
                super.onStop();
        }
}

分享到:
评论

相关推荐

    android 服务和广播机制(service和broadcast)

    在Android系统中,服务(Service)和广播接收者(BroadcastReceiver)是两个核心组件,它们在后台执行任务和实现跨应用程序通信。本教程将深入探讨如何利用这两种组件来实现手机背景的定时切换功能,比如根据用户...

    broadcase encryption scheme

    摘要:本文主要关注的是在轻量级设备上实现的属性基广播加密(Attribute-Based Broadcast Encryption,简称ABBE)方案。这种加密技术对于智能卡、付费电视顶盒、SIM卡与智能手机等设备的安全应用至关重要。...

    YLReactiveCocoa:MVVM的ReactiveCocoa演示

    android : 四大组件(activity、service、broadcase receiver、content provider)和五大布局(LinearLayout、FrameLayout、RelativeLayout、AbsoluteLayout、TableLayout) 还有 java iOS : xib/storyboard + oc web...

    broadcast-js-sdk:cine.io 的 JavaScript SDK

    广播 JS SDK 用于发布和播放的 JavaScript SDK。 安装 < script src =" //cdn.cine.io/cineio-broadcast.js " > </ script > 用法 CineIO对象具有三个主要方法。... 使用您的公钥初始化 CineIO jssdk。...

    android 面试2

    22、简要解释一下activity、 intent 、intent filter、service、Broadcase、BroadcaseReceiver 答:activity呈现了一个用户可以操作的可视化用户界面 service不包含可见的用户界面,而是在后台无限地运行可以连接到...

    在Android中查看当前Activity是否销毁的操作

    (Activity,Service,BroadCase,ContentProvider) 的存在情况打印到当前目录的activity.txt文件中 然后进入打印文件搜索: ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities) 补充知识:打开另一个...

    一个让你掌握Android所有控件的Demo

    androidalarm:广播Broadcase 服务service,活动activity gesture:手势滑动实别,手势交互 时间控件 button,list,surfaceive绘图 菜单:上下文菜单,自定义菜单 对话框:多按钮,列表、单选、多选、进度、读取中、...

    android广播集合.txt

    - 权限描述:允许应用更新收集的电池统计信息。 - 使用场景:适用于电池管理应用、性能监测工具等。 8. **BLUETOOTH & BLUETOOTH_ADMIN** - 权限描述: - **BLUETOOTH**:允许应用连接已配对的蓝牙设备。 - **...

    浅谈Vue2.0父子组件间事件派发机制

    从vue1.x过来的都知道,在vue2.0中,父子组件间事件通信的$dispatch和$broadcase被移除了。官方考虑是基于组件树结构的事件流方式实在是让人难以理解,并且在组件结构扩展的过程中会变得越来越脆落。特别是在组件...

    Android监听来电和去电的实现方法

    TelephonyManager tManager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE); switch (tManager.getCallState()) { case TelephonyManager.CALL_STATE_RINGING: mIncomingNumber = ...

    第一节运算机网络基础知识.pdf

    "运算机网络基础知识" 一、什么是网络? 网络是指在必然区域内将两台或两台以上的运算机以必然的方式连接起来,起到共享文件、程序、数据的...4. 广播域(Broadcase Domain):发送数据给一个不明确的目标所阻碍的范围

Global site tag (gtag.js) - Google Analytics