1. 程式人生 > >設定語言改變時,主activity 會重新啟動

設定語言改變時,主activity 會重新啟動

語言變化後,當不設定android:configChanges這項時,會執行:onPause -> onStop -> onDestory -> onCreate -> onStart -> onResume。

如果設定了 android:configChanges="orientation|keyboard|keyboardHidden|locale"

將執行

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}


當然這樣將會導致語言變化後,Launcher的語言並沒有改變,這並不符合專案需求。

這時可以在ondestroy方法中設定:

if(Build.VERSION.SDK_INT<=7){
Log.e(TAG, "destroy"+Build.VERSION.SDK_INT);
Intent intent = new Intent(getApplicationContext(), Launcher.class);
           PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0);


           // We want the alarm to go off 30 seconds from now.
           Calendar calendar = Calendar.getInstance();
           calendar.setTimeInMillis(System.currentTimeMillis());
           calendar.add(Calendar.SECOND, 1);


           // Schedule the alarm!
           AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
           am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
  ActivityManager acm = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
       acm.restartPackage("com.android.launcher");
}else{
                     android.os.Process.killProcess(android.os.Process.myPid());
}

這樣就會KIll掉整個程序。