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);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章