Android Service和广播联合更新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 = newCommandReceiver();
             super.onCreate();
       }
       @Override
       public IBinder onBind(Intent intent){//重写onBind方法
              // TODO Auto-generated methodstub
              return null;
       }
       @Override
       public int onStartCommand(Intent intent, intflags, int startId) {//重写onStartCommand方法
              IntentFilter filter = newIntentFilter();//创建IntentFilter对象
             filter.addAction("wyf.wpf.MyService");
              registerReceiver(cmdReceiver,filter);//注册Broadcast Receiver
             doJob();//调用方法启动线程
              returnsuper.onStartCommand(intent, flags, startId);
       }
       //方法:
       public void doJob(){
              newThread(){
                     publicvoid run(){
                           while(flag){
                                  try{//睡眠一段时间
                                        Thread.sleep(1000);
                                  }
                                  catch(Exceptione){
                                        e.printStackTrace();
                                  }
                                  Intent intent = newIntent();//创建Intent对象
                                 intent.setAction("wyf.wpf.Sample_3_6");
                                  intent.putExtra("data",Math.random());
                                 sendBroadcast(intent);//发送广播
                           }                          
                    }
                    
              }.start();
       }      
       private class CommandReceiver extendsBroadcastReceiver{//继承自BroadcastReceiver的子类
              @Override
              public void onReceive(Contextcontext, 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;
       ButtonbtnStart;//开始服务Button对象应用
       Button btnStop;//停止服务Button对象应用
       TextView tv;//TextView对象应用
       DataReceiverdataReceiver;//BroadcastReceiver对象
       @Override
    public void onCreate(BundlesavedInstanceState) {//重写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(newOnClickListener() {//为按钮添加点击事件监听             
                    @Override
                     publicvoid 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(newOnClickListener() {//为按钮添加点击事件监听      
                    @Override
                     publicvoid onClick(View v) {//重写onClick方法
                           Intent myIntent = newIntent();//创建Intent对象
                          myIntent.setAction("wyf.wpf.MyService");
                           myIntent.putExtra("cmd",CMD_STOP_SERVICE);
                           sendBroadcast(myIntent);//发送广播
                    }
              });
    }      
       private class DataReceiver extendsBroadcastReceiver{//继承自BroadcastReceiver的子类
              @Override
              public void onReceive(Contextcontext, Intent intent) {//重写onReceive方法
                     doubledata = intent.getDoubleExtra("data", 0);
                    tv.setText("Service的数据为:"+data);                   
              }             
       }
       @Override
       protected void onStart(){//重写onStart方法
              dataReceiver = newDataReceiver();
              IntentFilter filter = newIntentFilter();//创建IntentFilter对象
             filter.addAction("wyf.wpf.Sample_3_6");
             registerReceiver(dataReceiver, filter);//注册BroadcastReceiver
             super.onStart();
       }
       @Override
       protected void onStop(){//重写onStop方法
             unregisterReceiver(dataReceiver);//取消注册BroadcastReceiver
             super.onStop();
       }

}



相关文章
|
19天前
|
Android开发
Android 11 添加Service服务SELinux问题
Android 11 添加Service服务SELinux问题
42 1
|
1月前
|
消息中间件 安全 数据处理
Android为什么不能在子线程更新UI
Android为什么不能在子线程更新UI
29 0
|
19天前
|
Android开发
Android Service Call /dev/xxx SELinux
Android Service Call /dev/xxx SELinux
16 1
|
1天前
|
Android开发 数据库管理
Android如何在Activity和Service之间传递数据
Android如何在Activity和Service之间传递数据
|
4天前
|
前端开发 Java Android开发
Android UI底层绘制原理
Android UI底层绘制原理
11 0
|
5天前
|
Android开发
Android Service的两种使用方法
Android Service的两种使用方法
11 2
|
19天前
|
Java Android开发
Android Mediatek 禁用拨号应用的部分UI显示
Android Mediatek 禁用拨号应用的部分UI显示
12 0
|
28天前
|
编解码 Android开发 UED
安卓UI/UX设计原则:打造引人入胜的用户体验
【4月更文挑战第13天】本文探讨了安卓UI/UX设计的关键原则,包括一致性、简洁性、反馈、清晰性、效率和适应性。一致性要求视觉和行为保持一致,利用系统UI;简洁性减少用户行动,简化导航;反馈需即时且明确;清晰性强调表达清晰,布局有序;效率关注性能优化和任务简化;适应性涉及多设备适配和用户多样性。遵循这些原则,可创建出色应用,提供无缝用户体验。设计应持续迭代,适应技术发展和用户需求。
|
1月前
|
XML 移动开发 Android开发
构建高效安卓应用:采用Jetpack Compose实现动态UI
【4月更文挑战第10天】 在现代移动开发中,用户界面的流畅性和响应性对于应用的成功至关重要。随着技术的不断进步,安卓开发者寻求更加高效和简洁的方式来构建动态且吸引人的UI。本文将深入探讨Jetpack Compose这一革新性技术,它通过声明式编程模型简化了UI构建过程,并提升了性能与跨平台开发的可行性。我们将从基本概念出发,逐步解析如何利用Jetpack Compose来创建具有数据动态绑定能力的安卓应用,同时确保应用的高性能和良好用户体验。
19 0
|
1月前
|
XML Java Android开发
Android之UI基础控件
Android之UI基础控件