Cly*_*yde 14 android android-intent android-notifications android-activity
我有一个应用程序,它会在选择启动活动时发出通知.根据Android文档,我可以使用NavUtils.shouldUpRecreateTask来检查活动是否已直接启动(即来自通知)或通过正常活动堆栈启动.但它给出了错误的答案.我正在JellyBean上测试它,但使用支持库.
基本上,即使从通知中启动了活动,shouldUpRecreateTask也总是返回false.
关于为什么uppRecreateTask未能给出正确答案的任何想法?
这不对!当您从通知开始时,您必须在构建通知时创建堆栈,如下所述:http://developer.android.com/guide/topics/ui/notifiers/notifications.html#NotificationResponse
因此,在创建通知时,您必须执行以下操作:
Intent resultIntent = new Intent(this, ResultActivity.class);
// ResultActivity is the activity you'll land on, of course
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent to the top of the stack
// make sure that in the manifest ResultActivity has parent specified!!!
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)
然后当你点击UP按钮时,你需要常规代码,即:
if (NavUtils.shouldUpRecreateTask(this, intent)) {
// This activity is NOT part of this app's task, so
// create a new task when navigating up, with a
// synthesized back stack.
TaskStackBuilder.create(this)
// Add all of this activity's parents to the back stack
.addNextIntentWithParentStack(intent)
// Navigate up to the closest parent
.startActivities();
} else {
NavUtils.navigateUpTo(this, intent);
}
Run Code Online (Sandbox Code Playgroud)
这对我来说非常适合.
我仍然不知道为什么uppRecreateTask失败 - 查看它的源代码并没有多大帮助.但解决方案非常简单 - 我只是向附加到通知的Intent添加一个额外的标志值,并在onCreate()中进行检查.如果已设置,则已从通知中调用Activity,因此必须重新创建后栈.
代码如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
fromNotification = b.getInt("fromNotification") == 1;
setContentView(R.layout.threadlist);
}
@Override
public boolean onHomeButtonPressed() {
if(fromNotification) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder tsb = TaskStackBuilder.from(this)
.addNextIntent(new Intent(this, COPAme.class));
tsb.startActivities();
}
// Otherwise, This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
finish();
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2752 次 |
| 最近记录: |