Foreground Service前臺服務
介紹前臺服務
前臺服務是那些被認爲用戶知道(用戶所認可的)且在系統內存不足的時候不允許系統殺死的服務。前臺服務必須給狀態欄提供一個通知,它被放到正在運行(Ongoing)標題之下——這就意味着通知只有在這個服務被終止或從前臺主動移除通知後才能被解除。
模擬播放器前臺服務發送通知
1、首先創建一個服務併發送通知
public class MusicService extends Service {
private static final String TAG = "---";
public MusicService() {
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this.getApplicationContext());
builder.setSmallIcon(R.mipmap.ic_launcher).setContentText("text").setContentTitle("title");
//開啓前臺服務
// 參數一:唯一的通知標識;參數二:通知消息。
startForeground(110,builder.build());
//發送一般通知
manager.notify(1,builder.build());
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
// 停止前臺服務--參數:表示是否移除之前的通知
stopForeground(true);
}
}
2、在Activity中添加一個按鈕用於發送通知
public class MusicActivity extends AppCompatActivity {
private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MusicActivity.this,MusicService.class);
startService(intent);
}
});
}
}