一、普通服务
1 . 定义服务
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 . 启动和停止服务
- 启动服务
Intent service = new Intent (this,MyService.class);
startService (service);
- 停止服务
stopService (service);
3 . 绑定和解绑服务、调用服务中的方法。
- 绑定服务前的准备
在服务中定义一个公共的继承Binder类,并实现一个自定义的接口(为了调用服务中的方法)的MyBinder类,在服务的onBind()方法中创建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 ();
}
在活动中创建实现ServiceConnection接口的类,用于绑定服务。
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) {
}
}
- 绑定服务
conn = new MyConnection ();
Intent service = new Intent (this,MyService.class);
bindService (service,conn,BIND_AUTO_CREATE);
解绑服务
unbindService (conn);
调用服务中的方法
@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 . 服务的几个规则
- 服务可以被多次启动,每次启动都会执行onStartCommand()方法
- 服务可以多次绑定,但只会执行一次onBind()方法。
- 服务只能解绑一次,解绑多次会出错。
- 服务的onCreate()方法只会在第一次启动或者第一次绑定时调用。
- 服务的onDestory()方法只会在停止服务的时候,或者在未启动但绑定状态下,解绑时调用。
二、前台服务
- 前台服务与普通服务的区别是,前台服务启动起来之后,会在系统的状态栏一直有个图标显示,下拉状态之后会看到更详细的信息。
- 前台服务的定义与普通服务定义的不同是,前台服务会在普通服务的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);
- 前台服务的启动与普通服务的启动相同。
三、在服务中做耗时操作
- 服务是运行在主线程中的,android规定不能在主线程中做耗时操作。
- 使用IntentService可以在服务中做耗时操作,定义如下:
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");
}
}
- 可以将耗时操作放在MyIntentService的onHandleIntent ()方法中,这个方法中的代码是运行在子线程中。