@Override public void onCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock.
@Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; }
/** * Old version of {@link #stopSelfResult} that doesn't return a result. * * @see #stopSelfResult */ public final void stopSelf(int startId) { if (mActivityManager == null) { return; } try { mActivityManager.stopServiceToken( new ComponentName(this, mClassName), mToken, startId); } catch (RemoteException ex) { } }
在我们自己的 IntentService 里面,写处理的逻辑,由于是在子线程中,所以可以处理耗时的逻辑,不必担心 ANR,普通 Service 由于在主线程运行,所以不能直接处理耗时逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_FOO.equals(action)) { final String param1 = intent.getStringExtra(EXTRA_PARAM1); final String param2 = intenonHt.getStringExtra(EXTRA_PARAM2); handleActionFoo(param1, param2); } else if (ACTION_BAZ.equals(action)) { final String param1 = intent.getStringExtra(EXTRA_PARAM1); final String param2 = intent.getStringExtra(EXTRA_PARAM2); handleActionBaz(param1, param2); } } }
小结
非常简单的 IntentService,使用的时候注意与普通 Service 的区别即可,里面使用了 HandlerThread 获取 Looper 对象,处理完会自动关闭,即调用 onDestroy,再次启动又重新走 Service 的生命周期,一个问题,如果多次 startService,那么 onHandleIntent 是怎么样的呢?答案是一次执行,因为 Looper 事件处理是阻塞的