您的位置:首页 > 移动开发 > Android开发

Android开发:getContentResolver的使用

2017-02-16 17:14 393 查看
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);  
}

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: