Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A first attempt at an implementation of a intent service with priorities, based on CommonsWare's answer and Android's <code>IntentService</code> <a href="http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/app/IntentService.java" rel="noreferrer">source code</a>. Will test extensively and edit accordingly.</p> <pre><code>public abstract class PriorityIntentService extends Service { private final class QueueItem implements Comparable&lt;QueueItem&gt; { Intent intent; int priority; int startId; @Override public int compareTo(QueueItem another) { if (this.priority &lt; another.priority) { return -1; } else if (this.priority &gt; another.priority) { return 1; } else { return (this.startId &lt; another.startId) ? -1 : 1; } } } private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { try { final QueueItem item = mQueue.take(); onHandleIntent(item.intent); if (mQueue.isEmpty()) { PriorityIntentService.this.stopSelf(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static final String EXTRA_PRIORITY = "priority"; private String mName; private PriorityBlockingQueue&lt;QueueItem&gt; mQueue; private boolean mRedelivery; private volatile ServiceHandler mServiceHandler; private volatile Looper mServiceLooper; public PriorityIntentService(String name) { super(); mName = name; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("PriorityIntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); mQueue = new PriorityBlockingQueue&lt;QueueItem&gt;(); } @Override public void onDestroy() { mServiceLooper.quit(); } protected abstract void onHandleIntent(Intent intent); @Override public void onStart(Intent intent, int startId) { final QueueItem item = new QueueItem(); item.intent = intent; item.startId = startId; final int priority = intent.getIntExtra(EXTRA_PRIORITY, 0); item.priority = priority; mQueue.add(item); mServiceHandler.sendEmptyMessage(0); } @Override public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; } public void setIntentRedelivery(boolean enabled) { mRedelivery = enabled; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload