سؤال

I building a Android based SMS Server.

It shall request server (each x seconds) for new SMSes to send (in an infinite loop). The Android device will be always plugged-in via USB to the server.

The fetching of the new messages is running as a service and I need it to run 24/7. Since battery draining is not an issue here, how should I use the WakeLock?

As I read some articles about the partial lock it seems to be sufficient.

But yet I did not find any clues when should I call the wakeLock.acquire(); and wakeLock.release();

I do not suppose that it could work like that:

while(true){
    wakeLock.acquire();
    //Do stuff
    wakeLock.release();
    Thread.sleep(10000);
}

Considering the idea... Any inputs would be greatly apperciated. For example does it make sense to scheduler a daily restart of the phone so it will not get stucked? etc...

هل كانت مفيدة؟

المحلول

As explained here, various type of lock can be used. If you want to be always on, then you can acquire it outside the loop :

boolean end = false;
wakeLock.acquire();
while(!end){

    //Do stuff

    Thread.sleep(10000);
}
wakeLock.release();

But you shouldn't really use a loop for that, try an handler instead to do repeating tasks : http://developer.android.com/reference/android/os/Handler.html

Example :

    private class MyRunnable implements Runnable {

    @Override
    public void run() {
        // Do stuff
        handler.postDelayed(new MyRunnable(), 100000);

    }

}   

Handler handler = new android.os.Handler();
handler.postDelayed(new MyRunnable(), 1000000);

The handler is useful if you need to do a repeating task often and with a short period. If there period is longer (like few hours), use the AlarmManager : Alarm Manager Example That is a good example of what you can do, and they also use a wakelock for their tasks.

نصائح أخرى

use the bellow way to wake up the device

private void wakeUpTheDevice()
{

    pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wL = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "wakeupdevice");   
    if ((wL != null) &&         // we have a WakeLock
            (wL.isHeld() == false) ){  // but we don't hold it 
        wL.acquire();
        }
  }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top