我的应用程序中确实有多个活动和多个片段。每当我从设备语言设置更改语言环境时,只有当前活动会重新启动。在设备设置下,是否可以通过更改语言来重新启动整个应用程序?
答案 0 :(得分:2)
您可以注册BroadcastReceiver
来监听意图ACTION_LOCALE_CHANGED
,然后在收到意图后,您可以执行重新启动应用程序的逻辑。像这样:
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//RESTART APPLICATION
}
};
//register broadcastreceiver
LocalBroadcastManager.getInstance(getContext())
.registerReceiver(mBroadcastReceiver, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
//remember to unregister in onDestroy with LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
要“重新启动”应用程序,可以使用:
Intent intent = new Intent(this, YourHomeActivity.class);
this.startActivity(intent);
this.finishAffinity();
开始家庭活动并清除所有其他活动。
或者类似这样的东西:
Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
实际上要停止应用程序,然后再重新启动100毫秒(将其设置为所需的值)。