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

Android应用开发学习笔记之Service

Android Service分为两种,一是StartedService,另一种是Bound Service。下面来看Android官方文档对这两种Service的定义:
 
A service canessentially take two forms:
 
Started
 
A service is "started" when anapplication component (such as an activity) starts it by calling startService(). Once started, a service can run in thebackground indefinitely, even if the component that started it is destroyed.Usually, a started service performs a single operation and does not return aresult to the caller. For example, it might download or upload a file over thenetwork. When the operation is done, the service should stop itself.
 
Bound
 
A service is "bound" when anapplication component binds to it by calling bindService(). A bound service offers a client-serverinterface that allows components to interact with the service, send requests,get results, and even do so across processes with interprocess communication(IPC). A bound service runs only as long as another application component isbound to it. Multiple components can bind to the service at once, but when allof them unbind, the service is destroyed.
 
 
 
一、StartedService的实现
 
 
 
创建Started Service有两种方法,一是继承IntentService类,二是继承Service类。前者我们只需要实现onHandleIntent()函数和一个无参数的构造函数,代码简单,但是这种方法一次只能处理一个客户端请求。后者需要我们实现多个成员函数,但是自主性较大,可以同时处理多个客户请求。
 
我们先来看一个通过继承IntentService实现Started Service的例子,该程序运行效果如下:
 
点击“显示当前时间”按钮后, 
 
 
 
先来看主布局文件,其内容如下:
 
[html]  
<?xml version="1.0"encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:orientation="vertical" >  
   
   <TextView  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:textSize="20dp"  
        android:text="@string/hello" />  
   <Button  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:id="@+id/button"  
        android:textSize="20dp"  
        android:text="显示当前时间"/>  
   
</LinearLayout>  
 
 
再来看主Activity文件,其内容如下:
 
[java]  
package com.liuhaoyu;  
   
import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
   
public classMainActivity extends Activity {  
   /** Called when the activity is firstcreated. */  
   @Override  
   publicvoidonCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
         
        Button button =(Button)findViewById(R.id.button);  
        button.setOnClickListener(new View.OnClickListener(){  
             
            @Override  
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
                startService(new Intent(MainActivity.this, CurrentTimeService.class));  
            }  
        });  
   }  
}  
 
 
下面看service的实现:
 
[java]  
package com.liuhaoyu;  
   
import android.app.IntentService;  
import android.content.Intent;  
import android.text.format.Time;  
import android.util.Log;  
   
public classCurrentTimeService extends IntentService {  
   
   publicCurrentTimeService() {  
        super("CurrentTimeService");  
   }  
   
   @Override  
   protectedvoidonHandleIntent(Intent intent) {  
        Time time = new Time();  
        time.setToNow();  
        String currentTime = time.format("%Y-%m-%d %H:%M:%S");  
        Log.i("CurrentTimeService", currentTime);  
   }  
}  
 
 
最后,需要注意我们要在AndroidManifest.xml文件中声明Service,如下:
 
[html]  
<service android:name=".CurrentTimeService">  
</service>  
 
 
注意上面这个程序,每次点击按钮,LogCat只会显示一条时间信息,也就是说Service的onHandleIntent()函数只会执行一次。而且我们并没有调用stopSelf()等函数停止Service,这是因为IntentService已经在幕后替我们完成了许多工作,我们就不用亲自做了,来看Android官方文档的描述:
 
The IntentService doesthe following:
 
·        Creates a default worker threadthat executes all intents delivered to onStartCommand() separate from your application's main thread.
 
·        Creates a work queue thatpasses one intent at a time to your onHandleIntent() implementation, so you never have to worry aboutmulti-threading.
 
·        Stops the service after allstart requests have been handled, so you never have to call stopSelf().
 
·        Provides default implementationof onBind() that returns null.
 
·        Provides a defaultimplementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIn
补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,