分类
按运行地点分类
本地服务(Local)
该服务依附在主进程上
远程服务(Remote)
该服务是独立的进程
remote服务还是很少见的,并且一般都是系统服务
按运行类型分类
前台服务
会在通知一栏显示 ONGOING 的 Notification
后台服务
默认的服务即为后台服务,即不会在通知一栏显示 ONGOING 的 Notification
按使用方式分类
- startService 启动的服务
- bindService 启动的服务
- startService 同时也 bindService 启动的服务
生命周期
用法
- 启动服务、停止服务、绑定服务、解除绑定、前台服务
public class MyService extends Service{
private static final String TAG = "MyService";
private DownloadBinder downloadBinder = new DownloadBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return downloadBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_menu_camera);
builder.setContentTitle("my notification");
builder.setContentText("hello world!");
builder.setAutoCancel(true);
Intent intent = new Intent(this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notificationManager.notify(0x11, builder.build());
//startForeground(0x11, builder.build());
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
class DownloadBinder extends Binder{
public void startDownload(){
Log.d(TAG, "start download...");
}
public int getProgress(){
Log.d(TAG, "get progress");
return 0;
}
}
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stop_service:
Intent stopService = new Intent(this, MyService.class);
stopService(stopService);
break;
case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
}
}
远程服务
将一个普通的Service转换成远程Service其实非常简单,只需要在注册Service的时候将它的android:process属性指定成:remote就可以了。但是 bindService() 方法会让 Activity 和远程 Service(MyService) 建立关联,现在 Activity 和 MyService 不在同一个进程,这个方法会让程序崩溃。
让Activity与一个远程Service建立关联,就要使用AIDL来进行跨进程通信了(IPC)。