image.png
Android 8.0 有一項復(fù)雜功能;系統(tǒng)不允許后臺應(yīng)用創(chuàng)建后臺服務(wù)蔑鹦。 因此偏友,Android 8.0 引入了一種全新的方法,即 Context.startForegroundService()朋截,以在前臺啟動新服務(wù)蛹稍。
startForegroundService
在系統(tǒng)創(chuàng)建服務(wù)后,應(yīng)用有五秒的時間來調(diào)用該服務(wù)的 startForeground()
方法以顯示新服務(wù)的用戶可見通知部服。
如果應(yīng)用在此時間限制內(nèi)未調(diào)用 startForeground()
唆姐,則系統(tǒng)將停止服務(wù)并聲明此應(yīng)用為 ANR。
針對Android 9(API級別28)或更高級別并使用前臺服務(wù)的應(yīng)用程序必須請求 FOREGROUND_SERVICE permission
廓八。
所以現(xiàn)在我們需要在清單文件中添加 Foreground服務(wù)權(quán)限
允許常規(guī)應(yīng)用程序使用 Service.startForeground
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
使用實例
首先創(chuàng)建一個服務(wù):
public class MusicPlayerService extends Service {
private static final String TAG = MusicPlayerService.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand()");
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind()");
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
修改onStartCommand代碼,添加通知:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand()");
// 在API11之后構(gòu)建Notification的方式
Notification.Builder builder = new Notification.Builder
(this.getApplicationContext()); //獲取一個Notification構(gòu)造器
Intent nfIntent = new Intent(this, MainActivity.class);
builder.setContentIntent(PendingIntent.
getActivity(this, 0, nfIntent, 0)) // 設(shè)置PendingIntent
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.mipmap.ic_large)) // 設(shè)置下拉列表中的圖標(biāo)(大圖標(biāo))
.setContentTitle("下拉列表中的Title") // 設(shè)置下拉列表里的標(biāo)題
.setSmallIcon(R.mipmap.ic_launcher) // 設(shè)置狀態(tài)欄內(nèi)的小圖標(biāo)
.setContentText("要顯示的內(nèi)容") // 設(shè)置上下文內(nèi)容
.setWhen(System.currentTimeMillis()); // 設(shè)置該通知發(fā)生的時間
Notification notification = builder.build(); // 獲取構(gòu)建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //設(shè)置為默認(rèn)的聲音
}
在完成Notification通知消息的構(gòu)建后奉芦,在Service的onStartCommand中可以使用startForeground方法來讓Android服務(wù)運(yùn)行在前臺:
// 參數(shù)一:唯一的通知標(biāo)識赵抢;參數(shù)二:通知消息。
startForeground(110, notification);// 開始前臺服務(wù)