Service通知Activity修改UIUI动态更新)有两种方式:

通过service发送广播通知activity修改UI的内容;

通过Handler进行传递值更新。

 

一、首先来说第一种,通过service发送广播通知activity修改UI的内容。(结合例子讲解,计时器)

说明:Activity与通过startService方法启动的Service之间是无法直接进行通信的,但是借助BroadcastReceiver可以实现两者之间的通信。

1.实现思路:1)后台Service每隔1秒发送广播通知时间已发生变化;

    2UI层(Activity)通过BroadcastReceiver接收到广播,更新显示的时间。

2.关键技术点:Service的应用、BroadcastReceiver的应用

3.关于注册广播,有两种方式:

①xml中配置:

 

 

 
  
  1. <receiver android:name=".UITimeReceiver">  
  2.           <intent-filter>  
  3.               <action       android:name="com.xc.TIME_CHANGED_ACTION"/>  
  4.           </intent-filter>  
  5. </receiver>  

②代码:

 

 
  
  1. registerReceiver(BroadcastReceiver receiver,IntentFilter filter); 

4.上代码:

①布局文件:main.xml

 

 
  
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"   
  5.     android:layout_height="fill_parent"  
  6.     >   
  7.     <TextView  
  8.         android:id="@+id/tv"  
  9.         android:layout_width="wrap_content"   
  10.         android:layout_height="wrap_content"  
  11.         android:text="当前时间: "  
  12.         />   
  13.          
  14.     <TextView android:id="@+id/time"  
  15.         android:layout_width="fill_parent"   
  16.         android:layout_height="wrap_content"   
  17.         android:layout_toRightOf="@+id/tv"  
  18.         />   
  19.   </RelativeLayout>  

DynamicUIActivity.java

这里注册广播的方式为代码。如果要用xml注册,则需要将UITimeReceiver单独创建一个java文件。

 

 

 
  
  1. package com.example.servicedemo; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.BroadcastReceiver; 
  5. import android.content.Context; 
  6. import android.content.Intent; 
  7. import android.content.IntentFilter; 
  8. import android.graphics.Color; 
  9. import android.os.Bundle; 
  10. import android.widget.TextView; 
  11.  
  12. public class DynamicUIActivity extends Activity {   
  13.     public static String TIME_CHANGED_ACTION = "com.xc.TIME_CHANGED_ACTION";   
  14.     private  static TextView time = null;   
  15.     private Intent timeService = null;   
  16.     @Override   
  17.     public void onCreate(Bundle savedInstanceState) {   
  18.         super.onCreate(savedInstanceState);   
  19.         setContentView(R.layout.main);   
  20.            
  21.         //初始化UI   
  22.         initUI();   
  23.         System.out.println("initUI");   
  24.            
  25.         //注册广播-方法1   
  26.         /*  
  27.          * 配置  
  28.          * <receiver android:name=".UITimeReceiver">  
  29.             <intent-filter>  
  30.                 <action android:name="com.xc.TIME_CHANGED_ACTION"/>  
  31.             </intent-filter>  
  32.         </receiver>  
  33.          */   
  34.            
  35.         //注册广播-方法2   
  36.         //注册广播,监听后台Service发送过来的广播   
  37.         registerBroadcastReceiver();   
  38.            
  39.         //启动服务,时间改变后发送广播,通知UI层修改时间   
  40.         startTimeService();   
  41.     }   
  42.        
  43.     public TextView getTimeTextView(){   
  44.         return time;   
  45.     }   
  46.        
  47.     /**  
  48.      * 初始化UI  
  49.      */   
  50.     private void initUI(){   
  51.         time = (TextView)findViewById(R.id.time);   
  52.         time.setTextColor(Color.RED);   
  53.         time.setTextSize(15);   
  54.     }   
  55.        
  56.     /**  
  57.      * 注册广播  
  58.      */   
  59.     private void registerBroadcastReceiver(){   
  60.         UITimeReceiver receiver = new UITimeReceiver();   
  61.         IntentFilter filter = new IntentFilter(TIME_CHANGED_ACTION);   
  62.         registerReceiver(receiver, filter);   
  63.     }   
  64.        
  65.     /**  
  66.      * 启动服务  
  67.      */   
  68.     private void startTimeService(){   
  69.         timeService = new Intent(this,TimeService.class);   
  70.         this.startService(timeService);   
  71.     }   
  72.        
  73.     @Override   
  74.     protected void onDestroy() {   
  75.         super.onDestroy();   
  76.         //停止服务   
  77.         stopService(timeService);   
  78.     }   
  79.      
  80.      
  81.     public class UITimeReceiver extends BroadcastReceiver{   
  82.           
  83.         @Override   
  84.         public void onReceive(Context context, Intent intent) {   
  85.             String action = intent.getAction();   
  86.              
  87.             if(DynamicUIActivity.TIME_CHANGED_ACTION.equals(action)){   
  88.                 Bundle bundle = intent.getExtras();   
  89.                 String strtime = bundle.getString("time");                
  90.                 time.setText(strtime);   
  91.             }   
  92.         }   
  93.     }   
  94.  
  95.   }   

