我想做的是非常类似于"ColorNote"应用程序。基本上我有应用程序小部件,可以启动"EditNote"活动,我想在任务中只有一个实例的活动;假设用户1。点击小部件A,启动"编辑笔记"。回家,3。点击小部件B,启动"EditNote"。然后点击后退键,用户应该回到主屏幕。我将rowid存储在sqlite数据库中,并在意图中传递感兴趣的行id以获取"EditNote"活动。
我试图将"launchMode"设置为"singleTask"或"singleInstance",Android将绕过"onCreate"并直接调用"onNewIntent"(这是预期的,因为它的文档),但问题是每次"EditNote"然后获得包含相同rowId的相同意图,因此步骤3"EditNote"A将被启动。(如果"launchMode"被设置为"standard",那么任务将包含多个具有正确id的"EditNote"活动。)
这是appWidgetProvider中的代码片段:int rowId = dataAccess.getIdByAppWidgetId(appWidgetId);
intent.putExtra(NoteColumns.ID, ((Integer)rowId).longValue());
PendingIntent pending = PendingIntent.getActivity(context, appWidgetId,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.appwidget, pending);
appWidgetManager.updateAppWidget(appWidgetId, views);
"EditNote"活动中的代码:
@Override
protected void onNewIntent(Intent intent) {
Log.d(TAG, "\\\new intent: "
+" the rowId is "+getIntent().getLongExtra(NoteColumns.ID, -1));
super.onNewIntent(intent);
}
最简单的做法是在Edit Note B中,重写onKeyDown和onKeyUp以启动主屏幕的新意图:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if(keyCode==KeyEvent.KEYCODE_BACK){
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
return true; //this tells android that you have handled the keypress
}
else return false; // this tells android to handle the key press
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event){ // in new versions of android, to support canceled button presses on virtual keys, onKeyUp needs to be used
super.onKeyDown(keyCode, event, mapview);
if(keyCode==KeyEvent.KEYCODE_BACK){
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
return true; //this tells android that you have handled the keypress
}
else return false; // this tells android to handle the key press
return super.onKeyUp(keyCode, event);
}
事实证明,是进入intent的extra的key导致了这个问题:
intent.putExtra(NoteColumnteger)rowId).longValue());
"NoteColumns。ID"是"_id",当使用稍微不同的键时,问题就消失了:
public static final String ROW_ID = "rowId";
当活动的launchMode为"standard"时,为什么"_id"按预期工作,这个难题仍然没有解决。