When developing an e-commerce APP application, in order to prevent the activity from being created multiple times, I set Android :launchMode="singleTask" and the code is as follows:
- <!-- Main page -->
- <activity
- android:name="com.sondon.mayi.activity.MainTabActivity_"
- android:label="@string/app_name"
- android:launchMode="singleTask"
- >
It was OK all the way through development, so I became careless.
Then when debugging umeng push, there was a problem that getIntent() could not obtain data. Various debugs and various Log output logs showed that there was data in the part where umeng processed the message, but there was no Intent in MainTabActivity. data.
umeng message processing part of the code:
-
-
-
-
- UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler(){
-
- @Override
- public void launchApp(final Context context, final UMessage msg) {
- new Handler(getMainLooper()).post(new Runnable() {
- @Override
- public void run() {
-
- myprefs.position().put(1);
- Intent intent = new Intent(context,MainTabActivity_.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- for (Entry<String, String> entry : msg.extra.entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue();
- if ("code".equals(key.trim())) {
- LogUtil.e("Umeng...launchApp","key :"+key+" value :"+value);
- Bundle bundle=new Bundle();
- bundle.putString("news_code",value);
- intent.putExtras(bundle);
- }
- }
- context.startActivity(intent);
- }
- });
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- };
-
- mPushAgent.setNotificationClickHandler(notificationClickHandler);
折腾了很久,一直以为是umeng的问题,查了很多资料,搞了很久,最后才想起我这个activity的launchMode是singleTask,赶紧google了一下关于singleTask的资料,发现如下:
launchMode为singleTask的时候,通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上,但这个时候,系统就不会再调用通常情况下我们处理请求数据的onCreate方法,而是调用onNewIntent方法
于是赶紧在我的MainTabActivity页面中添加OnNewIntent方法,方法如下:
-
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- LogUtil.e("MainTabActivity", " onNewIntent...");
- handleIntent(intent);
- }
google的时候又发现了这样的提醒:
不要忘记,系统可能会随时杀掉后台运行的Activity,如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法,如下所示:
觉得别人考虑的真是缜密啊,佩服,赶紧给自己代码打上补丁吧,修改如下:
-
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- LogUtil.e("MainTabActivity", " onNewIntent...");
- handleIntent(intent);
- }
-
- @Override
- protected void onStart() {
- super.onStart();
- LogUtil.e("MainTabActivity", " onStart...");
- handleIntent(getIntent());
- }
-
-
-
-
-
-
-
- private void handleIntent(Intent intent){
- if(intent!=null){
- String news_code=intent.getExtras().getString("news_code");
-
- myprefs.news_code().put(news_code);
- }
- }
That's it. I learned a lot afterwards. Basic things are still very important. There are some things that are rarely used, so you should pay special attention to them!