Service通知Activity修改UI(UI动态更新)有两种方式:
①通过service发送广播通知activity修改UI的内容;
②通过Handler进行传递值更新。
一、首先来说第一种,通过service发送广播通知activity修改UI的内容。(结合例子讲解,计时器)
说明:Activity与通过startService方法启动的Service之间是无法直接进行通信的,但是借助BroadcastReceiver可以实现两者之间的通信。
1.实现思路:1)后台Service每隔1秒发送广播通知时间已发生变化;
2)UI层(Activity)通过BroadcastReceiver接收到广播,更新显示的时间。
2.关键技术点:Service的应用、BroadcastReceiver的应用
3.关于注册广播,有两种方式:
①xml中配置:
- <receiver android:name=".UITimeReceiver">
- <intent-filter>
- <action android:name="com.xc.TIME_CHANGED_ACTION"/>
- </intent-filter>
- </receiver>
②代码:
- registerReceiver(BroadcastReceiver receiver,IntentFilter filter);
4.上代码:
①布局文件:main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="当前时间: "
- />
- <TextView android:id="@+id/time"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_toRightOf="@+id/tv"
- />
- </RelativeLayout>
②DynamicUIActivity.java
这里注册广播的方式为代码。如果要用xml注册,则需要将UITimeReceiver单独创建一个java文件。
- package com.example.servicedemo;
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.widget.TextView;
- public class DynamicUIActivity extends Activity {
- public static String TIME_CHANGED_ACTION = "com.xc.TIME_CHANGED_ACTION";
- private static TextView time = null;
- private Intent timeService = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //初始化UI
- initUI();
- System.out.println("initUI");
- //注册广播-方法1
- /*
- * 配置
- * <receiver android:name=".UITimeReceiver">
- <intent-filter>
- <action android:name="com.xc.TIME_CHANGED_ACTION"/>
- </intent-filter>
- </receiver>
- */
- //注册广播-方法2
- //注册广播,监听后台Service发送过来的广播
- registerBroadcastReceiver();
- //启动服务,时间改变后发送广播,通知UI层修改时间
- startTimeService();
- }
- public TextView getTimeTextView(){
- return time;
- }
- /**
- * 初始化UI
- */
- private void initUI(){
- time = (TextView)findViewById(R.id.time);
- time.setTextColor(Color.RED);
- time.setTextSize(15);
- }
- /**
- * 注册广播
- */
- private void registerBroadcastReceiver(){
- UITimeReceiver receiver = new UITimeReceiver();
- IntentFilter filter = new IntentFilter(TIME_CHANGED_ACTION);
- registerReceiver(receiver, filter);
- }
- /**
- * 启动服务
- */
- private void startTimeService(){
- timeService = new Intent(this,TimeService.class);
- this.startService(timeService);
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- //停止服务
- stopService(timeService);
- }
- public class UITimeReceiver extends BroadcastReceiver{
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- if(DynamicUIActivity.TIME_CHANGED_ACTION.equals(action)){
- Bundle bundle = intent.getExtras();
- String strtime = bundle.getString("time");
- time.setText(strtime);
- }
- }
- }
- }
③:TimeService.java
- package com.example.servicedemo;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Service;
- import android.content.ComponentName;
- import android.content.Intent;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.util.Log;
- public class TimeService extends Service {
- private String TAG = "TimeService";
- private Timer timer = null;
- private SimpleDateFormat sdf = null;
- private Intent timeIntent = null;
- private Bundle bundle = null;
- @Override
- public void onCreate() {
- super.onCreate();
- Log.i(TAG,"TimeService->onCreate");
- //初始化
- this.init();
- //定时器发送广播
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- //发送广播
- sendTimeChangedBroadcast();
- }
- }, 1000,1000);
- }
- @Override
- public IBinder onBind(Intent intent) {
- Log.i(TAG,"TimeService->onBind");
- return null;
- }
- /**
- * 相关变量初始化
- */
- private void init(){
- timer = new Timer();
- sdf = new SimpleDateFormat("yyyy年MM月dd日 "+"hh:mm:ss");
- timeIntent = new Intent();
- bundle = new Bundle();
- }
- /**
- * 发送广播,通知UI层时间已改变
- */
- private void sendTimeChangedBroadcast(){
- bundle.putString("time", getTime());
- timeIntent.putExtras(bundle);
- timeIntent.setAction(DynamicUIActivity.TIME_CHANGED_ACTION);
- //发送广播,通知UI层时间改变了
- sendBroadcast(timeIntent);
- }
- /**
- * 获取最新系统时间
- * @return
- */
- private String getTime(){
- return sdf.format(new Date());
- }
- @Override
- public ComponentName startService(Intent service) {
- Log.i(TAG,"TimeService->startService");
- return super.startService(service);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- Log.i(TAG,"TimeService->onDestroy");
- }
- }
④:AndroidMainifest.xml
- <service android:name=".TimeService"></service>
5.效果图
二、通过Handler进行传递值更新。由于使用广播开销过大,我们一般使用Handler传递值。
①handlerservice.xml:
②:HandlerActivity.java
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- >
- <TextView
- android:id="@+id/text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/hello_world"
- />
- <Button
- android:id="@+id/start"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="开始服务"
- />
- <Button
- android:id="@+id/stop"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="停止服务"
- />
- </LinearLayout>
- package com.example.servicedemo;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
- public class HandlerActivity extends Activity implements OnClickListener{
- private Button start,stop;
- private TextView text;
- public static Handler handler;
- public static int FLAG = 1;
- private Intent timeService = null;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.handlerservice);
- initLayout();
- setListeners();
- timeService = new Intent(HandlerActivity.this,HandlerService.class);
- handler = new Handler(){
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- if(msg.what==FLAG){
- text.setText((String)msg.obj);
- }
- }
- };
- }
- private void initLayout() {
- text = (TextView)findViewById(R.id.text);
- start = (Button)findViewById(R.id.start);
- stop = (Button)findViewById(R.id.stop);
- }
- public void setListeners()
- {
- start.setOnClickListener(this);
- stop.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.start:
- startService(timeService);
- break;
- case R.id.stop:
- stopService(timeService);
- handler.removeMessages(FLAG);
- break;
- }
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
- }
③HandlerService.java
- package com.example.servicedemo;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Service;
- import android.content.Intent;
- import android.os.IBinder;
- import android.os.Message;
- import android.util.Log;
- public class HandlerService extends Service{
- private Timer timer = null;
- private SimpleDateFormat sdf = null;
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onCreate() {
- super.onCreate();
- init();
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- Message msg = new Message();
- msg.what = HandlerActivity.FLAG;
- msg.obj=getTime();
- HandlerActivity.handler.sendMessage(msg);
- }
- }, 0, 1000);
- }
- public void init(){
- timer = new Timer();
- sdf = new SimpleDateFormat("yyyy年MM月dd日 "+"hh:mm:ss");
- }
- private String getTime() {
- return sdf.format(new Date());
- }
- @Override
- public void onDestroy() {
- Log.i("TAG","Services onDestory");
- super.onDestroy();
- }
- }
④AndroidManifest.xml
- <service android:name=".HandlerService"></service>
后续继续补充。