可乐是好心情 發表於 2020-5-7 20:41:00

Android开发:getContentResolver的使用

<p>getContentResolver的使用 分两种情况:</p>
<p>一、在有Activity和Service的情况下</p>
<p>&nbsp;&nbsp;getContext().getContentResolver().insert(...);</p>
<p>1.getContext()是获得一个上下文对象(Context),一般在四大组件中都会获取上下文对象。</p>
<p>&nbsp;2.在Activity和Service中,就没必要获取Context了,因为他本身就是,所以可以直接调用getContentResolver()。</p>
<p>3.在ContentProvider中,就需要先调用getContext()获取到Context,然后调用getContentResolver() 获得ContentResolver对 象,也就是,getContext().getContentResolver().</p>
<p>另外:</p>
<p>(1)getContext().getContentResolver()返回的是ContentResolver 对象,ContentResolver负责获取ContentProvider提供的数据。</p>
<p>(2)&nbsp;MainActivity.this.getContentResolver()+数据库操作 等同于 getContext().getContentResolver()+数据操作。</p>
<p>&nbsp;</p>
<p>二、在没有Activity的情况下</p>
<p>例如:<br>public class companyInfo{ &nbsp;<br>public void AAA() throws Exception { &nbsp;<br>Uri scanUri = getContentResolver().insert(MediaStore.getMediaScannerUri(), values);&nbsp;<br>getContentResolver().delete(scanUri, null, null); &nbsp;<br>}&nbsp;<br>}&nbsp;<br>报错提示getContentResolver()不存在,需要通过activity或者service来实现。</p>
<p>这个类的AAA()方法肯定是有activity或者service调用的,所以需要写一个带有Context参数的构造方法就可以实现:<br>public class companyInfo{ &nbsp;<br>private Context context; &nbsp;<br>public companyInfo(Context context){ &nbsp;<br>this.context = context; &nbsp;<br>} &nbsp;</p>
<p>public void AAA() throws Exception { &nbsp;<br>Uri scanUri = getContentResolver().insert(MediaStore.getMediaScannerUri(), values);&nbsp;<br>context.getContentResolver().delete(scanUri, null, null); &nbsp;<br>}<br>} &nbsp;<br>————————————————<br>版权声明:本文为CSDN博主「AFull-GF」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。<br>原文链接:https://blog.csdn.net/daniel80110_1020/article/details/55260510</p>

</div>
<div id="MySignature" role="contentinfo">
    Always Believe Something Beauitful Will Be Happen<br><br>
来源:https://www.cnblogs.com/Oude/p/12845471.html
頁: [1]
查看完整版本: Android开发:getContentResolver的使用