ContentProvider 系统URI

ContentProvider 系统URI

  • 案例一:获取手机联系人,展示并储存
  • 案例二:获取手机短信
  • 案例三:自动填写注册手机验证码
  • 案例四:获取手机所有的图片
  • 案例五:获取手机所有的视频
  • 案例六:手机联系人的增删改(拓展)

案例一:获取手机联系人,展示并储存

public class MainActivity extends AppCompatActivity {
    private Button buttonId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonId = findViewById(R.id.button_id);

        buttonId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            //根据版本动态获取授权(6.0以上)
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                   requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_CONTACTS},100);
                }else{
                    resolverMethod();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 & grantResults[0] == PackageManager.PERMISSION_GRANTED){
            resolverMethod();
        }
    }

    //因为重复使用,所有封装
    private void resolverMethod() {
        ContentResolver contentResolver = getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] strings = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
        Cursor cursor = contentResolver.query(uri, strings, null, null, null);
        while (cursor.moveToNext()){
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
            //有了对象,其他都好说了.
            Phone phone = new Phone(name, number);
        }
    }
}

案例二:获取手机短信

 private void smsMethod() {
        ContentResolver resolver = getContentResolver();
        Uri uri= Telephony.Sms.CONTENT_URI;
        String[] strs={Telephony.Sms.BODY,Telephony.Sms.ADDRESS};
        Cursor cursor=resolver.query(uri,strs,null,null,null);
        //第一种ListView 中  第二种 :存到数据库
        ArrayList<Msm> list=new ArrayList<>();
        while(cursor.moveToNext()){
            String address=cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            String body=cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
            Toast.makeText(this, body, Toast.LENGTH_SHORT).show();
            list.add(new Msm(address,body));
            //执行insert语句
        }
    }

案例三:自动填写注册手机验证码

观察者代码

public class SmsObserver  extends ContentObserver {
    private static final String TAG = "SmsObserver";
    private ContentResolver contentResolver;
    private Handler handler;
    public SmsObserver(Handler handler ,Context context) {
        super(handler);
        this.handler = handler;
        contentResolver = context.getContentResolver();
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        String[] strs={Telephony.Sms.BODY,Telephony.Sms.ADDRESS};
        Cursor cursor = contentResolver.query(Telephony.Sms.CONTENT_URI, strs, null, null, null);
        if (cursor != null){
            cursor.moveToFirst();
            String string = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
            Log.i(TAG, "onChange: 0000"+string);
            Message obtain = Message.obtain();
            obtain.obj = string;
            handler.sendMessage(obtain);
        }else{
            Log.i(TAG, "onChange: kong");
        }
    }
}

MainActicity

public class SmsActivity extends AppCompatActivity {
    private EditText smsId;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String s = (String)msg.obj;
            Toast.makeText(SmsActivity.this, s, Toast.LENGTH_SHORT).show();
            smsId.setText(s);
        }
    };
    private SmsObserver smsObserver;
    private ContentResolver contentResolver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        smsId = findViewById(R.id.sms_id);

        smsObserver = new SmsObserver(handler,this);
        contentResolver = getContentResolver();
//注册观察者
        contentResolver.registerContentObserver(Telephony.Sms.CONTENT_URI,true,smsObserver);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销观察者
        contentResolver.unregisterContentObserver(smsObserver);
    }
}

案例四:获取手机所有的图片

1,添加权限.


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

2,添加一个监听事件

  musicId.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},103);
            }else{
                musicMethod();
            }
        }
    });

3,添加java代码

private void musicMethod() {
    //TODO 1:获得ContentResolver
    ContentResolver contentResolver = getContentResolver();
    //参数一 URI
    //TODO 2:获得音乐的URI
    Uri uri1 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//音乐的URI
    Cursor cursor = contentResolver.query(uri1, null, null, null, null);
    while (cursor.moveToNext()){
        //字段
        String title=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
        //地址
        String data=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
        //歌手
        String artist=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
        //时长
        long duration=cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
        long size=cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
        Log.i("###", "音乐: "+title+":"+data+":"+artist+":"+duration+":"+size);
    }
}

4,回调函数中,添加逻辑

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 100 & grantResults[0] == PackageManager.PERMISSION_GRANTED){
        resolverMethod();
    }else if (requestCode == 101 & grantResults[0] == PackageManager.PERMISSION_GRANTED){
        smsMethod();
    }else if (requestCode == 102 & grantResults[0] == PackageManager.PERMISSION_GRANTED){
        picMethod();
    }else if (requestCode == 103 & grantResults[0] == PackageManager.PERMISSION_GRANTED){
        musicMethod();
    }
}

案例五:获取手机所有的视频

1,添加权限.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

2,添加一个监听事件

 videoId.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
               requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},104);
           }else{
               videoMethod();
           }
       }
   });

3,添加java代码

 		private void videoMethod() {
   		//TODO 1:获得ContentResolver
       ContentResolver contentResolver = getContentResolver();
       //参数一 URI
       //TODO 2:获得视频的URI
       Uri uri1 = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;//视频的URI
//        Uri uri1 = Uri.parse("content://media/external/video/media");
       Cursor cursor = contentResolver.query(uri1, null, null, null, null);
       while (cursor.moveToNext()){
           //字段
           String title=cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
           String data=cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
           String artist=cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.ARTIST));
           long duration=cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DURATION));
           long size=cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.SIZE));
           Log.i("###", "视频: "+title+":"+data+":"+artist+":"+duration+":"+size);
       }
   }

4,回调函数中,添加逻辑

else if (requestCode == 104 & grantResults[0] == PackageManager.PERMISSION_GRANTED){
videoMethod();
}

案例六:手机联系人的增删改(拓展)

 private void addPerson() {
        ContentResolver contentResolver = getContentResolver();
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        //ContactsContract.RawContacts.CONTENT_URI
        ContentValues values = new ContentValues();
        //插入一条空数据,返回当前空数据的id.
        long contactid = ContentUris.parseId(contentResolver.insert(uri, values));
        uri = Uri.parse("content://com.android.contacts/data");
        //添加姓名
        values.put("raw_contact_id", contactid);
        values.put("mimetype", "vnd.android.cursor.item/name");
        values.put("data1", "xiaoming11");
        contentResolver.insert(uri, values);
        values.clear();

        
        //添加电话
        values.put(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, contactid);
        //ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
        values.put(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/phone_v2");
        //ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE;
        values.put(ContactsContract.Data.DATA1, "12312312311");
        contentResolver.insert(uri, values);
        values.clear();
        
        //添加Email
        values.put("raw_contact_id", contactid);
        //ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
        values.put(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/email_v2");
        values.put("data1", "[email protected]");
        contentResolver.insert(uri, values);
    }
   

你可能感兴趣的:(Java语言)