出于调试的原因,我想列出一个Intent的所有附加项(以及它们的值)。现在,拿到钥匙不是问题
Set<String> keys = intent.getExtras().keySet();
但是获取键的值对我来说是一个,因为有些值是字符串,有些是布尔值……如何在循环中获取值(遍历键)并将值写入日志文件?谢谢你的提示!
出于调试的原因,我想列出一个Intent的所有附加项(以及它们的值)。现在,拿到钥匙不是问题
Set<String> keys = intent.getExtras().keySet();
但是获取键的值对我来说是一个,因为有些值是字符串,有些是布尔值……如何在循环中获取值(遍历键)并将值写入日志文件?谢谢你的提示!
当前回答
你可以在一行代码中完成:
Log.d("intent URI", intent.toUri(0));
它输出如下内容:
“#意图;行动= android.intent.action.MAIN;类别= android.intent.category.LAUNCHER; launchFlags = 0 x10a00000;组件= com.mydomain.myapp / .StartActivity; sourceBounds = 12% 20870% 20276% 201167;l.profile = 0;端”
在这个字符串的末尾(我加粗的部分),您可以找到额外的列表(在这个示例中只有一个额外的)。
这是根据toUri文档: URI包含了作为基本URI的意图数据,以及描述动作、类别、类型、标志、包、组件和额外内容的额外片段。
其他回答
我想要一种方法来输出一个意图的内容到日志中,并且能够很容易地读取它,所以我想到了这里。我已经创建了一个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());
}
}
}
希望这能帮助到一些人!
Bundle的get(String key)方法返回一个对象。最好的方法是旋转键集,在每个键上调用get(String),并在对象上使用toString()来输出它们。这对于基本类型最有效,但是对于没有实现toString()的对象,可能会遇到问题。
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")
}
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");
}
}