如何从主屏幕快捷方式将额外数据传递给活动?

时间:2017-03-10 10:13:46

标签: android android-intent android-activity android-shortcut

我有一个带有上下文菜单的Non-Launcher活动。该菜单包含一个选项,可以将活动添加到Android主屏幕作为快捷方式。

我使用以下代码创建快捷方式。

RegularExpressionAttribute

正确设置了必要的权限和意图过滤器。当我运行此代码时,快捷方式已成功创建。在快捷方式单击时,活动将按预期打开。

但是,我的活动显示了一些动态数据。为此,我需要将一个小字符串变量传递给活动。

我尝试在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); } 之前使用此代码(就像您将额外数据传递给正常意图启动活动一样)

setAction

但是,当用户点击活动内部的快捷方式时,addIntent.putExtra("key_primarykey", value_i_want_to_pass); 会显示为空。

某些应用程序(如value_i_want_to_pass)可以完全相同。您可以保存聊天的快捷方式。还有一些Whatsapp允许将联系人添加为快捷方式,这样当您点按快捷方式时,系统会自动启动语音通话。

我想知道如何将快捷方式中的一些数据传递给我的活动。

1 个答案:

答案 0 :(得分:0)

您正在将数据发送到addIntent,这些数据将由Launcher的广播接收器捕获。

只需更改以下行

addIntent.putExtra("key_primarykey", value_i_want_to_pass); 

shortcutIntent.putExtra("key_primarykey", value_i_want_to_pass);

并在将shorcutIntent设置为shortcutIntent之前将其与addIntent代码一起编写。
因此,您为快捷方式设置的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);
}
相关问题