Created
May 15, 2015 07:30
-
-
Save Den-Rimus/9f632e1553de335f3455 to your computer and use it in GitHub Desktop.
Unstoppable intent service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.mobindustry.shopaholic.service; | |
import android.app.Service; | |
import android.content.Intent; | |
import android.os.Handler; | |
import android.os.HandlerThread; | |
import android.os.IBinder; | |
import android.os.Looper; | |
import android.os.Message; | |
/** Same as IntentService but lacks stopSelf() call after handled all work. | |
* MUST be stopped explicitly or will run infinitely! | |
* For documentation see {@link android.app.IntentService} */ | |
public abstract class UnstoppableIntentService extends Service { | |
private volatile Looper mServiceLooper; | |
private volatile ServiceHandler mServiceHandler; | |
private String mName; | |
private boolean mRedelivery; | |
private final class ServiceHandler extends Handler { | |
public ServiceHandler(Looper looper) { | |
super(looper); | |
} | |
@Override | |
public void handleMessage(Message msg) { | |
onHandleIntent((Intent)msg.obj); | |
// stopSelf(msg.arg1); // here's where magic happens | |
} | |
} | |
public UnstoppableIntentService(String name) { | |
super(); | |
mName = name; | |
} | |
public void setIntentRedelivery(boolean enabled) { | |
mRedelivery = enabled; | |
} | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); | |
thread.start(); | |
mServiceLooper = thread.getLooper(); | |
mServiceHandler = new ServiceHandler(mServiceLooper); | |
} | |
@Override | |
public void onStart(Intent intent, int startId) { | |
Message msg = mServiceHandler.obtainMessage(); | |
msg.arg1 = startId; | |
msg.obj = intent; | |
mServiceHandler.sendMessage(msg); | |
} | |
@Override | |
public int onStartCommand(Intent intent, int flags, int startId) { | |
onStart(intent, startId); | |
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; | |
} | |
@Override | |
public void onDestroy() { | |
mServiceLooper.quit(); | |
} | |
@Override | |
public IBinder onBind(Intent intent) { | |
return null; | |
} | |
protected abstract void onHandleIntent(Intent intent); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment