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

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

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


当前回答

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

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

其他回答

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

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

Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
    Log.d("KEY", iterator.next());
}

Pratik的实用方法的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")

}

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

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

基于ruX的答案。

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