最近在出去面试的时候,有面试官问了这样一个问题,什么情况下调用 ==Activity的onNewIntent(Intent intent)== 函数
这个问题很简单,源码里面说的很清楚
/**
* 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.
*
* <p>An activity will always be paused before receiving a new intent, so
* you can count on {@link #onResume} being called after this method.
*
* <p>Note that {@link #getIntent} still returns the original Intent. You
* can use {@link #setIntent} to update it to this new Intent.
*
* @param intent The new intent that was started for the activity.
*
* @see #getIntent
* @see #setIntent
* @see #onResume
*/
protected void onNewIntent(Intent intent) {
}
注释说的很清楚了,就是在 Activity 的启动模式设置为 ==singleTop== 或者 调用==startActivity== 的时候为Intent 设置 flag ==为FLAG_ACTIVITY_SINGLE_TOP==
无论哪种情况,当Activity将在Activity Task 顶部重新启动对于正在启动的活动的新实例,onNewIntent()将在现有实例上调用,其目的是重新启动。
注意这句
@param intent The new intent that was started for the activity.
就是这样,然后紧接着 面试官又问: getIntent 获取到的Intent 和 onNewIntent 中的intent 是同一个吗?
有点懵了,这个问题从来没有想过啊,但是仔细分析了一下,应该是同一个,因为 onNewIntent 的回调,是在复用这个activity 的基础上的,既然是复用,应该是同一个!
于是我回答是 应该是同一个,看到面试官露出满意的笑容,我觉的应该是蒙对了!虽然猜对了,但还是看看源码,源码里面说的很清楚:
//返回的是开启这个Activity 的Intent
/** Return the intent that started this activity. */
public Intent getIntent() {
return mIntent;
}
看到这里,应该就明白了,注释里说的很清楚,返回的也是 开启这个activity 的intent,
网友评论