3.3 ContactSaveService
ContactSaveService类继承自IntentService,实现了onHandleIntent方法。当然,另开一个子线程执行异步任务,主要对联系人(包括手机联系人和SIM卡联系人)进行添加,删除,修改,合并等操作。
AndroidManifest.xml有关ContactSaveService配置如下,
<service
android:name=".ContactSaveService"
android:exported="false" />
没有任何intent-filter的信息,因此,只能使用包名和类型进行启动了,当然,只能在Contacts进程中启动。
1,构造启动ContactSaveService的intent,
启动方式:启动ContactSaveService的initent 都是通过ContactSaveService的static方法设置的。例如,保存联系人的createSaveContactIntent,删除联系人的createDeleteContactIntent方法,还有原生的合并联系人createJoinContactsIntent方法等,这些方法构造intent方法格式如下,
Intent serviceIntent = new Intent(context, ContactSaveService.class);
serviceIntent.setAction(ContactSaveService.•••);
serviceIntent.putExtra(ContactSaveService. •••);
•••
2, onHandleIntent方法
ContactSaveService的onHandleIntent方法根据static方法设置的Action分别进行处理,使用了大量的if语句进行判断,部分代码如下,
String action = intent.getAction();
if (ACTION_NEW_RAW_CONTACT.equals(action)) {
createRawContact(intent);
} else if (ACTION_SAVE_CONTACT.equals(action)) {
saveContact(intent);
} else if (ACTION_CREATE_GROUP.equals(action)) {
createGroup(intent);
•••
3,回调
在ContactSaveService的相关方法操作完成之后,调用stopself结束service之前,有时候会调用deliverCallback方法切换到UI线程中,然后回调onServiceCompleted方法更新activity界面。
deliverCallback方法如下,
mMainHandler.post(new Runnable() {
@Override
public void run() {
deliverCallbackOnUiThread(callbackIntent);
}
});
mMainHandler就是UI线程的Handler,在ContactSaveService的构造方法中,
mMainHandler = new Handler(Looper.getMainLooper());
通过UI线程的Handler将代码执行流程从子线程切换到UI线程中。
deliverCallbackOnUiThread方法如下,
for (Listener listener : sListeners) {
if (callbackIntent.getComponent().equals( ((Activity) listener).getIntent().getComponent())) {
listener.onServiceCompleted(callbackIntent);
return;
}
}
sListeners是一个监听器的集合,
private static final CopyOnWriteArrayList<Listener> sListeners =
new CopyOnWriteArrayList<Listener>();
注:CopyOnWriteArrayList这是一个ArrayList的线程安全的变体.
Listener 是ContactSaveService的内部接口,只有一个onServiceCompleted方法,
public interface Listener {
public void onServiceCompleted(Intent callbackIntent);
}
当然,通过调用registerListener方法进行注册,调用unregisterListener方法取消注册。
因此,如果需要回调,需要满足2个条件:
1,实现ContactSaveService的Listener接口;
2,调用ContactSaveService的static方法registerListener进行注册。
刚好,整个android系统中, ContactsActivity类实现了ContactSaveService的Listener接口,
public abstract class ContactsActivity extends TransactionSafeActivity
implements ContactSaveService.Listener
并且,在onCreate方法中进行了注册,
ContactSaveService.registerListener(this);
ContactsActivity的onServiceCompleted方法实现如下,
onNewIntent(callbackIntent);
回调activity的onNewIntent方法,重新刷新activity的界面以及相关逻辑。