LoginSignup
0
0

More than 5 years have passed since last update.

Intentのアクション名など他と重複しないキー名の宣言 with kotlin

Last updated at Posted at 2016-06-24

ServiceからBroadcastするときなどIntentにアクション名を設定しますが、これは他と重複しないものにする必要があります。Serviceのパッケージ名+クラス名+アクション名にしておくと安全ですが、タイプするのは面倒だし、パッケージ名が変わった時、合わせて修正するのも面倒。

このようにすると便利だと思います。

class Service1 : Service() {
    companion object {
        val ACTION_HOGE: String
            get() = javaClass.canonicalName + ".HOGE"
    }

    private fun sendBroadcast() {
        val intent = Intent(ACTION_HOGE)
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
    }

CannonicalNameでパッケージ名+クラス名が得られるので、それにアクション名を足せばユニークになります。

特定のクラスでだけ使う設定をSharedPreferenceで保存する時のキー名も同じようにできますね。

val pref = context.getSharedPreferences(javaClass.canonicalName, Context.MODE_PRIVATE)
val editor = pref.edit()
editor.putInt("value1", 100)
editor.commit()
0
0
0

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
0
0