当前位置:操作系统 > 安卓/Android >>

Android ApiDemos示例解析(44):App->Service->Service Start Arguments Controller

本例是ApiDemos关于Service的最后一个例子,这个例子的主要目的是介绍如何向Service传递参数。前面的例子忽略了一个重要的问题: Service 的onStartCommand 或是 onStart(2.1版本之前)是使用调用它的Android组件(通常是Activity)同一个Thread来执行的,对应Activity来说,这个Thread通常是UI Thread,前面的Service例子都是提供非常简单的服务,对于UI 性能不会有很大影响,但如果在Service中使用了较费时的操作,如果网络访问,数据库查询,如果还是使用UI Thread来运行的话,就可能大大降低UI的响应性能,甚至出现ANR(Application Not Response)对话框,所以通常都是在Service新建一个线程来处理来自Client的请求。

Android.os 的Handler, HandlerThread, Loop, Message 常用于Service中,其中Handler介绍可以参见Android 系统Handler用法简介。

Android 中每个Thread都可以有一Message Queue,但除UI Thread外,Thread缺省情况下不带Message Queue, 要为一个Thread 创建一个Message Queue,可以参见下面代码:

[java] 
class LooperThread extends Thread { 
 public Handler mHandler; 
 public void run() { 
 Looper.prepare(); 
 mHandler = new Handler() { 
 public void handleMessage(Message msg) { 
 // process incoming messages here  
 } 
 }; 
 Looper.loop(); 
 } 
 } 
class LooperThread extends Thread {
 public Handler mHandler;
 public void run() {
 Looper.prepare();
 mHandler = new Handler() {
 public void handleMessage(Message msg) {
 // process incoming messages here
 }
 };
 Looper.loop();
 }
 }
Looper.prepare()用来创建一个Message Queue, Looper.loop() 处理消息直到Loop停止。 在Thread在创建的Handler将会和Thread的Message Queue关联。Handler的handleMessage用来处理消息,其类型为Message类。

HandlerThread派生于Thread,用于方便创建一个带Looper的Thread。本例就是使用了HandlerThread.

[java] 
private volatile Looper mServiceLooper; 
private volatile ServiceHandler mServiceHandler; 
  
private final class ServiceHandler extends Handler { 
public ServiceHandler(Looper looper) { 
 super(looper); 

  
@Override 
public void handleMessage(Message msg) { 
 ... 
 } 
  
 ... 
 HandlerThread thread = new HandlerThread("ServiceStartArguments", 
 Process.THREAD_PRIORITY_BACKGROUND); 
thread.start(); 
  
mServiceLooper = thread.getLooper(); 
mServiceHandler = new ServiceHandler(mServiceLooper); 
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
 
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
 super(looper);
}
 
@Override
public void handleMessage(Message msg) {
 ...
 }
 
 ...
 HandlerThread thread = new HandlerThread("ServiceStartArguments",
 Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
 
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
ServiceStartArguments Service 使用一个新创建的Thread来处理来自Client的消息,这个Thread不是UI Thread,使用HandlerThread 创建一个带Looper的线程,而具体的消息处理是由ServiceHandler的handleMessage来处理。

Message类定义了消息,可以含有对消息的描述description,类型what,缺省带arg1,arg2, obj三个参数可以直接使用。 并提供了obtain()静态函数来构造一个新的Message对象。

ServiceStartArguments.Controller 为ServiceStartArguments Service的Client。它定义了四个按钮,通过Intent的Extra向Service传递参数:

[java] 
startService(new Intent(Controller.this, 
 ServiceStartArguments.class) 
 .putExtra("name", "One")); 
  
startService(new Intent(Controller.this, 
 ServiceStartArguments.class) 
 .putExtra("name", "Two")); 
  
startService(new Intent(Controller.this, 
 ServiceStartArguments.class) 
 .putExtra("name", "Three") 
 .putExtra("redeliver", true)); 
  
startService(new Intent(Controller.this, 
 ServiceStartArguments.class) 
 .putExtra("name", "Failure") 
 .putExtra("fail", true)); 
startService(new Intent(Controller.this,
 ServiceStartArguments.class)
 .putExtra("name", "One"));
 
startService(new Intent(Controller.this,
 ServiceStartArguments.class)
 .putExtra("name", "Two"));
 
startService(new Intent(Controller.this,
 ServiceStartArguments.class)
 .putExtra("name", "Three")
 .putExtra("redeliver", true));
 
startService(new Intent(Controller.this,
 ServiceStartArguments.class)
 .putExtra("name", "Failure")
 .putExtra("fail", true));
相当于向Service传递了name (string), redeliver(boolean) ,fail(boolean)几个参数。

StartService会触发Service的onStartCommand方法:

[java] 
@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
 Log.i("ServiceStartArguments", 
 "Starting #" + startId + ": " + intent.getExtras()); 
 Message msg = mServiceHandler.obtainMessage(); 
 msg.arg1 = startId; 
 msg.arg2 = flags; 
 msg.obj = intent.getExtras(); 
 mServiceHandler.sendMessage(msg); 
 Log.i("ServiceStartArguments", "Sending: " + msg); 
  
 // For the start fail button, we will simulate the process dying  
 // for some reason in onStartCommand().  
 if (intent.getBooleanExtra("fail", false)) { 
 // Don't do this if we are in a retry... the system will  
 // eventually give up if we keep crashing.  
 if ((flags&START_FLAG_RETRY) == 0) { 
 // Since the process hasn't finished handling the command,  
 // it will be restarted with the command again, regardless of  
 // whether we return START_REDELIVER_INTENT.  
 Process.killProcess(Process.myPid()); 
 } 
 } 
  
 // Normally we would consistently return one kind of result...  
 // however, here we will select between these two, so you can see  
 // how they impact the behavior.  Try killing the process while it  
 // is in the middle of executing the different commands.  
 return intent.getBooleanExtra("redeliver", false) 
 ? START_REDELIVER_INTENT : START_NOT_STICKY; 

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
 Log.i("ServiceStartArguments",
 "Starting #" + startId + ": " + intent.getExtras());
 Message msg = mServiceHandler.obtainMessage();
 msg.arg1 = startId;
 msg.arg2 = flags;
 msg.obj = intent.getExtra

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,