分類
- 按綁定方式劃分
1>綁定Service
2>非綁定Service - 按Service類型劃分
1>后臺(tái)服務(wù),Android開發(fā)中多數(shù)用后臺(tái)Service,這種Service的優(yōu)先級(jí)比較低,當(dāng)系統(tǒng)內(nèi)存不足,會(huì)被回收
2>前臺(tái)服務(wù),就是Service和Notification關(guān)聯(lián),用戶可見的服務(wù),不會(huì)因?yàn)閮?nèi)存不足而被回收,簡單理解就是音樂播放器的通知欄彈窗
后臺(tái)服務(wù)
- 啟動(dòng)方式
1> 非綁定Service啟動(dòng)
startService(new Intent().setClass(ServiceDemoActivity.this,NoBindService.class));
2>綁定Service啟動(dòng)
Intent intent = new Intent().setClass(ServiceDemoActivity.this, BindService.class);
bindService(intent,connect,BIND_AUTO_CREATE);
綁定Service需要?jiǎng)?chuàng)建connect,實(shí)現(xiàn)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) {
}
};
前臺(tái)服務(wù)
- 創(chuàng)建 ,跟后臺(tái)Service創(chuàng)建方式一樣,寫個(gè)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();
}
}
- 構(gòu)建通知消息
在Service的onCreate
中添加如下代碼構(gòu)建Notification
@Override
public void onCreate() {
super.onCreate();
// 創(chuàng)建通知
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","前臺(tái)通知",NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(this,"channel_id")
.setContentTitle("標(biāo)題")
.setContentText("內(nèi)容")
.setLargeIcon(largeIcon)
.setSmallIcon(R.drawable.ic_launcher)
.build();
Log.d(TAG, "onStartCommand: 前臺(tái)服務(wù)啟動(dòng)");
/**
* 開啟前臺(tái)服務(wù)
* @parame1是服務(wù)的唯一標(biāo)識(shí)
* @param2是通知
*/
startForeground(1, notification);
}