Service是android系统的四大组件之一,它的地位和Activity是并列的,只不过没有Activity的使用频率高。Service是运行在后台的一种服务进程,没有和用户的交互界面,例如当你看电子书时将音乐播放器关闭了,但是你希望能够继续播放音乐,就要通过Service来实现音乐的后台播放。
Service有自己的生命周期,我们可以调用startService()启动一个Service或者使用bindService()方法来绑定一个存在的Service,也可以通过远程进程调用(RPC)机制来实现不同进程间Service的调用。
启动一个Service比较简单,只要定义了一个类继承Service,并覆盖类中相应的方法就可以了,Service中定义了一系列与自身生命周期相关的方法,主要有:
(1)、onBind(Intent intent),是必须实现的一个方法,返回一个绑定的借口给Service。
(2)、onCreate(),当Service第一次被创建时由系统调用。
(3)、onStart(Intent internt,int startId),当通过startService()方法启动Service时该方法被调用。
(4)、onDestroy(),当Service不再使用时由系统调用。
要想使用Service,必须在AndroidManifest.xml配置文件中用<service>元素申明Service,在<service>元素中添加<intent-filter>制定如何访问Service。
至于如何启动和停止Service,也是比较简单的。一旦定义和申明好一个Service之后,就可以在其他组件中启动Service来使用它了,启动一个Service使用的方法是Context.startService(Intent intent)。当调用startService()方法是,被使用的Service会调用它的onCreate()方法(如果该Service还没有创建的话),接着调用onStart()方法。一旦Service启动后将一直运行知道调用了Context.stopService()或者stopSelf().
上面说过启动Service可以通过绑定存在的Service来实现。当通过bindService()方法来绑定一个Service时也会调用onCreate()方法来创建Service(如果它还没有被创建的话),但是并不会调用onStart()方法而是调用onBind()方法来返回客户端的一个IBinder借口。绑定Service一般用在远程Service调用时。
绑定Service需要三个参数:bindService(intent,conn,Service.BIND_AUTO_CREATE);
第一个是Intent;第二个是ServiceConnection对象,我们创建该对象实现其onServiceConnected()和onServiceDisconnected()来判断链接成功或者断开链接;第三个参数是如何创建Service,一般制定绑定时自动创建。
下面通过一个例子来演示Service的生命周期:首先创建一个ServiceTest的android工程;布局文件中分别声明四个Button,分别用来启动、停止、绑定和解除绑定Service。
Main.xml
<?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:text="@string/hello" />
<Button
android:id="@+id/startService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动Service"
/>
<Button
android:id="@+id/stopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止Service"
/>
<Button
android:id="@+id/bindService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定Service"
/>
<Button
android:id="@+id/onBindService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="解除绑定Service"
/>
</LinearLayout>
创建一个MyService类继承自Service类,并覆盖其生命周期方法。
package com.luofu.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service
{
@Override
public IBinder onBind(Intent intent)
{
Log.i("SERVICE", "onBind......");
Toast.makeText(MyService.this, "onBind.....", Toast.LENGTH_LONG).show();
return null;
}
public void onCreate()
{
Log.i("SERVICE", "onCreate......");
Toast.makeText(MyService.this, "onCreate.....", Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent,int startId)
{
Log.i("SERVICE", "onStart......");
Toast.makeText(MyService.this, "onStart.....", Toast.LENGTH_LONG).show();
}
public void onDestroy()
{
Log.i("SERVICE", "onDestroy......");
Toast.makeText(MyService.this, "onDestroy.....", Toast.LENGTH_LONG).show();
}
}
在AndroidManifest.xml文件中声明Service和Activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.luofu.service"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdkandroid:minSdkVersion="7"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".ServiceTestActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<serviceandroid:name="MyService">
<intent-filter >
<action android:name="com.luofu.service.app.action.MY_SERVICE"/>
</intent-filter>
</service>
</application>
</manifest>
ServiceTestActivity代码如下
package com.luofu.service;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ServiceTestActivity extends Activity {
private Button startButton,stopButton,bindButton,unBindButton;
private ServiceConnection conn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startButton = (Button)findViewById(R.id.startService);
stopButton = (Button)findViewById(R.id.stopService);
bindButton = (Button)findViewById(R.id.bindService);
unBindButton = (Button)findViewById(R.id.unBindService);
//创建ServiceConnection对象
conn = new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder service)
{
Log.i("SERVICE", "链接成功......");
Toast.makeText(ServiceTestActivity.this, "链接成功.....", Toast.LENGTH_LONG).show();
}
public void onServiceDisconnected(ComponentName name)
{
Log.i("SERVICE", "断开链接......");
Toast.makeText(ServiceTestActivity.this, "断开链接.....", Toast.LENGTH_LONG).show();
}
};
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//启动service
startService(ServiceTestActivity.this.createIntent());
}
});
stopButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//停止service
stopService(ServiceTestActivity.this.createIntent());
}
});
bindButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//绑定service
bindService(ServiceTestActivity.this.createIntent(), conn, Service.BIND_AUTO_CREATE);
}
});
unBindButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//解除绑定
unbindService(conn);
}
});
}
//设置intent的方法
public Intent createIntent()
{
Intent intent = new Intent();
intent.setAction("com.luofu.service.app.action.MY_SERVICE");
return intent;
}
}