Browse Source

优化通讯录更新操作,增加强制更新通讯录功能

weizhengliang 3 years ago
parent
commit
ddf2ac7a71

+ 3 - 1
app/src/main/AndroidManifest.xml

@@ -48,7 +48,9 @@
 <!--            >-->
 <!--        <activity android:name="com.wdkl.ncs.android.component.home.activity.WatchRegisterActivity">-->
 <!--        <activity android:name="com.starrtc.demo.demo.SplashActivity">-->
-        <activity android:name="com.wdkl.ncs.android.component.home.activity.WatchHome2Activity" android:screenOrientation="portrait">
+        <activity android:name="com.wdkl.ncs.android.component.home.activity.WatchHome2Activity"
+            android:launchMode="singleInstance"
+            android:screenOrientation="portrait">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
 

+ 1 - 1
app/src/main/code/com/wdkl/app/ncs/application/Application.kt

@@ -71,7 +71,7 @@ class Application : BaseApplication() {
      */
     private fun initFrame() {
         //禁止滑掉退出
-        BaseConfig.getInstance().addActivity("WatchHome2Activity", "NewEventListActivity", "AppUpdateActivity")
+        BaseConfig.getInstance().addActivity("WatchHome2Activity", "NewEventListActivity", "AppUpdateActivity", "ContactUpdateActivity")
 
         NetEngineConfig.init(baseContext)
                 .openLogger()

+ 1 - 0
home/src/main/AndroidManifest.xml

@@ -38,6 +38,7 @@
             android:launchMode="singleTask"/>
         <activity android:name=".activity.VoiceMsgActivity" android:screenOrientation="portrait"/>
         <activity android:name=".activity.ChannelImActivity" android:screenOrientation="portrait"/>
+        <activity android:name=".activity.ContactUpdateActivity" android:screenOrientation="portrait"/>
 
         <activity
             android:name=".ui.CallSingleActivity"

+ 167 - 0
home/src/main/code/com/wdkl/ncs/android/component/home/activity/ContactUpdateActivity.kt

@@ -0,0 +1,167 @@
+package com.wdkl.ncs.android.component.home.activity
+
+import android.graphics.Color
+import android.view.View
+import com.alibaba.android.vlayout.DelegateAdapter
+import com.alibaba.android.vlayout.VirtualLayoutManager
+import com.enation.javashop.net.engine.model.NetState
+import com.wdkl.ncs.android.component.home.R
+import com.wdkl.ncs.android.component.home.adapter.ContactUpdateAdapter
+import com.wdkl.ncs.android.component.home.databinding.ActivityContactUpdateBinding
+import com.wdkl.ncs.android.component.home.launch.HomeLaunch
+import com.wdkl.ncs.android.lib.utils.showMessage
+import com.wdkl.ncs.android.lib.vo.MessageEvent
+import com.wdkl.ncs.android.middleware.common.Constants
+import com.wdkl.ncs.android.middleware.logic.contract.home.WatchHomeActivityContract
+import com.wdkl.ncs.android.middleware.logic.presenter.home.WatchHomeActivityPresenter
+import com.wdkl.ncs.android.middleware.model.dos.AppVersionDO
+import com.wdkl.ncs.android.middleware.model.dos.ChannelDO
+import com.wdkl.ncs.android.middleware.model.dos.PartSettingDO
+import com.wdkl.ncs.android.middleware.model.dto.TcpSeverDTO
+import com.wdkl.ncs.android.middleware.model.vo.DeviceVO
+import com.wdkl.ncs.android.middleware.model.vo.WatchContactVO
+import com.wdkl.ncs.android.middleware.utils.ContactHelper
+import kotlinx.android.synthetic.main.activity_contact_update.*
+import org.greenrobot.eventbus.Subscribe
+import org.greenrobot.eventbus.ThreadMode
+
+class ContactUpdateActivity: BaseActivity<WatchHomeActivityPresenter, ActivityContactUpdateBinding>(), WatchHomeActivityContract.View {
+    private lateinit var adapter: ContactUpdateAdapter
+    private lateinit var virtualLayoutManager: VirtualLayoutManager
+    private lateinit var delegateAdapter: DelegateAdapter
+
+    private var clickTime: Long = 0
+
+    override fun getLayId(): Int {
+        return R.layout.activity_contact_update
+    }
+
+    override fun bindDagger() {
+        HomeLaunch.component.inject(this)
+    }
+
+    override fun init() {
+        /**初始化LayoutMannager*/
+        virtualLayoutManager = VirtualLayoutManager(this.activity)
+
+        adapter = ContactUpdateAdapter(ArrayList(), activity)
+        delegateAdapter = DelegateAdapter(virtualLayoutManager)
+        delegateAdapter.addAdapter(adapter)
+
+        update_contact_list.adapter = delegateAdapter
+        update_contact_list.layoutManager = virtualLayoutManager
+
+        if (Constants.deviceId > 0) {
+            tv_contact_title.text = "开始获取联系人..."
+            presenter.getWatchContacts(Constants.deviceId)
+            showMessage("开始更新,可能花费几分钟时间")
+        } else {
+            tv_contact_title.text = "获取联系人失败,设备可能未注册"
+            tv_contact_title.setTextColor(Color.RED)
+            showMessage("设备可能未注册...")
+        }
+    }
+
+    override fun bindEvent() {
+        //
+    }
+
+    override fun destory() {
+        //
+    }
+
+    override fun enableHeadsetVoiceMsg(): Boolean {
+        return false
+    }
+
+    override fun handleAppVersion(appInfo: AppVersionDO) {
+    }
+
+    override fun setDeviceDo(data: DeviceVO) {
+    }
+
+    override fun setTcpServerHost(tcpSeverDTO: TcpSeverDTO) {
+    }
+
+    override fun setDeviceSettingData(partSettingDO: PartSettingDO) {
+    }
+
+    override fun setDeviceVoiceChannel(channelList: ArrayList<ChannelDO>) {
+    }
+
+    override fun setPhoneNumberWhiteList(phoneList: ArrayList<String>) {
+    }
+
+    override fun setContact(contactsVOs: List<WatchContactVO>) {
+        tv_contact_title.text = "获取到" + contactsVOs.size + "个联系人"
+        tv_contact_title.setTextColor(Color.GREEN)
+        if (contactsVOs.size > 0) {
+            var list = ArrayList<String>()
+            for (contact in contactsVOs) {
+                val str = "联系人名称: " + contact.name + ", 号码: " + contact.phoneNumber
+                list.add(str)
+            }
+            list.add("\n开始更新通讯录...")
+            adapter.data.addAll(list)
+            adapter.notifyDataSetChanged()
+
+
+            Thread {
+                ContactHelper.updateContacts(applicationContext, contactsVOs, object : ContactHelper.Callback {
+                    override fun onBack(str: String) {
+                        runOnUiThread {
+                            adapter.data.add(str)
+                            if (adapter.data.size > 10) {
+                                update_contact_list.smoothScrollToPosition(adapter.itemCount - 1)
+                            }
+                            adapter.notifyDataSetChanged()
+                        }
+                    }
+
+                    override fun onUpdate(progress: Int) {
+                        runOnUiThread {
+                            progress_contact_update.setCurProgress(progress)
+                            if (progress == 100) {
+                                tv_contact_update_progress.setText("更新完成: " + progress + "%")
+                            } else {
+                                tv_contact_update_progress.setText("正在更新: " + progress + "%")
+                            }
+                        }
+                    }
+                })
+            }.start()
+        }
+    }
+
+    override fun onBackPressed() {
+        if (System.currentTimeMillis() - clickTime > 2000) {
+            showMessage("再按一次退出")
+        } else {
+            ContactHelper.exitUpdateContact()
+            super.onBackPressed()
+        }
+        clickTime = System.currentTimeMillis()
+    }
+
+    override fun onError(message: String, type: Int) {
+        showMessage(message)
+    }
+
+    override fun complete(message: String, type: Int) {
+
+    }
+
+    override fun start() {
+
+    }
+
+    override fun networkMonitor(state: NetState) {
+
+    }
+
+
+    @Subscribe(threadMode = ThreadMode.MAIN)
+    fun onMoonEvent(messageEvent: MessageEvent) {
+        //
+    }
+}

+ 22 - 9
home/src/main/code/com/wdkl/ncs/android/component/home/activity/WatchHome2Activity.kt

@@ -75,6 +75,7 @@ class WatchHome2Activity : BaseActivity<WatchHomeActivityPresenter, WatchActivit
     lateinit var countDownTimer: CountDownTimer
 
     private var clickTime: Long = 0
+    private var contactUpdating = false
 
     private lateinit var netWorkChangeReceiver: NetWorkChangeReceiver
 
@@ -427,15 +428,27 @@ class WatchHome2Activity : BaseActivity<WatchHomeActivityPresenter, WatchActivit
     //写手机通讯录
     override fun setContact(contactVOs: List<WatchContactVO>) {
         if (contactVOs != null && contactVOs.size > 0) {
-            Thread {
-                Log.e(TAG, "111 start update contacts...")
-                for (contactVO in contactVOs) {
-                    if (!Strings.isNullOrEmpty(contactVO.name) && !Strings.isNullOrEmpty(contactVO.phoneNumber)) {
-                        ContactHelper.setContact(BaseApplication.appContext, contactVO.name, contactVO.phoneNumber)
+            if (!contactUpdating) {
+                contactUpdating = true
+                Thread {
+                    try {
+                        Log.e(TAG, "111 start update contacts...")
+                        for (contactVO in contactVOs) {
+                            if (!Strings.isNullOrEmpty(contactVO.name) && !Strings.isNullOrEmpty(contactVO.phoneNumber)) {
+                                ContactHelper.setContact(BaseApplication.appContext, contactVO.name, contactVO.phoneNumber)
+                            }
+                        }
+                        Log.e(TAG, "111 update contacts end...")
+                        contactUpdating = false
+                    } catch (ex: Exception) {
+                        contactUpdating = false
+                        ex.printStackTrace()
                     }
-                }
-                Log.e(TAG, "111 update contacts end...")
-            }.start()
+                }.start()
+
+            } else {
+                showMessage("通讯录正在更新...")
+            }
         }
     }
 
@@ -550,7 +563,7 @@ class WatchHome2Activity : BaseActivity<WatchHomeActivityPresenter, WatchActivit
                 presenter.getTcpServerHost()
 
                 try {
-                    Thread.sleep(5000)
+                    Thread.sleep(10000)
                 } catch (e: Exception) {
                 }
                 count--

+ 13 - 0
home/src/main/code/com/wdkl/ncs/android/component/home/activity/WatchUserSettingActivity.java

@@ -26,6 +26,9 @@ import com.wdkl.ncs.android.lib.utils.ExtendMethodsKt;
 import com.wdkl.ncs.android.middleware.tcp.NettyClient;
 import com.wdkl.ncs.android.middleware.tcp.channel.DeviceUtil;
 import com.wdkl.ncs.android.middleware.tcp.dto.TcpModel;
+import com.wdkl.ncs.android.middleware.utils.ContactHelper;
+
+import java.util.ArrayList;
 
 public class WatchUserSettingActivity extends Activity {
     private static final String TAG = WatchUserSettingActivity.class.getSimpleName();
@@ -130,6 +133,16 @@ public class WatchUserSettingActivity extends Activity {
                 }
             }
         });
+
+
+        Button update = findViewById(R.id.btn_update_contact);
+        update.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                Intent intent = new Intent(getApplicationContext(), ContactUpdateActivity.class);
+                startActivity(intent);
+            }
+        });
     }
 
     @Override

