创建和控制Service

   

Service被设计用于在后台运行,所以,它们需要被其它程序组件启动、停止和控制。

 

在接下来的章节,你将学习如何创建一个新的Service,如何使用IntentstartService方法来启动和停止它。之后,你讲学习如何绑定一个ServiceActivity上,为交互性提供更加丰富的界面。

 

创建一个Service

 

通过扩展Service基类来定义一个Service。你需要重写onBindonCreate方法,如下面的框架类所示:

 

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

public class MyService extends Service {

 

@Override

public void onCreate() {

// TODO: Actions to perform when service is created.

}

 

@Override

public IBinder onBind(Intent intent) {

// TODO: Replace with service binding implementation.

return null;

}

}

 

在多数情况下,你还需要重写onStart方法。这个方法在Service通过startService启动时会调用,因此,在Service的生命周期里,它能执行很多次。

 

下面的代码片段显示了重写onStart方法:

 

@Override

public void onStart(Intent intent, int startId) {

// TODO: Actions to perform when service is started.

}

 

一旦你构建了一个新的Service,你就必须在应用程序的manifest中注册它。

 

通过在application节点中包含一个service标签来注册。你可以在service标签上使用特性来enable/disable Service,和使用一个requires-permission标志来指明其它应用程序访问它所需的权限。

 

下面的service标签是为上面创建的框架Service添加的:

 

<service android:enabled=”true” android:name=”.MyService”></service>

posted on 2009-08-12 10:26  xirihanlin  阅读(518)  评论(0编辑  收藏  举报