Android - Listening to a locale change without static variables

半世苍凉 提交于 2019-12-25 15:52:57

问题


I have a BroadcastReceiver that listens to a locale change. Here's my problem:

I navigate to an Activity and then want to change locale (language setting) which I do by going to the settings app. The BroadcastReceiver then listens in onReceive() once a change is made. I then navigate back to the app and when I do so I'd like to take a user to another Activity.

Also, a locale modification corresponds to a change in configuration which means an Activity will be destroyed and created again. https://developer.android.com/guide/topics/resources/runtime-changes.html

Here is the BroadcastReceiver:

public class LocaleReceiver extends BroadcastReceiver {
    public LocaleReceiver() {}

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.

        if(Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())){
            MainActivity.isLocaleChanged = true;
        }
    }
}

And here is the Activity that uses the static variable set by the BroadcastReceiver.

public class MainActivity extends AppCompatActivity {

    public static boolean isLocaleChanged = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(isLocaleChanged){
            Intent intent = new Intent(this,SecondActivity.class);
            startActivity(intent);
            isLocaleChanged = false;
        }
    }
}

And indeed I am able to navigate to a different Activity !

However, I'd like to do this in a manner that does not use static variables (since they are evil :(). Is there any other way to accomplish this.

I'd also be extra happy if there were no SharedPreferences involved.


回答1:


Well, you can turn off configuration changes for locale, implement onConfigurationChanged, check if the change is to the locale, and launch the new activity there. I'm not sure if I'd suggest it though, you'll have issues when you return with strings. This is a case where you have to store state non-locally- either in a static, on disk (sharedPreference) or via a state singleton, or some other means. It isn't that statics are evil, its that they can be misused. This is a case where they make sense.

I'd actually recommend static over shared preference here, as shared preferences may stick around if you don't clear it properly and screw up a later execution of your app. A static won't, it will be cleared when your app is killed worst case.



来源:https://stackoverflow.com/questions/38239551/android-listening-to-a-locale-change-without-static-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!