+ 45 - 0
home/src/main/code/com/wdkl/ncs/android/component/home/adapter/ContactUpdateAdapter.kt

@@ -0,0 +1,45 @@
+package com.wdkl.ncs.android.component.home.adapter
+
+import android.content.Context
+import android.view.ViewGroup
+import com.alibaba.android.vlayout.LayoutHelper
+import com.alibaba.android.vlayout.layout.LinearLayoutHelper
+import com.wdkl.ncs.android.component.home.R
+import com.wdkl.ncs.android.component.home.databinding.UpdateContactItemBinding
+import com.wdkl.ncs.android.lib.adapter.BaseDelegateAdapter
+import com.wdkl.ncs.android.lib.utils.BaseRecyclerViewHolder
+
+class ContactUpdateAdapter(val data: ArrayList<String>, val context: Context):
+    BaseDelegateAdapter<BaseRecyclerViewHolder<UpdateContactItemBinding>, String>() {
+
+    override fun dataProvider(): Any {
+        return data
+    }
+
+    override fun itemFilter(position: Int): Boolean {
+        return true
+    }
+
+    override fun onCreateViewHolder(
+        p0: ViewGroup?,
+        p1: Int
+    ): BaseRecyclerViewHolder<UpdateContactItemBinding> {
+        return BaseRecyclerViewHolder.build(p0, R.layout.update_contact_item)
+    }
+
+    override fun onBindViewHolder(p0: BaseRecyclerViewHolder<UpdateContactItemBinding>?, p1: Int) {
+        p0?.bind {
+            binding ->
+            binding.tvContactItem.text = data[p1]
+        }
+    }
+
+    override fun getItemCount(): Int {
+        return data.size
+    }
+
+    override fun onCreateLayoutHelper(): LayoutHelper {
+        return LinearLayoutHelper(0, data.size)
+    }
+
+}

