Need code example on how to run an Android service forever in the background even when device sleeping, like Whatsapp?

后端 未结 5 1984
死守一世寂寞
死守一世寂寞 2020-11-30 19:51

I have tried various ways to achieve this, but my service eventually gets killed.

I want to use AlarmManager to trigger a class every one hour. Even if the device is

5条回答
  •  没有蜡笔的小新
    2020-11-30 20:25

    Request partial WakeLock.

    
    
     PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
    mWakeLock.acquire();
    

    onStartCommand retrun START_STICKY :

    @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId); 
            return START_STICKY;
        }
    

提交回复
热议问题