首页 > 系统 > Android > 正文

Android开发:getContentResolver的使用

2019-11-08 18:40:16
字体:
来源:转载
供稿:网友

getContentResolver的使用 分两种情况:

一、在有Activity和Service的情况下

  getContext().getContentResolver().insert(...);

1.getContext()是获得一个上下文对象(Context),一般在四大组件中都会获取上下文对象。

 2.在Activity和Service中,就没必要获取Context了,因为他本身就是,所以可以直接调用getContentResolver()。

3.在ContentPRovider中,就需要先调用getContext()获取到Context,然后调用getContentResolver() 获得ContentResolver对 象,也就是,getContext().getContentResolver().

另外:

(1)getContext().getContentResolver()返回的是ContentResolver 对象,ContentResolver负责获取ContentProvider提供的数据。

(2) MainActivity.this.getContentResolver()+数据库操作 等同于 getContext().getContentResolver()+数据操作。

二、在没有Activity的情况下

例如:public class companyInfo{  public void AAA() throws Exception {  Uri scanUri = getContentResolver().insert(MediaStore.getMediaScannerUri(), values); getContentResolver().delete(scanUri, null, null);  } } 报错提示getContentResolver()不存在,需要通过activity或者service来实现。这个类的AAA()方法肯定是有activity或者service调用的,所以需要写一个带有Context参数的构造方法就可以实现:public class companyInfo{  private Context context;  public companyInfo(Context context){  this.context = context;  }  

public void AAA() throws Exception {  Uri scanUri = getContentResolver().insert(MediaStore.getMediaScannerUri(), values); context.getContentResolver().delete(scanUri, null, null);  }}  


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表