+ 2 - 0
home/src/main/code/com/wdkl/ncs/android/component/home/di/HomeComponent.kt

@@ -33,4 +33,6 @@ interface HomeComponent {
     fun inject(activity: VoiceMsgActivity)
 
     fun inject(activity: ChannelImActivity)
+
+    fun inject(activity: ContactUpdateActivity)
 }

+ 44 - 0
home/src/main/res/layout/activity_contact_update.xml

@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>
+<layout xmlns:app="http://schemas.android.com/apk/res-auto">
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:padding="8dp"
+    android:orientation="vertical">
+
+    <TextView
+        android:id="@+id/tv_contact_title"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text=""
+        android:textSize="18sp"/>
+
+    <TextView
+        android:id="@+id/tv_contact_update_progress"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="6dp"
+        android:textSize="16sp"
+        android:text="0%"/>
+
+    <com.wdkl.ncs.android.lib.widget.ProgressView
+        android:id="@+id/progress_contact_update"
+        android:layout_width="match_parent"
+        android:layout_height="20dp"
+        android:layout_marginTop="6dp"
+        app:haveChangeColor="true"
+        app:isShowDesc="false"
+        app:max="100"
+        app:progress="0"
+        app:progressDesc="进度:"
+        app:progressRadius="10dp" />
+
+    <android.support.v7.widget.RecyclerView
+        android:id="@+id/update_contact_list"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:layout_marginTop="8dp"
+        android:scrollbars="vertical"/>
+
+</LinearLayout>
+</layout>

+ 12 - 0
home/src/main/res/layout/update_contact_item.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<layout>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content">
+    <TextView
+        android:id="@+id/tv_contact_item"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:textSize="16sp"/>
+</LinearLayout>
+</layout>

+ 11 - 0
home/src/main/res/layout/user_setting_layout.xml

@@ -245,6 +245,17 @@
                     android:text="系统设置"
                     android:textSize="14dp" />
 
+                <Button
+                    android:id="@+id/btn_update_contact"
+                    android:layout_marginTop="10dp"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="center_horizontal"
+                    android:layout_below="@id/btn_system_setting"
+                    android:background="@drawable/javashop_btn_balck_line_bg"
+                    android:text="更新通讯录"
+                    android:textSize="14dp" />
+
                 <TextView
                     android:id="@+id/tv_call_title"
                     android:layout_width="wrap_content"

+ 280 - 6
middleware/src/main/code/com/wdkl/ncs/android/middleware/utils/ContactHelper.java

@@ -9,15 +9,19 @@ import android.database.Cursor;
 import android.net.Uri;
 import android.provider.ContactsContract;
 import android.telephony.TelephonyManager;
+import android.text.TextUtils;
 import android.util.Log;
 
 import com.wdkl.ncs.android.lib.base.BaseApplication;