③:TimeService.java

 

 
  
  1. package com.example.servicedemo; 
  2.  
  3. import java.text.SimpleDateFormat; 
  4. import java.util.Date; 
  5. import java.util.Timer; 
  6. import java.util.TimerTask; 
  7.  
  8. import android.app.Service; 
  9. import android.content.ComponentName; 
  10. import android.content.Intent; 
  11. import android.os.Bundle; 
  12. import android.os.IBinder; 
  13. import android.util.Log; 
  14.  
  15. public class TimeService extends Service { 
  16.     private String TAG = "TimeService";   
  17.     private Timer timer = null;   
  18.     private SimpleDateFormat sdf = null;   
  19.     private Intent timeIntent = null;   
  20.     private Bundle bundle = null;   
  21.     @Override   
  22.     public void onCreate() {   
  23.         super.onCreate();   
  24.         Log.i(TAG,"TimeService->onCreate");   
  25.         //初始化   
  26.         this.init();   
  27.         //定时器发送广播   
  28.         timer.schedule(new TimerTask() {   
  29.             @Override   
  30.             public void run() {   
  31.                 //发送广播   
  32.                 sendTimeChangedBroadcast();   
  33.             }   
  34.         }, 1000,1000);   
  35.     }   
  36.        
  37.     @Override   
  38.     public IBinder onBind(Intent intent) {   
  39.         Log.i(TAG,"TimeService->onBind");   
  40.         return null;   
  41.     }   
  42.        
  43.     /**  
  44.      * 相关变量初始化  
  45.      */   
  46.     private void init(){   
  47.         timer = new Timer();   
  48.         sdf = new SimpleDateFormat("yyyy年MM月dd日 "+"hh:mm:ss");   
  49.         timeIntent = new Intent();   
  50.         bundle = new Bundle();   
  51.     }   
  52.        
  53.     /**  
  54.      * 发送广播,通知UI层时间已改变  
  55.      */   
  56.     private void sendTimeChangedBroadcast(){   
  57.         bundle.putString("time", getTime());   
  58.         timeIntent.putExtras(bundle);   
  59.         timeIntent.setAction(DynamicUIActivity.TIME_CHANGED_ACTION);   
  60.         //发送广播,通知UI层时间改变了   
  61.         sendBroadcast(timeIntent);   
  62.     }   
  63.        
  64.     /**  
  65.      * 获取最新系统时间  
  66.      * @return  
  67.      */   
  68.     private String getTime(){   
  69.         return sdf.format(new Date());   
  70.     }   
  71.        
  72.     @Override   
  73.     public ComponentName startService(Intent service) {   
  74.         Log.i(TAG,"TimeService->startService");   
  75.         return super.startService(service);   
  76.     }   
  77.        
  78.     @Override   
  79.     public void onDestroy() {   
  80.         super.onDestroy();   
  81.         Log.i(TAG,"TimeService->onDestroy");   
  82.     }   

④:AndroidMainifest.xml

 

 

 
  
  1. <service android:name=".TimeService"></service>  

5.效果图

 

 

二、通过Handler进行传递值更新。由于使用广播开销过大,我们一般使用Handler传递值。

①handlerservice.xml:

 
  
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="http://schemas.android.com/tools" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" 
  6.      > 
  7.  
  8.     <TextView 
  9.         android:id="@+id/text" 
  10.         android:layout_width="wrap_content" 
  11.         android:layout_height="wrap_content" 
  12.         android:text="@string/hello_world" 
  13.         /> 
  14.     <Button 
  15.         android:id="@+id/start" 
  16.         android:layout_width="wrap_content" 
  17.         android:layout_height="wrap_content" 
  18.         android:text="开始服务" 
  19.         /> 
  20.     <Button 
  21.         android:id="@+id/stop" 
  22.         android:layout_width="wrap_content" 
  23.         android:layout_height="wrap_content" 
  24.         android:text="停止服务" 
  25.         /> 
  26. </LinearLayout> 
②:HandlerActivity.java

 

 
  
  1. package com.example.servicedemo; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.Intent; 
  5. import android.os.Bundle; 
  6. import android.os.Handler; 
  7. import android.os.Message; 
  8. import android.view.View; 
  9. import android.view.View.OnClickListener; 
  10. import android.widget.Button; 
  11. import android.widget.TextView; 
  12.  
  13. public class HandlerActivity extends Activity implements OnClickListener{ 
  14.     private Button start,stop; 
  15.     private TextView text; 
  16.     public static Handler handler; 
  17.     public static int FLAG = 1
  18.     private Intent timeService = null;  
  19.  
  20.     @Override 
  21.     protected void onCreate(Bundle savedInstanceState) { 
  22.         // TODO Auto-generated method stub 
  23.         super.onCreate(savedInstanceState); 
  24.         setContentView(R.layout.handlerservice); 
  25.         initLayout(); 
  26.         setListeners(); 
  27.         timeService = new Intent(HandlerActivity.this,HandlerService.class); 
  28.          
  29.         handler = new Handler(){ 
  30.  
  31.             @Override 
  32.             public void handleMessage(Message msg) { 
  33.                 super.handleMessage(msg); 
  34.                 if(msg.what==FLAG){ 
  35.                     text.setText((String)msg.obj); 
  36.                 } 
  37.             } 
  38.              
  39.         }; 
  40.          
  41.     } 
  42.  
  43.     private void initLayout() { 
  44.         text = (TextView)findViewById(R.id.text); 
  45.         start = (Button)findViewById(R.id.start); 
  46.         stop = (Button)findViewById(R.id.stop); 
  47.     } 
  48.  
  49.     public void setListeners() 
  50.     { 
  51.         start.setOnClickListener(this); 
  52.         stop.setOnClickListener(this); 
  53.     } 
  54.  
  55.     @Override 
  56.     public void onClick(View v) { 
  57.         switch (v.getId()) { 
  58.         case R.id.start: 
  59.              
  60.             startService(timeService); 
  61.             break
  62.  
  63.         case R.id.stop: 
  64.              
  65.             stopService(timeService); 
  66.  
  67.             handler.removeMessages(FLAG); 
  68.             break
  69.         } 
  70.     } 
  71.  
  72.     @Override 
  73.     protected void onDestroy() { 
  74.         super.onDestroy(); 
  75.          
  76.     } 
  77.      

 

 


③HandlerService.java

 

 

 
  
  1. package com.example.servicedemo; 
  2.  
  3. import java.text.SimpleDateFormat; 
  4. import java.util.Date; 
  5. import java.util.Timer; 
  6. import java.util.TimerTask; 
  7.  
  8. import android.app.Service; 
  9. import android.content.Intent; 
  10. import android.os.IBinder; 
  11. import android.os.Message; 
  12. import android.util.Log; 
  13.  
  14. public class HandlerService extends Service{ 
  15.     private Timer timer = null;   
  16.     private SimpleDateFormat sdf = null;    
  17.      
  18.     @Override 
  19.     public IBinder onBind(Intent intent) { 
  20.         return null
  21.     } 
  22.  
  23.     @Override 
  24.     public void onCreate() { 
  25.         super.onCreate(); 
  26.         init(); 
  27.          
  28.         timer.schedule(new TimerTask() { 
  29.              
  30.             @Override 
  31.             public void run() { 
  32.                 Message msg = new Message(); 
  33.                 msg.what = HandlerActivity.FLAG; 
  34.                 msg.obj=getTime(); 
  35.                 HandlerActivity.handler.sendMessage(msg); 
  36.             } 
  37.  
  38.         }, 01000); 
  39.          
  40.     } 
  41.  
  42.     public void init(){ 
  43.         timer = new Timer(); 
  44.         sdf = new SimpleDateFormat("yyyy年MM月dd日 "+"hh:mm:ss"); 
  45.     } 
  46.      
  47.  
  48.     private String getTime() { 
  49.          
  50.         return sdf.format(new Date()); 
  51.     } 
  52.  
  53.     @Override 
  54.     public void onDestroy() { 
  55.         Log.i("TAG","Services onDestory"); 
  56.         super.onDestroy(); 
  57.          
  58.     } 
  59.      
  60.      

④AndroidManifest.xml

 

 
  
  1. <service android:name=".HandlerService"></service>  

 

 

 

 

后续继续补充。