Launching Activity from Widget first stops app from launching the same activity
I have a very strange behavior in my Android app. 开发者_运维技巧Here's what happens:
If I "launch" the app (click its icon) and start an activity through startActivity(Intent) it works fine. If I then add a widget and click on it to launch the same intent through setOnClickPendingIntent() it also works well.
Now, if I hit the back button until the application "closes" (i.e. I'm back to the home screen) and tap the widget, the Activity displays ok. However, when I try to start the same activity/intent from within the app, it does not work anymore. The Activity is not started and I remain on the same screen. I debugged the code and the startActivity(Intent) method is called exactly like before (exactly the same piece of code is being executed).
If I go back to the home screen and "launch" the app again (click on its icon) everything gets back to normal.
Any ideas on what could be causing the problem.
Phone is Android 2.3.3. and the app is built against Android 2.1-update1 (API Level 7).
I found what the problem was.
The Widget was launching the intent by setting the flag intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
In my list view activity, I was using the same flag to launch the intent
Intent intent = new Intent("x.y.NEWS_DETAIL");
intent.putExtra(NewsConstants.ISSUE_ID, newsId);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
For some reason, requesting an Activity with the FLAG_ACTIVITY_NEW_TASK when that activity is already in the history prevents it from displaying. I fixed the code by removing the flag and launching the intent from the current context, instead of the application context:
Intent intent = new Intent("x.y.NEWS_DETAIL");
intent.putExtra(NewsConstants.ISSUE_ID, newsId);
startActivity(intent);
I have to find out now what's the effect of that flag on a PendingIntent and if it should be used with Widgets or not.
精彩评论