如何找出在Android的内容提供商的呼叫活动?出在、提供商、内容、Android

2023-09-08 08:43:59 作者:那时天空的云

据我了解,在Android中,对于内容提供商实现不和可能不应该与哪个应用程序请求数据有关。只要调用应用程序访问数据的实现应该只返回根据所请求的URI数据所需的权限。不过,我想不同的东西在我的内容提供商,需要找出哪些应用程序响应查询数据之前调用供应商。有没有我的内容提供商的方式来发现这一点?任何帮助将大大AP preciated。

As I understand, in Android, the implementation for a content provider does not and possibly should not be concerned with which application is requesting the data. As long as the calling application has the required permission to access the data the implementation should just return data based on what URI is being requested. However, I am trying something different in my content provider and need to find out which application is calling the provider before responding to the query for data. Is there a way for my content provider to find this out? Any help will be much appreciated.

推荐答案

假设你只找出它是否是你的应用程序访问提供商或第三方应用程序访问供应商有兴趣,你可以叫 ContentProvider.getCallingPackage(),看看是否返回的包名相匹配的应用程序的包名。

Assuming you are only interested in finding out whether it is your application accessing the provider or a third-party application accessing the provider, you can call ContentProvider.getCallingPackage() and see if the package name returned matches your application's package name.

编辑:对于API等级18之前,有一个变通办法,我知道。这是一种解决方法,所以它不是理想,但它的工作原理:一些额外的数据块追加到URI标识您的应用程序

For API Level 18 and before, there is one workaround method that I know. It is a workaround so it's not ideal, but it works: append some extra piece of data to the URI to identify your application.

所以,举例来说,如果一个URI为你的供应商通常会内容://com.example.app/table1 ,您的应用程序将使用URI 内容://com.example.app/table1/identifier 。你会使用不同的code每个模式都URI模式添加到您的 UriMatcher 。使URI没有公开可通过您的合同类标识符,但保留标识符私人。第三方将按照什么是你的合同类可公开获得的构造URI,因此,将不包括在URI标识。当你构建URI,包括标识符。因此,无论的URI将指向相同的数据,但你可以在此基础上自己的应用程序和第三方应用程序之间的区别code中的匹配的回报,从比赛(URI URI)。它不会与 ContentResolver的干扰要么因为解析器仅检查URI的授权部分。再次,这是假定你只关心从应用中区别来电。

So for example, if a URI for your provider would normally be content://com.example.app/table1, your app would use the URI content://com.example.app/table1/identifier. You would add both URI patterns to your UriMatcher using a different code for each pattern. Make the URI without the identifier publicly available through your contract class, but keep the identifier private. Third-parties will construct the URI according to what is publicly available in your contract class, and therefore, will not include the identifier in the URI. When you construct the URI, include the identifier. So both URIs will point to the same data, but you can differentiate between your own app and third-party apps based on which code the matcher returns from match(Uri uri). It will not interfere with the ContentResolver either since the resolver only examines the authority portion of the URI. Again, this assumes you only care about distinguishing calls from your app.