Why SavedInstanceState is not null in activity after changing device language while the app is in background?

350 Views Asked by At

I created a new activity for my app and implemented a BroadcastReceiver to handle the device language changing and when the user put the app in background and change the language, the activity should be recreated. I call this method in onCreate in my activity and I check if savedInstanceState is null before calling the languageReceiver(), but when I change the language, the savedInstanceState is not null and the method is not called...

The setupLangReceiver() method

private fun setupLangReceiver(): BroadcastReceiver? {
    if (mLangReceiver == null) {
        mLangReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                recreateActivity(intent)
            }
        }
        registerReceiver(mLangReceiver, IntentFilter(Intent.ACTION_LOCALE_CHANGED))
    }
    return mLangReceiver
}

The recreateActivity() method

 private fun recreateActivity(intent: Intent) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
    finish()
    overridePendingTransition(0, 0)
    startActivity(intent)
    overridePendingTransition(0, 0)
}

SetupLangReceiver method calling

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_prb_module)
    ThemeUtils.onActivityCreateSetTheme(this)

    if (savedInstanceState == null) {
        setupLangReceiver()
    }
1

There are 1 best solutions below

2
On

After u change the system langugae, ur app can be recreate by the system. And the system saves the activity's sate automatically. So u can ovveride the method onSaveInstanceState