How to find out a calling activity for content provider in Android?

我们两清 提交于 2019-12-01 14:37:57

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.

EDIT: 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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!