LoginSignup
7

More than 5 years have passed since last update.

ContentProviderのauthorityの取得方法

Posted at

ContentProviderのauthorityの取得方法

ContentProviderを使用する場合に、authorityはmanifestに書いてあるauthorityをコピペで

public static final String AUTHORITY = "com.hogehoge.jp";

定数として定義するのが一般的なやり方だと思います。

AndroidManifest.xmlのauthorityはContextとContentProviderの実装クラスさえ分かれば、コードからでも取ること可能です。

    /**
     * get authority from AndroidManifest.xml
     * @param context context
     * @param providerClass providerClass
     * @return authority
     */
    public static String getAuthority(Context context, Class< ? extends ContentProvider> providerClass){
        PackageManager manager = context.getApplicationContext().getPackageManager();
        try {
            ProviderInfo providerInfo = manager.getProviderInfo(
                    new ComponentName(context, providerClass), PackageManager.GET_META_DATA);
            return providerInfo.authority;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

他にもAndroidManifest.xmlの内容はPackageManagerから色々と取得できるみたいですね。

■参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7