分类
- 按绑定方式划分
1>绑定Service
2>非绑定Service - 按Service类型划分
1>后台服务,Android开发中多数用后台Service,这种Service的优先级比较低,当系统内存不足,会被回收
2>前台服务,就是Service和Notification关联,用户可见的服务,不会因为内存不足而被回收,简单理解就是音乐播放器的通知栏弹窗
后台服务
- 启动方式
1> 非绑定Service启动
startService(new Intent().setClass(ServiceDemoActivity.this,NoBindService.class));
2>绑定Service启动
Intent intent = new Intent().setClass(ServiceDemoActivity.this, BindService.class);
bindService(intent,connect,BIND_AUTO_CREATE);
绑定Service需要创建connect,实现Activity和Service的连接
private BindService.MyBinder mService = null;
//Service的连接
private ServiceConnection connect = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mService = (BindService.MyBinder) iBinder;
mService.methodInBindServiceUsedByActivity();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
前台服务
- 创建 ,跟后台Service创建方式一样,写个Service类继承自
Service
public class FrontService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
- 构建通知消息
在Service的onCreate
中添加如下代码构建Notification
@Override
public void onCreate() {
super.onCreate();
// 创建通知
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.drawable.test1);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("channel_id","前台通知",NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(this,"channel_id")
.setContentTitle("标题")
.setContentText("内容")
.setLargeIcon(largeIcon)
.setSmallIcon(R.drawable.ic_launcher)
.build();
Log.d(TAG, "onStartCommand: 前台服务启动");
/**
* 开启前台服务
* @parame1是服务的唯一标识
* @param2是通知
*/
startForeground(1, notification);
}