0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

アプリ起動時に1度だけ処理を行う方法

0
Posted at

Androidアプリで起動時に1度だけ処理を行いたい時があります。Application を継承する方法をメモします。

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        initializeApp()
    }

    private fun initializeApp() {
        FirebaseApp.initializeApp(this)
        AppLogger.initialize()
        NetworkManager.initialize(this)
        // アプリ起動時の初期処理
    }
}

Application.onCreate()はプロセスが作られたときに呼ばれ、以下のようなアプリ全体で使用する機能の初期化を行います。

  • Firebaseなどのライブラリの初期化
  • ログ機能の初期化
  • Roomなどのデータベースの初期化
  • ネットワーク関連の初期化
  • アプリ全体で使用する設定の読み込み
  • ライブラリの初期設定

AndroidManifest.xmlに登録する

作成した Application クラスをManifestに登録します。

<application
    android:name=".MyApplication"
    android:label="@string/app_name"
    android:theme="@style/Theme.MyApp">

    <activity
        android:name=".MainActivity"
        android:exported="true">
        ...
    </activity>

</application>

これでAndroidがアプリのプロセスを起動したときに、MyApplication が使用されます。

インストール後、初回起動時だけ処理を行う

もし最初の1度だけ処理を行いたい場合、SharedPreferences などでフラグを管理する方法があります。

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        val preferences = getSharedPreferences("app_preferences", MODE_PRIVATE)
        val isFirstLaunch = preferences.getBoolean("is_first_launch", true)

        if (isFirstLaunch) {
            // 初回起動時だけ実行する処理

            
            preferences
                .edit()
                .putBoolean("is_first_launch", false)
                .apply()
        }
    }
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?