如何使用存储在字符串中的值设置意图操作



我想在我的应用程序中添加一个功能,用户可以在其中制作按钮以在设备上启动应用程序。现在,要进行此设置,用户将输入他们想要调用的意向操作。如果用户输入"ACTION_MAIN"作为字符串值,是否可以在java中将其Intent.ACTION_MAIN处理?

我知道使用地图可能是一种解决方案,但维护所有可用意图的详尽列表可能很麻烦。他们还有其他解决方案吗?字符串值可以引用变量吗?

假设用户定义的操作作为字符串值存储在userInput中:

String userInput = "ACTION_MAIN";

您可以使用反射获取相应的Intent.<ACTION_SOMETHING>值,如下所示:

try {
    String action = (String) Intent.class.getDeclaredField(userInput).get(String.class);
    // use the action value here..
} catch (Exception e) {
    // no such action possible, maybe mistyped the action name
    e.printStackTrace();
}

示例

String action = (String) Intent.class.getDeclaredField("ACTION_MAIN").get(String.class);

返回:

"android.intent.action.MAIN"

最新更新