在 Android 中打开片段的动态快捷方式
Dynamic Shortcuts to open Fragments in Android
您好,我正在开发一个有两种用户类型的应用程序:管理员和普通用户;管理员显然比普通用户有更多的操作,所以我需要使用动态快捷方式,这取决于创建快捷方式的用户。
至此,一切都已编纂并开始运作。但是,在分配 Intent
时,即使是 MainActivity
我也会收到错误消息。
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.motusk.Monit", "com.motusk.Monit.activity.MainActivity"));
shortcut.add(new ShortcutInfo.Builder(this, "ub")
.setShortLabel("Location")
.setLongLabel("Location")
.setIcon(Icon.createWithResource(this, R.drawable.bg))
.setIntent(intent)
.build());
我也试过:
Intent intent = new Intent(this, MainActivity.class);
但是,在两者中我都得到了错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.motusk.Monit/com.motusk.Monit.activity.MainActivity}: java.lang.NullPointerException: intent's action must be set
我需要帮助的是:
1) 如何创建正确的Intent
到MainActivity
?
2) 如何知道按下了哪个快捷键? (根据按下哪个快捷方式打开某个Fragment
的过程将在MainActivity
中执行,所以我需要知道按下了哪个快捷方式)。
根据错误消息,您的 Intent 必须使用 setAction:
设置一个动作
intent.setAction("LOCATION_SHORTCUT");
然后您可以在 Activity 中检查操作:
String action = getIntent() != null ? getIntent().getAction() : null;
if ("LOCATION_SHORTCUT".equals(action)) {
// Show the correct fragment
}
您好,我正在开发一个有两种用户类型的应用程序:管理员和普通用户;管理员显然比普通用户有更多的操作,所以我需要使用动态快捷方式,这取决于创建快捷方式的用户。
至此,一切都已编纂并开始运作。但是,在分配 Intent
时,即使是 MainActivity
我也会收到错误消息。
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.motusk.Monit", "com.motusk.Monit.activity.MainActivity"));
shortcut.add(new ShortcutInfo.Builder(this, "ub")
.setShortLabel("Location")
.setLongLabel("Location")
.setIcon(Icon.createWithResource(this, R.drawable.bg))
.setIntent(intent)
.build());
我也试过:
Intent intent = new Intent(this, MainActivity.class);
但是,在两者中我都得到了错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.motusk.Monit/com.motusk.Monit.activity.MainActivity}: java.lang.NullPointerException: intent's action must be set
我需要帮助的是:
1) 如何创建正确的Intent
到MainActivity
?
2) 如何知道按下了哪个快捷键? (根据按下哪个快捷方式打开某个Fragment
的过程将在MainActivity
中执行,所以我需要知道按下了哪个快捷方式)。
根据错误消息,您的 Intent 必须使用 setAction:
设置一个动作intent.setAction("LOCATION_SHORTCUT");
然后您可以在 Activity 中检查操作:
String action = getIntent() != null ? getIntent().getAction() : null;
if ("LOCATION_SHORTCUT".equals(action)) {
// Show the correct fragment
}