服務:在後臺運行,沒有界面的組件。java
服務生命週期以下:android
兩種啓動方式:app
一、startService(): onCreate()-->onStartCommand()-->onDestroy().
二、bindService(): onCreate()-->onBind()-->onUnbind()-->onDestroy().異步
1、定義一個服務,得作到如下:ide
1.繼承Service,重寫onBind()、onCreate()、onStartCommand()和 onDestroy();this
2.在AndroidManifest裏面註冊才能生效.spa
2、啓動服務:線程
Intent startIntent=new Intent(this,MyService.class);3d
startService(startIntent);code
3、中止服務:
Intent stopIntent=new Intent(this,MyService.class);
stopService(stopIntent);
4、綁定服務:
1.onBind()方法返回Binder對象;
2.建立了ServiceConnection 的匿名類,重寫onServiceConnected()方法和 onServiceDisconnected()方法;
3.用bindService()方法將 Activity 和 Service 進行綁定。
bindService()方法接收三個參數,第一個參數就是 Intent 對象,第二個參數是ServiceConnection 的實例,第三個
參數則是一個標誌位,能夠傳入 BIND_AUTO_CREATE 表示在活動和服務進行綁定後自動建立服務。
示例以下:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
5、解綁服務:
unbindService(connection);
6、使用IntentService
優勢:
1.異步,能夠在子線程處理耗時操做
2.執行完畢自動中止
代碼示例以下:
MainActivity.java
package com.example.servicedemo;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private MyService.DownloadBinder downloadBinder;
private Button startIntentService;
private boolean mIsBound =false;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
downloadBinder=(MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button)findViewById(R.id.start);
stopService=(Button)findViewById(R.id.stop);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
startIntentService = (Button) findViewById(R.id.start_intent_service);
startIntentService.setOnClickListener(this);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.start:
Intent startIntent=new Intent(this,MyService.class);
startService(startIntent);
break;
case R.id.stop:
Intent stopIntent=new Intent(this,MyService.class);
stopService(stopIntent);
break;
case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);//綁定服務
mIsBound = true;
break;
case R.id.unbind_service:
if(mIsBound) {
unbindService(connection); //解綁服務
Log.d("MainActivity","UnbindService");
mIsBound=false;
}
break;
case R.id.start_intent_service:
Log.d("MainActivity","Thread id is "+Thread.currentThread().getId());
Intent intentService=new Intent(this,MyIntentService.class);
startService(intentService);
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
MyService.java:
package com.example.servicedemo; 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{ private DownloadBinder mBinder = new DownloadBinder(); //繼承Binder的內部類,一個方法開始下載,另外一個方法獲取進度 class DownloadBinder extends Binder { public void startDownload() { Log.d("MyService", "startDownload executed"); } public int getProgress() { Log.d("MyService", "getProgress executed"); return 0; } } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return mBinder; } public void onCreate(){ super.onCreate(); Log.d("MyService","onCreate executed"); } public int onStartCommand(Intent intent,int flags,int startId){ Log.d("MyService","onStartCommand executed"); return super.onStartCommand(intent,flags,startId); } public void onDestroy(){ Log.d("MyService","onDestroy executed"); super.onDestroy(); } }
MyIntentService.java:
package com.example.servicedemo; import android.app.IntentService; import android.content.Intent; import android.util.Log; public class MyIntentService extends IntentService{ public MyIntentService() { super("MyIntentService"); // TODO Auto-generated constructor stub } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub Log.d("MyIntentService", "Thread id is " + Thread.currentThread(). getId()); } public void onDestroy() { super.onDestroy(); Log.d("MyIntentService", "onDestroy executed"); } }
activity_main.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=".MainActivity" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/start" android:text="start service" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/stop" android:text="stop service" android:layout_below="@id/start" /> <Button android:id="@+id/bind_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Bind Service" android:layout_below="@id/stop" /> <Button android:id="@+id/unbind_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Unbind Service" android:layout_below="@id/bind_service" /> <Button android:id="@+id/start_intent_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start IntentService" android:layout_below="@id/unbind_service" /> </RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.servicedemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.servicedemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyService" ></service> <service android:name=".MyIntentService"></service> </application> </manifest>
運行效果以下所示:
start Service:
屢次start Service:
Bind Service:
start IntentService: