Android之调用ContentProvider中的方法

本文介绍如何在Android中通过ContentProvider实现跨应用数据共享。APP A通过重写Provider的call方法提供服务,APP B通过调用call方法与APP A交互。调用时,Uri的authority用于匹配正确的Provider。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

APP A通过Provider的方式向其他应用如APP B提供数据,如果APP B需要调用APP A中的方法,则Provider必须重写call方法,APP B通过调用call方法会执行APP A中Provider的call方法,B中调用call方法的返回值就是Provider中call方法的返回值。

APP A的Provider必须重写call方法:

public class ContentProviderDemo extends ContentProvider {

    @Override
    public Bundle call(String method, String arg, Bundle extras) {
        System.out.println("method:" + method);
        Bundle bundle = new Bundle();
        // put一个boolean值,如果执行方法成功返回true、失败返回fasle
        bundle.putBoolean(method, true);
        return bundle;
    }
	
	...

}

 

APP B调用call方法:

String method = "isSuccess";
String uri = "content://jobdispatcher/abc.txt";
Bundle bundle = context.getContentResolver().call(
        Uri.parse(uri), method, null, null);
// 通过返回值取出boolean变量知道是否调用成功
System.out.println("调用结果:" + bundle.getBoolean(method));


可以看到调用者的call方法比Provider中call方法多了一个Uri参数,那么调用者调用call方法时,是怎么知道调用哪个Provider的call方法的呢?

调用者执行call方法时,是根据Uri匹配执行哪个Provider的call方法的。匹配规则:Uri的authority。

如Provider的注册是:

<provider
    android:name="com.example.sspreceiver.ContentProviderDemo"
    android:authorities="jobdispatcher" >
</provider>


调用可以用:

context.getContentResolver().call(Uri.parse("content://jobdispatcher"), "hehe", null, null);


其中只要uri是以"content://jobdispatcher"开头的就都能够匹配到authority是"jobdispatcher"的这个Provider。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值