出于调试的原因,我想列出一个Intent的所有附加项(以及它们的值)。现在,拿到钥匙不是问题
Set<String> keys = intent.getExtras().keySet();
但是获取键的值对我来说是一个,因为有些值是字符串,有些是布尔值……如何在循环中获取值(遍历键)并将值写入日志文件?谢谢你的提示!
出于调试的原因,我想列出一个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是否为空。
其他回答
如果为了调试,你想要的只是一个字符串(OP暗示了,但没有显式声明),只需在额外的Bundle上使用toString:
intent.getExtras().toString()
它返回一个字符串,例如:
Bundle[{key1=value1, key2=value2, key3=value3}]
Bundle.toString()(不幸的是,它是默认的Object.toString() javadoc,因此在这里非常无用。)
我想要一种方法来输出一个意图的内容到日志中,并且能够很容易地读取它,所以我想到了这里。我已经创建了一个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());
}
}
}
希望这能帮助到一些人!
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());
}
}
Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
Log.d("KEY", iterator.next());
}
我注意到在Android源代码中,几乎每个操作都迫使Bundle解包它的数据。因此,如果(像我一样)你需要经常这样做以调试目的,下面是非常快速的输入:
Bundle extras = getIntent().getExtras();
extras.isEmpty(); // unparcel
System.out.println(extras);