service是運行後臺的一段代碼,並且和Activity不同,它不能直接和用戶交互,也不能自行啓動,對於service來說,主要用於在後臺運行,比方說後臺下載,後臺播放音樂等,和Activity一樣於oncreate後創建,ondestroy後銷燬,一個service的啓動有兩種方式,一種是Context.StartService的方式來啓動,這種方式啓動服務後,該服務就和啓動程序毫無關聯了,只有在調用context.stopservice後,或者服務自行死亡後,該服務纔會被銷燬,第二種是通過Context.bindservice的方式綁定程序後啓動服務,此時服務就和改程序綁定在一起了,當該程序死亡時服務也會被終結掉,這就是服務的基本概念
下面來介紹下服務的使用方式
1、首先要繼承Service類並重寫其中的onStart,onDestroy,onbind,onunbind,oncreate這幾個方法
public class MyService extends Service {
//定義log的標籤
private static final String str="ServiceDemo";
private Mybind binder=new Mybind();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i(str,"start bind service");
return binder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i(str,"start create service");
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.i(str,"start destroy service");
super.onDestroy();
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
Log.i(str,"start service");
super.onStart(intent, startId);
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Log.i(str,"start unbind service");
return super.onUnbind(intent);
}
//此方法是爲了可以在Acitity中獲得服務的實例
public class Mybind extends Binder{
MyService getService(){
return MyService.this;
}
}
}
2.在入口程序中註冊服務<service android:name=".MyService"></service>
3.使用startService或是bindService啓動服務
(1)通過startservice啓用服務時,android會首先調用oncreate方法創建服務,之後調用onstart啓用服務,在調用stopservice結束服務時會自行調用ondestroy銷燬服務,需要注意的是在服務被創建後,多次調用startservice並不會重複調用oncreate,除非服務銷燬後,但多次調用startservice會多次調用onstart
(2)通過bindservice啓用服務時,android會首先調用oncreate方法創建服務,之後調用onbind啓用綁定服務,在調用unbindservice結束服務時會先調用onunbind解除綁定,在調用ondestroy銷燬服務,需要注意的是在服務被創建後,多次調用bindservice並不會重複調用oncreate和onbind,除非該服務被銷燬
下面重點介紹一下bindservice的啓用方式
bindService一共有三個參數第一個參數爲意圖,第二個服務連接狀態,第三個爲標誌
第一個參數的主要目的是爲了定義要啓動哪個服務,第二個參數就是指示連接該服務狀態,第三個參數是定義其進行的方式
既然是第一個參數是intent,就需要先定義一個意圖參數即
Intent intent=new Intent();然後和Activity一樣通過setClass來指定要啓動的服務
intent.setClass(ServiceDemo.this,MyService.class);
第二個參數是爲了指示連接該服務狀態
private ServiceConnection conn=new ServiceConnection(){
@Override
//在連接成功時調用
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
Log.i("ServiceDemo","connected Service");
}
@Override
//在服務連接失敗時調用
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
Log.i("ServiceDemo","disconnected Service");
}
};
所以完整的調用方式如下
Intent intent=new Intent();
intent.setClass(ServiceDemo.this,MyService.class);
private ServiceConnection conn=new ServiceConnection(){
@Override
//在連接成功時調用
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
Log.i("ServiceDemo","connected Service");
}
@Override
//在服務連接失敗時調用
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
Log.i("ServiceDemo","disconnected Service");
}
};
mcontext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
下面是一個方便理解服務進行過程的例子,提供了兩種不同啓用方式,本文中並沒有介紹兩種啓動方式複合運用的場景,也可以通過下面的程序自行理解
servicedemo.Activity
package com.example.ui_demo;
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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ServiceDemo extends Activity {
private MyService mservice;
private Button mButtonstart;
private Button mButtonstop;
private Button mButtonexit;
private Button mButtonbind;
private Button mButtonbindstop;
private Context mcontext;
private ServiceConnection conn=new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
Log.i("ServiceDemo","connected Service");
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
Log.i("ServiceDemo","disconnected Service");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_demo);
setup();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.service_demo, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setup(){
mcontext=ServiceDemo.this;
mButtonstart=(Button) this.findViewById(R.id.startservice);
mButtonstop=(Button) this.findViewById(R.id.stopservice);
mButtonexit=(Button) this.findViewById(R.id.exitservice);
mButtonbind=(Button) this.findViewById(R.id.bindservice);
mButtonbindstop=(Button) this.findViewById(R.id.stopbindservice);
Mybutton mbutton=new Mybutton();
mButtonstart.setOnClickListener(mbutton);
mButtonstop.setOnClickListener(mbutton);
mButtonexit.setOnClickListener(mbutton);
mButtonbind.setOnClickListener(mbutton);
mButtonbindstop.setOnClickListener(mbutton);
}
public class Mybutton implements OnClickListener{
@Override
public void onClick(View vi ) {
// TODO Auto-generated method stub
if(vi==mButtonstart){
Intent intent=new Intent();
intent.setClass(ServiceDemo.this,MyService.class);
mcontext.startService(intent);
}else if(vi==mButtonstop){
Intent intent=new Intent();
intent.setClass(ServiceDemo.this,MyService.class);
mcontext.stopService(intent);
}else if(vi==mButtonexit){
ServiceDemo.this.finish();
}else if(vi==mButtonbind){
Intent intent=new Intent();
intent.setClass(ServiceDemo.this,MyService.class);
mcontext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
}else if(vi==mButtonbindstop){
mcontext.unbindService(conn);
}
}
}
}
action_servicedemo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ui_demo.ServiceDemo" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow>
<Button
android:id="@+id/startservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/stopservice"
android:layout_below="@+id/stopservice"
android:layout_column="1"
android:layout_marginTop="16dp"
android:text="啓用服務"
android:textSize="20sp" />
</TableRow>
<TableRow>
<Button
android:id="@+id/stopservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginTop="24dp"
android:text="停止服務"
android:textSize="20sp" />
</TableRow>
<TableRow>
<Button
android:id="@+id/bindservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginTop="24dp"
android:text="啓動綁定服務"
android:textSize="20sp" />
</TableRow>
<TableRow>
<Button
android:id="@+id/stopbindservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginTop="24dp"
android:text="停止綁定服務"
android:textSize="20sp" />
</TableRow>
<TableRow>
<Button
android:id="@+id/exitservice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginTop="24dp"
android:text="退出"
android:textSize="20sp" />
</TableRow>
</TableLayout>
</RelativeLayout>
MyService.java
package com.example.ui_demo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
//定義log的標籤
private static final String str="ServiceDemo";
private Mybind binder=new Mybind();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i(str,"start bind service");
return binder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i(str,"start create service");
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.i(str,"start destroy service");
super.onDestroy();
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
Log.i(str,"start service");
super.onStart(intent, startId);
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Log.i(str,"start unbind service");
return super.onUnbind(intent);
}
public class Mybind extends Binder{
MyService getService(){
return MyService.this;
}
}
}