Service設置爲前臺服務

通常Service都是運行在後臺,後臺運行的Service系統優先級較低,在系統內存不足的時候,後臺運行的Service可能會被回收。當需求Service一直保持運行且在內存不足的情況下不會被回收,可以將Service設置爲前臺服務。

創建一個前臺服務

public class MyService extends Service{
 private static final String TAG = MyService.class.getSimpleName();
 @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
        setForeground();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        super.onBind(intent);
        return null;
    }
    /**
     * 將Service設置爲前臺
     */
    private void setForeground() {
        Log.i(TAG, "setForeground: ");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("Foreground_Service",
                    "Foreground_Service", NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager == null) {
                return;
            }
            manager.createNotificationChannel(channel);
            Notification notification =
                    new NotificationCompat.Builder(this, "Foreground_Service")
                            .setAutoCancel(true)
                            .setCategory(Notification.CATEGORY_SERVICE)
                            .setOngoing(true)
                            .setPriority(NotificationManager.IMPORTANCE_LOW)
                            .build();
            startForeground(101, notification);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章