| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package com.android.internal.util; |
| 18 |
|
| 19 |
import android.app.Service; |
| 20 |
import android.content.Intent; |
| 21 |
import android.os.Handler; |
| 22 |
import android.os.IBinder; |
| 23 |
import android.os.Message; |
| 24 |
import android.os.Messenger; |
| 25 |
import android.util.Log; |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
abstract public class AsyncService extends Service { |
| 36 |
private static final String TAG = "AsyncService"; |
| 37 |
|
| 38 |
protected static final boolean DBG = true; |
| 39 |
|
| 40 |
|
| 41 |
public static final int CMD_ASYNC_SERVICE_ON_START_INTENT = IBinder.LAST_CALL_TRANSACTION; |
| 42 |
|
| 43 |
|
| 44 |
public static final int CMD_ASYNC_SERVICE_DESTROY = IBinder.LAST_CALL_TRANSACTION + 1; |
| 45 |
|
| 46 |
|
| 47 |
protected Messenger mMessenger; |
| 48 |
|
| 49 |
|
| 50 |
Handler mHandler; |
| 51 |
|
| 52 |
public static final class AsyncServiceInfo { |
| 53 |
|
| 54 |
public Handler mHandler; |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
public int mRestartFlags; |
| 61 |
} |
| 62 |
|
| 63 |
AsyncServiceInfo mAsyncServiceInfo; |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
abstract public AsyncServiceInfo createHandler(); |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
public Handler getHandler() { |
| 76 |
return mHandler; |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
@Override |
| 83 |
public void onCreate() { |
| 84 |
super.onCreate(); |
| 85 |
mAsyncServiceInfo = createHandler(); |
| 86 |
mHandler = mAsyncServiceInfo.mHandler; |
| 87 |
mMessenger = new Messenger(mHandler); |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
@Override |
| 94 |
public int onStartCommand(Intent intent, int flags, int startId) { |
| 95 |
if (DBG) Log.d(TAG, "onStartCommand"); |
| 96 |
|
| 97 |
Message msg = mHandler.obtainMessage(); |
| 98 |
msg.what = CMD_ASYNC_SERVICE_ON_START_INTENT; |
| 99 |
msg.arg1 = flags; |
| 100 |
msg.arg2 = startId; |
| 101 |
msg.obj = intent; |
| 102 |
mHandler.sendMessage(msg); |
| 103 |
|
| 104 |
return mAsyncServiceInfo.mRestartFlags; |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
@Override |
| 113 |
public void onDestroy() { |
| 114 |
if (DBG) Log.d(TAG, "onDestroy"); |
| 115 |
|
| 116 |
Message msg = mHandler.obtainMessage(); |
| 117 |
msg.what = CMD_ASYNC_SERVICE_DESTROY; |
| 118 |
mHandler.sendMessage(msg); |
| 119 |
} |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
@Override |
| 125 |
public IBinder onBind(Intent intent) { |
| 126 |
return mMessenger.getBinder(); |
| 127 |
} |
| 128 |
} |