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

前端 未结 1 1347
逝去的感伤
逝去的感伤 2021-01-17 04:15

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 a

相关标签:
1条回答
  • 2021-01-17 04:45

    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.

    0 讨论(0)
提交回复
热议问题