Android 8.0 有一項複雜功能;系統不允許後臺應用創建後臺服務。 因此,Android 8.0 引入了一種全新的方法,即 Context.startForegroundService(),以在前臺啓動新服務。
startForegroundService
在系統創建服務後,應用有五秒的時間來調用該服務的 startForeground()
方法以顯示新服務的用戶可見通知。
如果應用在此時間限制內未調用 startForeground()
,則系統將停止服務並聲明此應用爲 ANR。
針對Android 9(API級別28)或更高級別並使用前臺服務的應用程序必須請求 FOREGROUND_SERVICE permission
。
所以現在我們需要在清單文件中添加 Foreground服務權限
允許常規應用程序使用 Service.startForeground
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
使用實例
首先創建一個服務:
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之後構建Notification的方式
Notification.Builder builder = new Notification.Builder
(this.getApplicationContext()); //獲取一個Notification構造器
Intent nfIntent = new Intent(this, MainActivity.class);
builder.setContentIntent(PendingIntent.
getActivity(this, 0, nfIntent, 0)) // 設置PendingIntent
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.mipmap.ic_large)) // 設置下拉列表中的圖標(大圖標)
.setContentTitle("下拉列表中的Title") // 設置下拉列表裏的標題
.setSmallIcon(R.mipmap.ic_launcher) // 設置狀態欄內的小圖標
.setContentText("要顯示的內容") // 設置上下文內容
.setWhen(System.currentTimeMillis()); // 設置該通知發生的時間
Notification notification = builder.build(); // 獲取構建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //設置爲默認的聲音
}
在完成Notification通知消息的構建後,在Service的onStartCommand中可以使用startForeground方法來讓Android服務運行在前臺:
// 參數一:唯一的通知標識;參數二:通知消息。
startForeground(110, notification);// 開始前臺服務