Is there any way to run service continuously?

前端 未结 3 1404
小蘑菇
小蘑菇 2020-11-30 08:27

There are few questions similar to this on Stack Overflow but none of the solutions are working for me

The problem is with only few devices like OnePlus and MI, The

3条回答
  •  悲&欢浪女
    2020-11-30 09:00

    Here are few things which helped little .

    In AndroidManifest.xml add line android:enabled="true"

    
    

    Inside service Add alarm to wake up again after 2 seconds .

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        initAlarm();
        super.onTaskRemoved(rootIntent);
    }
    
       private void initAlarm() {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, StartServiceReceiver.class);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() +
                        2000, alarmIntent);
    
    }
    

    Create a receiver StartServiceReceiver and in it just start service again .

    For Mi devices we need to allow a permission inside setting to allows service to start in background

提交回复
热议问题