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);
}
}
————————————————
版權聲明:本文為CSDN博主「AFull-GF」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/daniel80110_1020/article/details/55260510