简体   繁体   English

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

[英]how to set intent action using value stored in string

I want to add a functionality in my App, where a user can make buttons to launch apps on the device. 我想在我的应用程序中添加功能,用户可以在其中创建按钮以在设备上启动应用程序。 Now, to set this up the user will enter the Intent Action they want to invoke. 现在,要进行设置,用户将输入他们要调用的Intent Action。 If user enters "ACTION_MAIN" as a string value, is it possible to process it as Intent.ACTION_MAIN in java ? 如果用户输入“ ACTION_MAIN”作为字符串值,是否可以在Java中将其作为Intent.ACTION_MAIN处理?

I know using a map can be one solution but maintaining an exhaustive list of all available intents can be cumbersome. 我知道使用地图可能是一种解决方案,但是维护所有可用意图的详尽列表可能很麻烦。 Is their any other solution to this ? 他们对此有其他解决方案吗? Can string value reference a variable ? 字符串值可以引用变量吗?

Lets say the user defined action as a string value is stored in userInput : 假设用户定义的操作作为字符串值存储在userInput

String userInput = "ACTION_MAIN";

You can get the corresponding value of Intent.<ACTION_SOMETHING> using reflection as follows: 您可以使用反射获得对应的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();
}

Example : 范例

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

returns: 返回:

"android.intent.action.MAIN"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM