【问题标题】:Listing all extras of an Intent列出 Intent 的所有额外内容
【发布时间】:2011-08-23 13:22:57
【问题描述】:

出于调试原因,我想列出 Intent 的所有额外内容(及其值)。现在,拿到钥匙已经不是问题了

Set<String> keys = intent.getExtras().keySet();

但是获取键的值对我来说是一个,因为有些值是字符串,有些是布尔值...我怎样才能在循环中获取值(循环通过键)并将值写入日志文件?感谢您的任何提示!

【问题讨论】:

    标签: android android-intent


    【解决方案1】:

    这是我用来获取有关无证(第 3 方)意图信息的信息:

    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        for (String key : bundle.keySet()) {
            Log.e(TAG, key + " : " + (bundle.get(key) != null ? bundle.get(key) : "NULL"));
        }
    }
    

    确保在循环之前检查bundle 是否为空。

    【讨论】:

    • 我刚刚发现Intent Intercept Android app。这也有效。
    • if (bundle == null) { return; } FTW
    • Bundle bundle = data.getExtras(); 其中data 是意图。适合安卓初学者。
    • 在记录之前需要检查该值是否为空,如果是则检查value = "null"
    • 谢谢!正在寻找一种方法来检查这个未记录的 iTracing 应用程序中提供的所有密钥,以通过便宜的蓝牙按钮控制我的手机。像魅力一样工作!
    【解决方案2】:

    这就是我如何定义实用方法来转储 Intent 的所有额外内容。

    import java.util.Iterator;
    import java.util.Set;
    import android.os.Bundle;
    
    
    public static void dumpIntent(Intent i){
    
        Bundle bundle = i.getExtras();
        if (bundle != null) {
            Set<String> keys = bundle.keySet();
            Iterator<String> it = keys.iterator();
            Log.e(LOG_TAG,"Dumping Intent start");
            while (it.hasNext()) {
                String key = it.next();
                Log.e(LOG_TAG,"[" + key + "=" + bundle.get(key)+"]");
            }
            Log.e(LOG_TAG,"Dumping Intent end");
        }
    }
    

    【讨论】:

    • 谢谢!现在,如果只有 android 团队会开始像这样实现有用的 .toString 覆盖。
    【解决方案3】:

    一行代码就可以搞定:

    Log.d("intent URI", intent.toUri(0));
    

    它输出如下内容:

    "#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10a00000;component=com.mydomain.myapp/.StartActivity;sourceBounds=12%20870%20276% 201167;l.profile=0;结束"

    在这个字符串的末尾(我加粗的部分)你可以找到额外的列表(在这个例子中只有一个额外的)。

    这是根据toUri documentation: “URI 包含 Intent 的数据作为基础 URI,还有一个描述操作、类别、类型、标志、包、组件和附加功能的附加片段。”

    【讨论】:

    • 如果你只是想调试一下,看看intent的内容是什么,这是最好的选择。非常感谢
    • 这应该是公认的答案。非常适合日志调试!
    【解决方案4】:
    private TextView tv;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        tv = new TextView(this);
        tv.setText("Extras: \n\r");
    
        setContentView(tv);
    
        StringBuilder str = new StringBuilder();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            Set<String> keys = bundle.keySet();
            Iterator<String> it = keys.iterator();
            while (it.hasNext()) {
                String key = it.next();
                str.append(key);
                str.append(":");
                str.append(bundle.get(key));
                str.append("\n\r");
            }
            tv.setText(str.toString());
        }
    }
    

    【讨论】:

      【解决方案5】:

      Bundle 的 get(String key) 方法返回一个 Object。最好的办法是在每个键上调用 get(String) 键集并在 Object 上使用 toString() 来输出它们。这对原语最有效,但您可能会遇到不实现 toString() 的对象的问题。

      【讨论】:

        【解决方案6】:

        Kotlin oneliner,用于调试模式下的评估:

        intent.extras.keySet().map { it to intent.extras.get(it) }
        

        这将打印捆绑包中所有附加组件的列表extras

        【讨论】:

          【解决方案7】:

          我想要一种将意图的内容输出到日志的方法,并且能够轻松读取它,所以这就是我想出的。我创建了一个LogUtil 类,然后采用@Pratik 创建的dumpIntent() 方法,并对其进行了一些修改。一切都是这样的:

          public class LogUtil {
          
              private static final String TAG = "IntentDump";
          
              public static void dumpIntent(Intent i){
                  Bundle bundle = i.getExtras();
                  if (bundle != null) {
                      Set<String> keys = bundle.keySet();
          
                      StringBuilder stringBuilder = new StringBuilder();
                      stringBuilder.append("IntentDump \n\r");
                      stringBuilder.append("-------------------------------------------------------------\n\r");
          
                      for (String key : keys) {
                          stringBuilder.append(key).append("=").append(bundle.get(key)).append("\n\r");
                      }
          
                      stringBuilder.append("-------------------------------------------------------------\n\r");
                      Log.i(TAG, stringBuilder.toString());
                  }
              }
          }
          

          希望这对某人有所帮助!

          【讨论】:

            【解决方案8】:
            Bundle extras = getIntent().getExtras();
            Set<String> ks = extras.keySet();
            Iterator<String> iterator = ks.iterator();
            while (iterator.hasNext()) {
                Log.d("KEY", iterator.next());
            }
            

            【讨论】:

            • for (String key : extras.keySet()) { Log.d(LOG_TAG, key + ": " + extras.get(key)); }
            【解决方案9】:

            您可以使用for (String key : keys) { Object o = get(key); 返回一个对象,在其上调用getClass().getName() 以获取类型,然后执行一组 if name.equals("String") 类型的事情来确定您实际上应该使用哪种方法打电话,是为了获取价值?

            【讨论】:

              【解决方案10】:

              我在 Android 源代码中注意到,几乎每个操作都会强制 Bundle 解包其数据。因此,如果(像我一样)您需要经常执行此操作以进行调试,则可以快速输入以下内容:

              Bundle extras = getIntent().getExtras();
              extras.isEmpty(); // unparcel
              System.out.println(extras);
              

              【讨论】:

                【解决方案11】:

                对不起,如果这太冗长或太迟了,但这是我能找到完成工作的唯一方法。最复杂的因素是 java 没有按引用传递函数,因此 get---Extra 方法需要返回默认值,并且无法修改布尔值来判断默认值是否是偶然返回的,或者因为结果不理想。为此,让方法引发异常比让它返回默认值更好。

                我在这里找到了我的信息:Android Intent Documentation

                    //substitute your own intent here
                    Intent intent = new Intent();
                    intent.putExtra("first", "hello");
                    intent.putExtra("second", 1);
                    intent.putExtra("third", true);
                    intent.putExtra("fourth", 1.01);
                    // convert the set to a string array
                

                Set Documentation

                    String[] anArray = {};
                    Set<String> extras1 = (Set<String>) intent.getExtras().keySet();
                    String[] extras = (String[]) extras1.toArray(anArray);
                    // an arraylist to hold all of the strings
                    // rather than putting strings in here, you could display them
                    ArrayList<String> endResult = new ArrayList<String>();
                    for (int i=0; i<extras.length; i++) {
                        //try using as a String
                        String aString = intent.getStringExtra(extras[i]);
                        // is a string, because the default return value for a non-string is null
                        if (aString != null) {
                            endResult.add(extras[i] + " : " + aString);
                        }
                        // not a string
                        else {
                            // try the next data type, int
                            int anInt = intent.getIntExtra(extras[i], 0);
                            // is the default value signifying that either it is not an int or that it happens to be 0 
                            if (anInt == 0) {
                                // is an int value that happens to be 0, the same as the default value
                                if (intent.getIntExtra(extras[i], 1) != 1) {
                                    endResult.add(extras[i] + " : " + Integer.toString(anInt));
                                }
                                // not an int value
                                // try double (also works for float)
                                else {
                                    double aDouble = intent.getDoubleExtra(extras[i], 0.0);
                                    // is the same as the default value, but does not necessarily mean that it is not double
                                    if (aDouble == 0.0) {
                                        // just happens that it was 0.0 and is a double
                                        if (intent.getDoubleExtra(extras[i], 1.0) != 1.0) {
                                            endResult.add(extras[i] + " : " + Double.toString(aDouble));
                                        }
                                        // keep looking...
                                        else {
                                            // lastly check for boolean
                                            boolean aBool = intent.getBooleanExtra(extras[i], false);
                                            // same as default, but not necessarily not a bool (still could be a bool)
                                            if (aBool == false) {
                                                // it is a bool!
                                                if (intent.getBooleanExtra(extras[i], true) != true) {
                                                    endResult.add(extras[i] + " : " + Boolean.toString(aBool));
                                                }
                                                else {
                                                    //well, the road ends here unless you want to add some more data types
                                                }
                                            }
                                            // it is a bool
                                            else {
                                                endResult.add(extras[i] + " : " + Boolean.toString(aBool));
                                            }
                                        }
                                    }
                                    // is a double
                                    else {
                                        endResult.add(extras[i] + " : " + Double.toString(aDouble));
                                    }
                                }
                            }
                            // is an int value
                            else {
                                endResult.add(extras[i] + " : " + Integer.toString(anInt));
                            }
                        }
                    }
                    // to display at the end
                    for (int i=0; i<endResult.size(); i++) {
                        Toast.makeText(this, endResult.get(i), Toast.LENGTH_SHORT).show();
                    }
                

                【讨论】:

                • 你不想写这么多代码来做这个简单的事情,除非你想让你的代码变得如此复杂,以至于你肯定永远无法完成你的应用程序的更新。前 2 个答案用更少的代码来做到这一点,并使用 Log,这比 Toasts 更适合这种用法
                【解决方案12】:

                Pratik's utility method 的 Kotlin 版本转储 Intent 的所有额外内容:

                fun dumpIntent(intent: Intent) {
                
                    val bundle: Bundle = intent.extras ?: return
                
                    val keys = bundle.keySet()
                    val it = keys.iterator()
                
                    Log.d(TAG, "Dumping intent start")
                
                    while (it.hasNext()) {
                        val key = it.next()
                        Log.d(TAG,"[" + key + "=" + bundle.get(key)+"]");
                    }
                
                    Log.d(TAG, "Dumping intent finish")
                
                }
                

                【讨论】:

                • 使用for (key in bundle.keySet())会更简单
                【解决方案13】:

                在 Kotlin 中将其作为用“,”分隔的字符串!

                val extras = intent?.extras?.keySet()?.map { "$it: ${intent.extras?.get(it)}" }?.joinToString { it }
                

                基于 ruX 答案。

                【讨论】:

                  【解决方案14】:

                  如果您想要调试的只是一个字符串(OP 暗示但没有明确说明),只需在附加 Bundle 上使用 toString

                  intent.getExtras().toString()
                  

                  它返回一个字符串,例如:

                  Bundle[{key1=value1, key2=value2, key3=value3}]
                  

                  文档:Bundle.toString()(不幸的是,这是默认的Object.toString() javadoc,因此在这里毫无用处。)

                  【讨论】:

                  • 当我尝试这个时它返回:Bundle[mParcelledData.dataSize=480]
                  猜你喜欢
                  • 2013-08-04
                  • 2018-03-18
                  • 1970-01-01
                  • 2022-05-27
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-06-13
                  • 1970-01-01
                  • 2021-12-17
                  相关资源
                  最近更新 更多