我有一个带有上下文菜单的非启动器 Activity 。该菜单包含一个选项,用于将 Activity 作为快捷方式添加到 Android 主屏幕。
我正在使用以下代码创建快捷方式。
private void ShortcutIcon(){
Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
必要的权限和 Intent 过滤器已正确设置。当我运行这段代码时,快捷方式创建成功。单击快捷方式时, Activity 将按预期打开。
但是,我的 Activity 显示了一些动态数据。为此,我需要将一个小字符串变量传递给 Activity 。
我曾尝试在 setAction
之前使用此代码(就像您将额外数据传递给启动 Activity 的正常 Intent 一样)
addIntent.putExtra("key_primarykey", value_i_want_to_pass);
但是,当用户单击快捷方式时,在 Activity 内部,value_i_want_to_pass
变为 Null。
Whatsapp
等一些应用程序允许执行完全相同的操作。您可以保存聊天的快捷方式。还有一些拨号器应用
允许将联系人添加为快捷方式,这样当您点击快捷方式时,会自动发起语音通话。
我想知道如何将一些数据从我的快捷方式传递到我的 Activity 。
最佳答案
您正在将数据发送到 addIntent
,Launcher 的 Broadcast Receiver 将捕获该数据。
只需更改以下行
addIntent.putExtra("key_primarykey", value_i_want_to_pass);
到
shortcutIntent.putExtra("key_primarykey", value_i_want_to_pass);
并在将 shortcutIntent
设置为 addIntent
之前将其与您的 shortcutIntent
代码一起写入。
这样您为快捷方式设置的 Action Intent
就会返回正确的值。
所以修改后的代码如下。
private void ShortcutIcon(){
Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.putExtra("key_primarykey", value_i_want_to_pass);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
关于android - 如何从主屏幕快捷方式将额外数据传递给 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42715782/