I want my app to be aware anytime the user changes the locale. So in my Application
class, I create a receiver
to listen to the system intent ACTION_LOCALE_CHANGED
:
public final class MyApp extends Application {
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
String locale = Locale.getDefault().getCountry();
Toast.makeText(context, "LOCALE CHANGED to " + locale, Toast.LENGTH_LONG).show();
}
};
@Override public void onCreate() {
IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, filter);
}
}
When I press home and go to the settings app to change my locale, the Toast is not shown. Setting the breakpoint inside onReceive
shows it never gets hit.
Why do you want the BroadcastReceiver in Application class. My suggestion is to have a separate class for BroadcastRecevier.
public class LocaleChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction (). compareTo (Intent.ACTION_LOCALE_CHANGED) == 0)
{
Log.v("LocaleChangedRecevier", "received ACTION_LOCALE_CHANGED");
}
}
}
and register your Brodcast receiver in Manifest file.
<receiver
android:name=".LocaleChangedReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.LOCALE_CHANGED" />
</intent-filter>
</receiver>
Intent.ACTION_LOCALE_CHANGED
is not a local broadcast, so it won't work when you register it with LocalBroadcastManager
. LocalBroadcastManager
is used for the broadcast used inside your app.
public class MyApp extends Application {
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String locale = Locale.getDefault().getCountry();
Toast.makeText(context, "LOCALE CHANGED to " + locale,
Toast.LENGTH_LONG).show();
}
};
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
registerReceiver(myReceiver, filter);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With