Служба не перезапустить после того, как вычеркнул из недавнего списка в xiaomi - PullRequest
0 голосов
/ 02 февраля 2019

У меня служба запущена из Manifest, служба работает нормально, когда запускается в первый раз.Он показывает 2 запущенных приложения - 1 процесс и 1 сервис.но когда я удаляю свое приложение из списка недавних задач, оно не запускает мой сервис автоматически на устройствах xiaomi.Он успешно запускается автоматически на других устройствах, таких как Lenovo.

Вот мой класс обслуживания: -

public class StickyService extends Service {

    private static final String TAG = "StickyService";

    @Override
    public void onCreate() {
        super.onCreate();

        startReceiver();

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            startMyOwnForeground();
        } else {
            startForeground(1, new Notification());
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startMyOwnForeground() {
        startTimer();
        String NOTIFICATION_CHANNEL_ID = "e xample.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");

        sendBroadcast(new Intent("GET_BUZZER"));

        //create an intent that you want to start again.
        Intent intent = new Intent(getApplicationContext(), StickyService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 1, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 2000, pendingIntent);
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.e(TAG, "onTaskRemoved");

        sendBroadcast(new Intent("GET_BUZZER"));

        //create an intent that you want to start again.
        Intent intent = new Intent(getApplicationContext(), StickyService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 1, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 2000, pendingIntent);

        super.onTaskRemoved(rootIntent);
    }

    private void startReceiver() {
        RestartReceiver receiver = new RestartReceiver();
        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction("GET_BUZZER");
        registerReceiver(receiver, localIntentFilter);
        startService(new Intent(this, StickyService.class));
    }

    public class RestartReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "Inside receiver inline class");

            Intent myIntent = new Intent(context, StickyService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(myIntent);
            } else {
                context.startService(myIntent);
            }
        }
    }

}

Я регистрирую свой широковещательный приемник в коде Java (не в манифесте).Я использовал класс обслуживания для регистрации широковещательного приемника.

Манифест: -

<service
    android:name=".ForceCloseAutoStart.StickyService"
    android:process=":StickyService" />

Я также делаю ниже изменения в устройстве xiaomi: - Settings->Battery->Manage Apps Battery Usage Все еще не работает.

Пожалуйста, помогите с любым решением, которое работает на этих устройствах.

1 Ответ

0 голосов
/ 02 февраля 2019

Я думаю, вам нужно включить службу автозапуска на вашем устройстве Xiaomi.

  1. Откройте меню безопасности на вашем устройстве Xiaomi.
  2. Нажмите «Разрешения».
  3. Нажмите «Автозапуск».
  4. Проведите, чтобы включить автозапуск для вашего приложения.

Проверьте здесь: - http://nine -faq.9folders.com / articles / 8772-как управлять автоматическим запуском-обслуживанием на устройствах xiaomi-устройства

...