一市殷、普通服務(wù)
1 . 定義服務(wù)
package com.ysy.mythreaddemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
public MyService () {
}
@Override
public void onCreate () {
super.onCreate ();
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
return super.onStartCommand (intent, flags, startId);
}
@Override
public IBinder onBind (Intent intent) {
throw new UnsupportedOperationException ("Not yet implemented");
}
@Override
public void onDestroy () {
super.onDestroy ();
}
}
2 . 啟動和停止服務(wù)
- 啟動服務(wù)
Intent service = new Intent (this,MyService.class);
startService (service);
- 停止服務(wù)
stopService (service);
3 . 綁定和解綁服務(wù)勘究、調(diào)用服務(wù)中的方法矮湘。
- 綁定服務(wù)前的準(zhǔn)備
在服務(wù)中定義一個(gè)公共的繼承Binder類,并實(shí)現(xiàn)一個(gè)自定義的接口(為了調(diào)用服務(wù)中的方法)的MyBinder類口糕,在服務(wù)的onBind()方法中創(chuàng)建MyBinder對象并返回缅阳。
public class MyBinder extends Binder implements IService{
@Override
public void startDownload () {
Log.d ("ysy","start download!");
}
@Override
public int getProgress () {
Log.d ("ysy","get progress!");
return 0;
}
}
@Override
public IBinder onBind (Intent intent) {
return new MyBinder ();
}
在活動中創(chuàng)建實(shí)現(xiàn)ServiceConnection接口的類,用于綁定服務(wù)景描。
public class MyConnection implements ServiceConnection{
@Override
public void onServiceConnected (ComponentName name, IBinder service) {
MyService.MyBinder mService = (MyService.MyBinder) service;
mService.startDownload ();
int progress = mService.getProgress ();
Log.d ("ysy","progress "+progress);
}
@Override
public void onServiceDisconnected (ComponentName name) {
}
}
- 綁定服務(wù)
conn = new MyConnection ();
Intent service = new Intent (this,MyService.class);
bindService (service,conn,BIND_AUTO_CREATE);
解綁服務(wù)
unbindService (conn);
調(diào)用服務(wù)中的方法
@Override
public void onServiceConnected (ComponentName name, IBinder service) {
MyService.MyBinder mService = (MyService.MyBinder) service;
mService.startDownload ();
int progress = mService.getProgress ();
Log.d ("ysy","progress "+progress);
}
4 . 服務(wù)的幾個(gè)規(guī)則
- 服務(wù)可以被多次啟動十办,每次啟動都會執(zhí)行onStartCommand()方法
- 服務(wù)可以多次綁定,但只會執(zhí)行一次onBind()方法超棺。
- 服務(wù)只能解綁一次向族,解綁多次會出錯。
- 服務(wù)的onCreate()方法只會在第一次啟動或者第一次綁定時(shí)調(diào)用棠绘。
- 服務(wù)的onDestory()方法只會在停止服務(wù)的時(shí)候件相,或者在未啟動但綁定狀態(tài)下,解綁時(shí)調(diào)用弄唧。
二适肠、前臺服務(wù)
- 前臺服務(wù)與普通服務(wù)的區(qū)別是,前臺服務(wù)啟動起來之后候引,會在系統(tǒng)的狀態(tài)欄一直有個(gè)圖標(biāo)顯示侯养,下拉狀態(tài)之后會看到更詳細(xì)的信息。
- 前臺服務(wù)的定義與普通服務(wù)定義的不同是澄干,前臺服務(wù)會在普通服務(wù)的onCreate()方法中添加以下代碼逛揩。
Intent intent = new Intent (this,MainActivity.class);
PendingIntent pi = PendingIntent.getActivity (this,0,intent,0);
Notification build = new NotificationCompat.Builder (this)
.setContentTitle ("this is title")
.setContentText ("this is content")
.setSmallIcon (R.mipmap.ic_launcher)
.setWhen (System.currentTimeMillis ())
.setContentIntent (pi)
.build ();
startForeground (1,build);
- 前臺服務(wù)的啟動與普通服務(wù)的啟動相同。
三麸俘、在服務(wù)中做耗時(shí)操作
- 服務(wù)是運(yùn)行在主線程中的辩稽,android規(guī)定不能在主線程中做耗時(shí)操作。
- 使用IntentService可以在服務(wù)中做耗時(shí)操作从媚,定義如下:
package com.ysy.mythreaddemo;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p>
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class MyIntentService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "com.ysy.mythreaddemo.action.FOO";
private static final String ACTION_BAZ = "com.ysy.mythreaddemo.action.BAZ";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "com.ysy.mythreaddemo.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.ysy.mythreaddemo.extra.PARAM2";
public MyIntentService () {
super ("MyIntentService");
}
/**
* Starts this service to perform action Foo with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionFoo (Context context, String param1, String param2) {
Intent intent = new Intent (context, MyIntentService.class);
intent.setAction (ACTION_FOO);
intent.putExtra (EXTRA_PARAM1, param1);
intent.putExtra (EXTRA_PARAM2, param2);
context.startService (intent);
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionBaz (Context context, String param1, String param2) {
Intent intent = new Intent (context, MyIntentService.class);
intent.setAction (ACTION_BAZ);
intent.putExtra (EXTRA_PARAM1, param1);
intent.putExtra (EXTRA_PARAM2, param2);
context.startService (intent);
}
@Override
protected void onHandleIntent (Intent intent) {
if (intent != null) {
final String action = intent.getAction ();
if (ACTION_FOO.equals (action)) {
final String param1 = intent.getStringExtra (EXTRA_PARAM1);
final String param2 = intent.getStringExtra (EXTRA_PARAM2);
handleActionFoo (param1, param2);
} else if (ACTION_BAZ.equals (action)) {
final String param1 = intent.getStringExtra (EXTRA_PARAM1);
final String param2 = intent.getStringExtra (EXTRA_PARAM2);
handleActionBaz (param1, param2);
}
}
Log.d ("ysy","Thread is "+Thread.currentThread ().getId ());
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionFoo (String param1, String param2) {
// TODO: Handle action Foo
throw new UnsupportedOperationException ("Not yet implemented");
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleActionBaz (String param1, String param2) {
// TODO: Handle action Baz
throw new UnsupportedOperationException ("Not yet implemented");
}
@Override
public void onDestroy () {
super.onDestroy ();
Log.d ("ysy","onDestroy");
}
}
- 可以將耗時(shí)操作放在MyIntentService的onHandleIntent ()方法中逞泄,這個(gè)方法中的代碼是運(yùn)行在子線程中。