Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BroadcastReceiver does not receive intent Intent.ACTION_LOCALE_CHANGED

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.

like image 203
user3148156 Avatar asked Oct 17 '25 11:10

user3148156


2 Answers

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>
like image 112
Ranjithkumar Avatar answered Oct 19 '25 01:10

Ranjithkumar


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);
}

}
like image 40
alijandro Avatar answered Oct 19 '25 01:10

alijandro