2

I have a background service in my application for detect wifi spots. He's running well, but when device enter in sleep mode, this service is restarted. I have configured Wake Lock and Wifi Lock.

My code: (Create service)

public void onCreate(){
    super.onCreate();
    Settings.System.putInt(getContentResolver(),
    Settings.System.WIFI_SLEEP_POLICY, 
    Settings.System.WIFI_SLEEP_POLICY_NEVER);

    wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "SD1xWifi");
    wifiLock.acquire();

    mgr = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wakeLock = mgr.newWakeLock(PowerManager.FULL_WAKE_LOCK, "SD1x");
    wakeLock.acquire();
}

My code: (Start service)

public void onStart(Intent i, int x){
    super.onStart(i, x);
    Log.i("TesteWifi", "Find spots wifi started");
    try{
        wm.startScan();
        timer.scheduleAtFixedRate(new mainTask(), 0, 1000);
    }catch(Exception e){
        e.printStackTrace();
        Log.i("TesteWifi", "Error on start service find wifi");
    }
}

My code: (TimerTask)

 private class mainTask extends TimerTask {

        @Override
        public void run() {
             // ...timertask processes...
        }

My code: (Service Started in MainActivity)

try {
    startService(obj.getServiceAutoCheckin());
} catch (Exception e) {
    Log.i("Services", "ERRO: " + e.getMessage());
}

Why my service is restarted?

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
JARPSimoes
  • 23
  • 3
  • How you are starting this service? – minhaz Apr 24 '13 at 16:18
  • Will you show me your Service code ? – Ronak Mehta Apr 24 '13 at 16:21
  • Probably you are doing this all wrong - post more details (and better formatted). For one you should be using alarm manager and not a long running service : http://stackoverflow.com/questions/15451347/android-design-background-long-running-service-or-alarmmanager. You are releasing the lock don't you ? Post more code and better explained – Mr_and_Mrs_D Apr 26 '13 at 21:21
  • When replying to someone add @someone - I just saw this accidentally - if you post more code and better explained I could post some code too :) – Mr_and_Mrs_D Apr 29 '13 at 17:30

2 Answers2

1

use broadcast receiver to get service intent from service.

MR. Kumar
  • 661
  • 8
  • 25
0

I solved the problem with changing the service startup event. I changed the event by onStartCommand. The service response is START_STICKY.

Docs

JARPSimoes
  • 23
  • 3