LoginSignup
4

More than 3 years have passed since last update.

Androidで他アプリのリソースを使う

Posted at

「Androidは他のアプリのリソースを取得することができる」ということを聞いたので、実際どのように行うのかを調べてみました。

ちなみに他社アプリのパッケージ名はこちらなどの情報を元にすぐ調べることができますが、リソース名までは(たぶん)わかりません。なので使うとしたら同じ会社のアプリで共通管理をするため、などの理由になるのかなと思うのですが、それはそれでややこしいことになりそうなのであまり実務で使うことはないのかなぁと思っています。

サンプルコードはこちらにおいています。
https://github.com/akatsuki174/UseOtherAppResourceSample

※環境
Android Studio: 3.4
Kotlin: 1.3.31

文字列

試しに設定アプリの文字列リソースを取得してみます。

fun showOtherAppResource() {
    val res: Resources?
    try {
        val packageName = "com.android.settings"
        // 他アプリのリソース群を取得
        res = this.packageManager.getResourcesForApplication(packageName)
        // パッケージ名、リソースの種類、リソース名を指定
        val resourceId = res?.getIdentifier("clear_activities", "string", packageName)
        if (resourceId != 0 && resourceId != null) {
            val text = this.packageManager.getText(packageName, resourceId, null)
            Toast.makeText(this, text, Toast.LENGTH_LONG).show()
        }
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
}

画像

こちらは画像です。リソース名まで知っている実例がなかったので、パッケージ名は適当なものにしています。

fun showOtherAppImage() {
    val res: Resources?
    try {
        val packageName = "com.hogehoge"
        res = this.packageManager.getResourcesForApplication(packageName)
        // 今回はmipmapを指定しているが、もちろんdrawableなどでも画像は取得できる
        val resourceId = res?.getIdentifier("ic_launcher", "mipmap", packageName)
        // API level 22以降はこの書き方
        val drawable = resourceId?.let { ResourcesCompat.getDrawable(res, it, null) }
        if (resourceId != 0 && resourceId != null) {
            val toast = Toast(this)
            toast.duration = Toast.LENGTH_LONG
            // 画像要素しかないレイアウトを作成して埋め込んでいます
            val layout = layoutInflater.inflate(R.layout.custom_toast, linearLayout)
            layout.customToastImage.setImageDrawable(drawable)
            toast.view = layout
            toast.show()
        }
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
}

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
4