use*_*156 1 android broadcastreceiver android-intent
我希望我的应用程序在用户更改语言环境时随时都能识别.所以在我的Application班上,我创建了一个receiver听取系统意图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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我按下主页并转到设置应用程序以更改我的区域设置时,不会显示Toast.在里面设置断点onReceive表明它永远不会被击中.
小智 12
为什么要在Application类中使用BroadcastReceiver.我的建议是为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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在Manifest文件中注册您的Brodcast接收器.
<receiver
android:name=".LocaleChangedReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.LOCALE_CHANGED" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
Intent.ACTION_LOCALE_CHANGED不是本地广播,因此当您使用进行注册时,它将无法使用LocalBroadcastManager。LocalBroadcastManager用于您的应用内部使用的广播。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6185 次 |
| 最近记录: |