出于调试的原因,我想列出一个Intent的所有附加项(以及它们的值)。现在,拿到钥匙不是问题

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

但是获取键的值对我来说是一个,因为有些值是字符串,有些是布尔值……如何在循环中获取值(遍历键)并将值写入日志文件?谢谢你的提示!


当前回答

我想要一种方法来输出一个意图的内容到日志中,并且能够很容易地读取它,所以我想到了这里。我已经创建了一个LogUtil类,然后使用dumpIntent()方法@Pratik创建,并对其进行了一些修改。这是它的样子:

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());
        }
    }
}

希望这能帮助到一些人!

其他回答

你可以使用for(字符串键:键){对象o = get(键);为了返回一个对象,在它上调用getClass().getName()来获得类型,然后做一组if name.equals("String")类型的事情来计算出你实际上应该调用哪个方法,以获得值?

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());
    }
}

这就是我如何定义实用工具方法来转储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");
    }
}

以下是我用来获取非法(第三方)意图信息的方法:

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是否为空。

一个用于调试模式下评估的Kotlin解决方案:

// list: List<Pair<String!, Any?>>?
val list = intent.extras?.keySet()?.map { it to (intent.extras?.get(it) ?: "null") }

Log.d("list", list.toString();

这将打印捆绑包中所有附加项的列表