您的位置:首页 > 移动开发 > Android开发

android之onNewIntent()用法

2016-05-30 17:33 344 查看
onNewIntent()用法

知识点:

1、intent的显示和隐式启动;

2、activity对intent的action的相应;

3、onNewIntent()和singleTask(栈唯一模式)的结合使用;

4、使用onNewIntent()需要注意坑;

在activity中,其实还有一个方法onNewIntent(),可以重写,这个方法在结合启动模式,有了很大的用处。关于启动模式,请看这里:点击打开链接

1、其他应用发Intent,执行下列方法:

Uri uri = Uri.parse("philn://blog.163.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
亦可:intent.setAction(Intent.ACTION_VIEW);
然后:startActivity(intent);

2、接收Intent声明:

<activity android:name=".IntentActivity" android:launchMode="singleTask"
android:label="@string/testname">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
</activity>


3、我们这里结合启动模式的singleTask模式来讲。singleTask模式:就是栈唯一原则。即是在同一个应用程序中,launchmode设置为singleTask的activity,在这个应用程序中,有且只有一个实例。

设置栈唯一原则设置。我们需要通过在AndroidManifest.xml配置activity的加载方式(launchMode)来设置栈唯一原则模式,如下所示:

<activity android:label="@string/app_name" android:launchmode=“singleTask"android:name="Activity1"></activity>

所以,我们可以知道:如果之前创建了目标Activity的实例,此时这个实例处于onPause、onStop 状态的话,再接收到intent的话,她的执行顺序为:

onNewIntent,onRestart,onStart,onResume。

activity栈唯一原则下,通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上,但这个时候,系统就不会再创建一个新的实例,不会调用onCreate方法,而是调用onNewIntent方法,如下所示:

protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);//must store the new intent unless getIntent() will return the old one
}

我们需要知道,在内存吃紧的情况下,系统可能会kill掉后台运行的
Activity
,如果不巧要启动的那个activity实例被系统kill了,那么系统就会调用
onCreate
方法,而不调用 onNewIntent
方法。这里有个解决方法就是在
onCreate
和 onNewIntent
方法中调用同一个处理数据的方法,如下所示:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getNewIntent();
}

protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);//must store the new intent unless getIntent() will return the old one
getNewIntent();
}

private void getNewIntent(){
Intent intent = getIntent(); //use the data received here
}

注意onNewIntent()中的陷阱:

有时候,我们在多次启动同一个栈唯一模式下的activity时,在onNewIntent()里面的getIntent()得到的intent感觉都是第一次的那个数据。对,这里就是这个陷阱。因为它就是会返回第一个intent的数据。就是这么坑。

原因就是我们没有在onNewIntent()里面设置setIntent(),将最新的intent设置给这个activity实例。

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);//设置新的intent
int data = getIntent().getIntExtra("tanksu", 0);//此时的到的数据就是正确的了
}

在这里,如果你没有调用setIntent()方法的话,则getIntent()获取的intent都只会是最初那个intent(Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息