Android通知欄前臺服務

1、前臺服務的簡單介紹

前臺服務是那些被認爲用戶知道且在系統內存不足的時候不容許系統殺死的服務。前臺服務必須給狀態欄提供一個通知,它被放到正在運行(Ongoing)標題之下——這就意味着通知只有在這個服務被終止或從前臺主動移除通知後才能被解除。java

最多見的表現形式就是音樂播放服務,應用程序後臺運行時,用戶能夠經過通知欄,知道當前播放內容,並進行暫停、繼續、切歌等相關操做。android

2、爲何使用前臺服務

後臺運行的Service系統優先級相對較低,當系統內存不足時,在後臺運行的Service就有可能被回收,爲了保持後臺服務的正常運行及相關操做,能夠選擇將須要保持運行的Service設置爲前臺服務,從而使APP長時間處於後臺或者關閉(進程未被清理)時,服務可以保持工做。git

3、前臺服務的詳細使用

  1. 建立服務內容,以下(四大組件不要忘記清單文件進行註冊,不然啓動會找不到服務);
public class ForegroundService extends Service {
    
    private static final String TAG = ForegroundService.class.getSimpleName();

	@Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate");
    }
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
    }
    
}
  1. 建立服務通知內容,例如音樂播放,藍牙設備正在鏈接等:
/**
 * 建立服務通知
 */
private Notification createForegroundNotification() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // 惟一的通知通道的id.
    String notificationChannelId = "notification_channel_id_01";

    // Android8.0以上的系統,新建消息通道
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        //用戶可見的通道名稱
        String channelName = "Foreground Service Notification";
        //通道的重要程度
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
        notificationChannel.setDescription("Channel description");
        //LED燈
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        //震動
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
    //通知小圖標
    builder.setSmallIcon(R.drawable.ic_launcher);
    //通知標題
    builder.setContentTitle("ContentTitle");
    //通知內容
    builder.setContentText("ContentText");
    //設定通知顯示的時間
    builder.setWhen(System.currentTimeMillis());
    //設定啓動的內容
    Intent activityIntent = new Intent(this, NotificationActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    //建立通知並返回
    return builder.build();
}
  1. 啓動服務時,建立通知:
@Override
public void onCreate() {
    super.onCreate();
    Log.e(TAG, "onCreate");
    // 獲取服務通知
    Notification notification = createForegroundNotification();
    //將服務置於啓動狀態 ,NOTIFICATION_ID指的是建立的通知的ID
    startForeground(NOTIFICATION_ID, notification);
}
  1. 中止服務時,移除通知:
@Override
public void onDestroy() {
    Log.e(TAG, "onDestroy");
    // 標記服務關閉
    ForegroundService.serviceIsLive = false;
    // 移除通知
    stopForeground(true);
    super.onDestroy();
}
  1. 判斷服務是否啓動及獲取傳遞信息:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e(TAG, "onStartCommand");
    // 標記服務啓動
    ForegroundService.serviceIsLive = true;
    // 數據獲取
    String data = intent.getStringExtra("Foreground");
    Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent, flags, startId);
}

以上就是前臺服務的建立過程,相關注釋已經很明白了,具體使用能夠查看文末的Demo。github

服務建立完畢,接下來就能夠進行服務的啓動了,啓動前不要忘記在清單文件中進行前臺服務權限的添加:ide

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  1. 服務的啓動和中止
//啓動服務
if (!ForegroundService.serviceIsLive) {
    // Android 8.0使用startForegroundService在前臺啓動新服務
    mForegroundService = new Intent(this, ForegroundService.class);
    mForegroundService.putExtra("Foreground", "This is a foreground service.");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(mForegroundService);
    } else {
        startService(mForegroundService);
    }
} else {
    Toast.makeText(this, "前臺服務正在運行中...", Toast.LENGTH_SHORT).show();
}
//中止服務
mForegroundService = new Intent(this, ForegroundService.class);
stopService(mForegroundService);

關於前臺服務的介紹及使用就到這裏了,相關使用已上傳至Github開發記錄,歡迎點擊查閱及Star,我也會繼續補充其它有用的知識及例子在項目上。工具

歡迎點贊、評論,大家的贊同和鼓勵是我寫做的最大動力!

歡迎關注公衆號:幾圈年輪,查看更多有趣的技術、工具、閒言、資源。
公衆號.pngui

相關文章
相關標籤/搜索