Android开发:getContentResolver的使用

来源:互联网 发布:linux c 串口中断 编辑:程序博客网 时间:2024/06/18 03:32

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);  
}
}  

0 0
原创粉丝点击