1 import android.Manifest;
2 android.content.ContentResolver;
3 android.content.pm.PackageManager;
4 android.database.ContentObserver;
5 android.net.Uri;
6 android.os.Handler;
7 android.provider.ContactsContract;
8 android.support.v4.app.ActivityCompat;
9 android.support.v7.app.AppCompatActivity;
10 android.os.Bundle;
11 android.util.Log;
12 android.widget.Toast;
13
14 public class MainActivity extends AppCompatActivity {
15
16 ContentResolver resolver = null;
17 Observer observer = 18 @Override
19 protected void onCreate(Bundle savedInstanceState) {
20 super.onCreate(savedInstanceState);
21 setContentView(R.layout.activity_main);
22
23 //动态权限申请(同时也要在AndroidManifest文件问进行申请权限)
24 if (ActivityCompat.checkSelfPermission(this,25 Manifest.permission.READ_CONTACTS)!=
26 PackageManager.PERMISSION_GRANTED);
27 ActivityCompat.requestPermissions(
28 MainActivity.29 new String[]{ Manifest.permission.READ_CONTACTS
30 },0);
31
32 实例化Observer
33 observer = new Observer( Handler());
34 获取resolver
35 resolver = getContentResolver();
36 Uri uri = ContactsContract.Contacts.CONTENT_URI;
37 注册Observer
38 resolver.registerContentObserver(uri,true39
40 }
41
42 class Observer ContentObserver{
43
44 public Observer(Handler handler) {
45 (handler);
46 }
47
48 @Override
49 void onChange(boolean selfChange) {
50 .onChange(selfChange);
51 Toast.makeText(MainActivity.52 "联系人列表发生变化"53 onchange 方法中添加Toast便于观察
54 55 56
57 58 onDetachedFromWindow() {
59 .onDetachedFromWindow();
60 在Activity中注销observer
61 resolver.unregisterContentObserver(observer);
62 63 }