+import com.wdkl.ncs.android.middleware.model.vo.WatchContactVO;
 
 import java.util.ArrayList;
+import java.util.List;
 
 public class ContactHelper {
-
+    private static final String TAG = "ContactHelper";
     private static final Object lock = new Object();
+    private static boolean exitUpdate = false;
 
     /**
      * 插入手机号
@@ -26,7 +30,12 @@ public class ContactHelper {
      * @param name
      * @param phoneNumber
      */
-    public static void insertContact(Context context, String name, String phoneNumber) {
+    public static void insertContact(Context context, String name, String phoneNumber, Callback callback) {
+        Log.d(TAG, "add contact: " + name + ", phone: " + phoneNumber);
+        if (callback != null) {
+            String text = "添加联系人: " + name + ", " + phoneNumber;
+            callback.onBack(text);
+        }
 
         Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
         ContentResolver resolver = context.getContentResolver();
@@ -81,7 +90,7 @@ public class ContactHelper {
                     null, null, null); //从raw_contact表中返回display_name
             if (cursor != null && cursor.moveToFirst()) {
                 int contact_id = cursor.getInt(0);
-                Log.i("联系人ID", contact_id + "");
+                Log.i(TAG, contact_id + "");
                 cursor.close();
                 return contact_id;
             }
@@ -95,6 +104,135 @@ public class ContactHelper {
         return -1;
     }
 
+    public static Integer checkPhoneNumExist(Context context, String phoneNum) {
+        //uri=  content://com.android.contacts/data/phones/filter/#
+        Cursor cursor;
+        int id = -1;
+        try {
+            ContentResolver cr = context.getContentResolver();
+            cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
+            if (cursor != null) {
+                while (cursor.moveToNext()) {
+                    boolean findContact = false;
+                    // 取得联系人名字
+                    int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
+                    String name = cursor.getString(nameFieldColumnIndex);
+                    // 取得联系人ID
+                    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
+                    Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
+                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
+                    //Log.d(TAG, "isPhoneNumbExist2: name=" + name + ", contactId=" + contactId);
+
+                    // 取得电话号码(可能存在多个号码)
+                    if (phoneCursor != null) {
+                        while (phoneCursor.moveToNext()) {
+                            String strPhoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
+                            //Log.d(TAG, "get phoneNumber=" + strPhoneNumber + ", phoneNum=" + phoneNum);
+                            if (!TextUtils.isEmpty(strPhoneNumber)) {
+                                strPhoneNumber = strPhoneNumber.replaceAll(" ", "");
+                                //过滤+86
+                                strPhoneNumber = strPhoneNumber.replace("+86", "");
+                                phoneNum = phoneNum.replace("+86", "");
+                                if (phoneNum.equals(strPhoneNumber)) {
+                                    id = phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID));
+                                    Log.d(TAG, "find contact id=" + id + ", phoneNumber=" + strPhoneNumber);
+                                    findContact = true;
+                                    break;
+                                }
+                            }
+                        }
+                        phoneCursor.close();
+                    }
+
+                    if (findContact && id > 0) {
+                        Log.e(TAG, "delete contact: " + name + ", id: " + id);
+                        deleteContact(context, id); //删除原来号码通讯录
+                    }
+                }
+                cursor.close();
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return id;
+    }
+
+    public static void checkContact(Context context, String phone) {
+        Cursor cursor = null;
+        try {
+            Uri phoneUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(phone));
+            ContentResolver resolver = context.getContentResolver();
+            cursor = resolver.query(phoneUri, new String[]{ContactsContract.CommonDataKinds.Phone._ID,
+                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, null, null, null);
+
+            Log.d(TAG, "check contact cursor: " + cursor);
+            if (cursor != null) {
+                while (cursor.moveToNext()) {
+                    int id = cursor.getInt(0);
+                    String name = cursor.getString(1);
+                    int contactId = cursor.getInt(2);
+                    Log.d(TAG, "find contact: " + name + ", contactId: " + contactId);
+                    deleteContact(context, contactId);
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            if (cursor != null) {
+                cursor.close();
+            }
+        }
+    }
+
+
+    /**
+     * 获取手机联系人号码
+     */
+    private static void checkAndDeleteContact(Context context, String phone, Callback callback){
+        //得到ContentResolver对象
+        ContentResolver cr = context.getContentResolver();
+        //取得电话本中开始一项的光标
+        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
+        if (cursor != null) {
+            while (cursor.moveToNext()) {
+                // 取得联系人名字
+                int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
+                String name = cursor.getString(nameFieldColumnIndex);
+                // 取得联系人ID
+                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
+                Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
+                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
+                Log.d(TAG, "getPhoneNumber: nameFieldColumnIndex=" + nameFieldColumnIndex + ", name=" + name + ", contactId=" + contactId);
+
+                // 取得电话号码(可能存在多个号码)
+                if (phoneCursor != null) {
+                    boolean delete = false;
+                    while (phoneCursor.moveToNext()) {
+                        String strPhoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
+                        Log.d(TAG, "get phoneNumber=" + strPhoneNumber);
+                        if (strPhoneNumber.equals(phone)) {
+                            if (callback != null) {
+                                String text = "找到相同号码联系人: " + name + ", " + strPhoneNumber;
+                                callback.onBack(text);
+                            }
+                            delete = true;
+                            break;
+                        }
+                    }
+                    phoneCursor.close();
+
+                    //删除联系人
+                    if (delete) {
+                        cr.delete(ContactsContract.Contacts.CONTENT_URI, ContactsContract.Contacts._ID + " =?", new String[]{contactId + ""});
+                        cr.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts.CONTACT_ID + " =?", new String[]{contactId + ""});
+                    }
+                }
+            }
+            cursor.close();
+        }
+    }
+
 
     /**
      * 根据姓名查找Contact_id
@@ -162,7 +300,7 @@ public class ContactHelper {
         }
     }
 
-    public static void setContact(Context context, String name, String phoneNumber) {
+    /*public static void setContact(Context context, String name, String phoneNumber) {
         synchronized (lock) {
             Integer contact_id = queryRawContactIdByName(context, name);
             Integer contact_id2 = isPhoneNumbExist(context, phoneNumber);
@@ -175,9 +313,9 @@ public class ContactHelper {
                     }
 //                updateContact(context, contact_id, phoneNumber); //更新通讯录
                 }//通讯录姓名和号码没有变化,不用操作
-                insertContact(context, name, phoneNumber);
+                insertContact(context, name, phoneNumber, null);
             } else { //这个名字不存在通讯录中
-                insertContact(context, name, phoneNumber);
+                insertContact(context, name, phoneNumber, null);
                 if (contact_id2 != null && contact_id2 > 0) { //电话号码确在通讯录中
                     deleteContact(context, contact_id2); //删除原来号码通讯录
                 }
@@ -185,6 +323,136 @@ public class ContactHelper {
             }
 
         }
+    }*/
+
+    public static void setContact(Context context, String name, String phoneNumber) {
+        synchronized (lock) {
+            if (TextUtils.isEmpty(phoneNumber)) {
+                Log.i(TAG, "setContact null");
+                return;
+            }
+
+            checkPhoneNumExist(context, phoneNumber);
+            Integer contact_id = queryRawContactIdByName(context, name);
+            Log.i(TAG, "setContact: " + contact_id + "");
+
+            if (contact_id != null && contact_id > 0) {
+                deleteContact(context, name);
+                insertContact(context, name, phoneNumber, null);
+            } else { //这个名字不存在通讯录中
+                insertContact(context, name, phoneNumber, null);
+            }
+        }
+    }
+
+
+    //批量更新通讯录
+    public static void updateContacts(Context context, List<WatchContactVO> contactVOS, Callback callback) {
+        synchronized (lock) {
+            exitUpdate = false;
+            int index = 0;
+            int size = contactVOS.size();
+            //得到ContentResolver对象
+            ContentResolver cr = context.getContentResolver();
+            //取得电话本中开始一项的光标
+            Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
+
+            if (cursor != null) {
+                for (WatchContactVO contactVO : contactVOS) {
+                    if (exitUpdate) {
+                        break;
+                    }
+                    index++;
+
+                    //如果这个号码为空则不操作
+                    if (TextUtils.isEmpty(contactVO.getPhoneNumber())) {
+                        if (callback != null) {
+                            String text = contactVO.getName() + ": 号码为空,不更新";
+                            callback.onBack(text);
+
+                            float p = (float) index / (float) size;
+                            int progress = (int) (p * 100);
+                            callback.onUpdate(progress);
+                        }
+                        continue;
+                    }
+
+                    if (cursor.moveToFirst()) {
+                        do {
+                            // 取得联系人名字
+                            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
+                            String name = cursor.getString(nameFieldColumnIndex);
+                            // 取得联系人ID
+                            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
+                            Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
+                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
+                            //Log.d(TAG, "getPhoneNumber: nameFieldColumnIndex=" + nameFieldColumnIndex + ", name=" + name + ", contactId=" + contactId);
+
+                            // 取得电话号码(可能存在多个号码)
+                            if (phoneCursor != null) {
+                                boolean delete = false;
+                                while (phoneCursor.moveToNext()) {
+                                    String strPhoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
+                                    //Log.d(TAG, "get phoneNumber=" + strPhoneNumber);
+                                    if (!TextUtils.isEmpty(strPhoneNumber)) {
+                                        strPhoneNumber = strPhoneNumber.replaceAll(" ", "");
+                                        //过滤+86
+                                        strPhoneNumber = strPhoneNumber.replace("+86", "");
+                                        String phoneNum = contactVO.getPhoneNumber().replace("+86", "");
+                                        //Log.e(TAG, "phone num compare: num1=" + strPhoneNumber + ", num2=" + phoneNum);
+                                        if (strPhoneNumber.equals(phoneNum)) {
+                                            if (callback != null) {
+                                                String text = "找到相同号码联系人: " + name + ", " + strPhoneNumber;
+                                                callback.onBack(text);
+                                            }
+                                            delete = true;
+                                            break;
+                                        }
+                                    }
+                                }
+                                phoneCursor.close();
+
+                                //删除联系人
+                                if (delete) {
+                                    cr.delete(ContactsContract.Contacts.CONTENT_URI, ContactsContract.Contacts._ID + " =?", new String[]{contactId + ""});
+                                    cr.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts.CONTACT_ID + " =?", new String[]{contactId + ""});
+                                }
+                            }
+                        } while (cursor.moveToNext());
+                    }
+
+                    //新增联系人
+                    insertContact(context, contactVO.getName(), contactVO.getPhoneNumber(), callback);
+
+                    if (callback != null) {
+                        float p = (float) index / (float) size;
+                        int progress = (int) (p * 100);
+                        callback.onUpdate(progress);
+                    }
+                }
+
+                cursor.close();
+
+                if (callback != null) {
+                    String text = "更新完成!";
+                    callback.onBack(text);
+                }
+            }
+        }
+    }
+
+    public static void exitUpdateContact() {
+        exitUpdate = true;
+    }
+
+    public static void updateContact(Context context, String name, String phoneNumber, Callback callback) {
+        synchronized (lock) {
+            //1.删除所有号码相同的联系人
+            checkAndDeleteContact(context, phoneNumber, callback);
+
+            //2.新增联系人
+            insertContact(context, name, phoneNumber, callback);
+        }
     }
 
 
@@ -229,4 +497,10 @@ public class ContactHelper {
         @SuppressLint("MissingPermission") String te1  = tm.getLine1Number();//获取本机号码
         return te1;
     }
+
+
+    public interface Callback {
+        void onBack(String str);
+        void onUpdate(int progress);
+    }
 }