package net.gotev.sipservice;

import android.app.Service;
import android.content.Intent;
import android.os.*;
import android.os.Process;

/**
 * Service with a background worker thread.
 * @author gotev (Aleksandar Gotev)
 */
class BackgroundService extends Service {

    private HandlerThread mWorkerThread;
    private Handler mHandler;
    private PowerManager.WakeLock mWakeLock;

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

        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getSimpleName());

        mWakeLock.acquire();

        mWorkerThread = new HandlerThread(getClass().getSimpleName(), Process.THREAD_PRIORITY_FOREGROUND);
        mWorkerThread.setPriority(Thread.MAX_PRIORITY);
        mWorkerThread.start();
        mHandler = new Handler(mWorkerThread.getLooper());
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWorkerThread.quitSafely();
        mWakeLock.release();
    }

    protected void enqueueJob(Runnable job) {
        mHandler.post(job);
    }

    protected void enqueueDelayedJob(Runnable job, long delayMillis) {
        mHandler.postDelayed(job, delayMillis);
    }

    protected void dequeueJob(Runnable job) {
        mHandler.removeCallbacks(job);
    }
}

@@ -107,35 +107,8 @@
 s.*;
-%0Aimport android.os.Process;
 %0A%0A/*
@@ -240,49 +240,8 @@
  %7B%0A%0A
-    private HandlerThread mWorkerThread;%0A
     
@@ -385,460 +385,88 @@
 ();%0A
-%0A        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);%0A        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getSimpleName());%0A%0A        mWakeLock.acquire();%0A%0A        mWorkerThread = new HandlerThread(getClass().getSimpleName(), Process.THREAD_PRIORITY_FOREGROUND);%0A        mWorkerThread.setPriority(Thread.MAX_PRIORITY);%0A        mWorkerThread.start();%0A        mHandler = new Handler(mWorkerThread.getLooper()
+        mHandler = new Handler(Looper.getMainLooper());%0A        acquireWakeLock(
 );%0A 
@@ -639,61 +639,23 @@
     
-mWorkerThread.quitSafely();%0A        mWakeLock.release
+releaseWakeLock
 ();%0A
@@ -906,32 +906,32 @@
 Runnable job) %7B%0A
-
         mHandler
@@ -958,11 +958,394 @@
 );%0A    %7D
+%0A%0A    public void acquireWakeLock() %7B%0A        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);%0A        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getSimpleName());%0A        mWakeLock.acquire();%0A    %7D%0A%0A    public void releaseWakeLock() %7B%0A        if (mWakeLock != null && mWakeLock.isHeld()) %7B%0A            mWakeLock.release();%0A        %7D%0A    %7D
 %0A%7D%0A

remove background thread on SipService - #147