---恢复内容开始---
Service的意义就在于当软件停止之后还可以在背景中进行运行,换句话也就是说,比如一个音乐播放器,当我们退出音乐播放器的时候,还是希望它在背景中运行,也就是一直播放着音乐,这时候Service就派上了大的用途。
Service的生命周期和Activity的生命周期差不多。也有开启和停止。onCreate()方法是初始化配置,onDestroy()是释放所有剩余的资源。Service周期是发生在onCreate()和onDestroy()之间的。
startService()方法是启动Service。
StopService()方法是停止Service。
bindService()方法是启动Service的激活生命周期始于onBind()调用,在onUnbind()返回时结束。
当一个组件启动Service时,是通过startService()进行启动Service,当Service被启动之后,onStartCommand()方法被调用,并且接收startService()方法中传递的Intent值。
onStartServiceCommand()方法必修返回一个整形值。这个整形值是说明了Service在系统中如何执行。其中三个比较常用的解释如下:
START_NOT_STICKY:如果系统在onStartServiceCommand()返回后杀死Service,那么不会重新创建Service,除非有等待的Intent要传递。
START_STICKY 如果系统在onStartServiceCommand()返回后杀死Service,重启Service,并且重新调用onStartServiceCommand(),但不重新传递最新的Intent。
START_REDELIVER_INTENT 如果系统在onStartServiceCommand()返回后杀死Service,那么重新创建Service,并且最近传给Service的Intent调用onStartServiceCommand()。
创建一个Service启动周期的实例
public class MyService extends Service{ //必须实现的方法,作用是用来返回binder对象 //重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("--onBind--");
return null;
} //用于创建Service的方法,只能调用一次
public void onCreate(){
super.onCreate();
System.out.println("--onCreate--"); //每次启动Service时都会调用这个方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("--onStartCommand--");
return super.onStartCommand(intent, flags, startId);
} //解绑的时候使用的这个方法
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("--onUnbind--");
return super.onUnbind(intent);
} //退出或者销毁的时候使用这个方法
@Override
public void onDestroy() {
// TODO Auto-generated method stub
serviceRunning = false;
System.out.println("--onDestroy--");
super.onDestroy(); } }
注意:在测试的时候一定要在onCreate()方法中写一个多线程,以便输出,让我们更加的明白。如下:
//用于创建Service的方法,只能调用一次
public void onCreate(){
super.onCreate();
System.out.println("--onCreate--");
serviceRunning = true;
new Thread(){
public void run(){
while(serviceRunning){
System.out.println("--Service运行中--");
try{
sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
}
}.start();
}
绑定Service
绑定Service的时候会比较的复杂,其中,看绑定方法bindService(Intent service, ServiceConnection conn, int flags)时大家就可以看出。其中Intent需要传递Intent的值,conn是ServiceConnection的实例,flags是所需要的一个标示。下面就为大家解析绑定Service所需要的三个步骤:
第一步:需要在Service中创建一个Binder接口,并且实现:
包含客户端可以调用public方法
或返回当前Service的实例--也包含客户端可以调用的Public方法
或返回Service持有的其他类型的实例--也包含客户端可以调用的Public方法
代码如下:
public class MyBinder extends Binder{
MyService getService(){
return MyService.this;
}
}
第二步:在onBind()中返回Binder实例。
代码如下:
//必须实现的方法,作用是用来返回binder对象
//重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("--onBind--");
return null;
}
第三步:在客户端中,从onServiceConnected()回调方法中接收这个Binder,并且使用Binder包含的Service提供的方法。
比如:
public class MyServiceConn implements ServiceConnection{ MyService.MyBinder binder = null; @Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
binder = (MyService.MyBinder)service;
} @Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
binder = null;
} }
注意:一定要在客户端中声明这个实例:
final MyServiceConn myserviceconn = new MyServiceConn();
客户端在合适的时候也可以进行解绑:
//解除绑定的Service
unbind.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(myserviceconn);
}
});
上述就把Service的启动、停止、绑定、解绑就完成了,下面的则是客户端的一些的代码:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity { private Button start;
private Button stop;
private Button bind;
private Button unbind;
private Intent intent; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.btn1);
stop = (Button)findViewById(R.id.btn2);
bind = (Button)findViewById(R.id.btn3);
unbind = (Button)findViewById(R.id.btn4); final MyServiceConn myserviceconn = new MyServiceConn(); //给按钮设置事件,以便监听Service中的变化
//开启service
start.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
}
}); //结束Service
stop.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(intent);
}
}); //绑定service服务
bind.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
bindService(intent,myserviceconn,Context.BIND_AUTO_CREATE);
}
}); //解除绑定的Service
unbind.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(myserviceconn);
}
});
} }
XML文件的代码(只是一些简单的按钮,就不解释了):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/service" /> <Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StartService" /> <Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StopService" /> <Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bindService" /> <Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unBindService" /> </LinearLayout>
一定要注意在AndroidManifest.xml文件中加上权限:
<service android:name="com.example.servicetest.MyService">
</service>
到这里就完了,有什么不懂或者不对的地方可以留言,至于截图,上述的代码比较详细,我这里就不贴出了。
---恢复内容结束---