今天在看android系统自带的“时钟”应用的代码时候,在DeskClock.java这文件里有这样一个函数:
@Override
public void onNewIntent(Intent newIntent) {
super.onNewIntent(newIntent);
if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
// update our intent so that we can consult it to determine whether or
// not the most recent launch was via a dock event
setIntent(newIntent);
// Timer receiver may ask to go to the timers fragment if a timer expired.
int tab = newIntent.getIntExtra(SELECT_TAB_INTENT_EXTRA, -1);
if (tab != -1) {
if (mActionBar != null) {
mActionBar.setSelectedNavigationItem(tab);
}
}
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mSelectedTab = CLOCK_TAB_INDEX;
if (icicle != null) {
mSelectedTab = icicle.getInt(KEY_SELECTED_TAB, CLOCK_TAB_INDEX);
}
// Timer receiver may ask the app to go to the timer fragment if a timer expired
Intent i = getIntent();
if (i != null) {
int tab = i.getIntExtra(SELECT_TAB_INTENT_EXTRA, -1);
if (tab != -1) {
mSelectedTab = tab;
}
}
initViews();
setHomeTimeZone();
}
onNewIntent这个函数到底想做什么?这个函数何时调用? 我觉得有必要说一下。
在Activity.java里面有对这个函数的详细说明(英文的说明太多,我们一段一段来介绍):
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag when calling {@link #startActivity}. In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be
called on the existing instance with the Intent that was used to re-launch it.
其意思是:当一个Activity的启动模式是singleTop(或者是 Intent 用FLAG_ACTIVITY_SINGLE_TOP来启动)时候,当这个启动的Activity实例在这个activity stack 的栈顶时候,如果这个activity被从新Launch,那么是不会实例化一个新的该activity实列的,而是用当前这个在activity stack 的栈顶的那个。这样一来,这个已经在栈顶的activity的onNewIntent函数就会被调用,而此时该函数的参数newIntent就是这次Launch该activity所用的 Intent。
对照上面onNewIntent这个函数的用法就很清楚了。由于直接调用在activity stack 中的一个实例,所以这个activity的onCreate() 更本就不会调用,那么此次调用这个activity的Intent怎么传递过来呢?为了解决这个问题,onNewIntent()这个函数就出现了,他就是在这种情况下传递Intent的一个途径!
从上面“时钟”应用的DeskClock这个activity的onNewIntent()就是这么用的:
利用传递过来的newIntent,获知当前这次Launch该activity是打开这个activity的那一个ActionBar:
mActionBar.setSelectedNavigationItem(tab);
我想我已经说的很清楚了吧!