列出一个Intent的所有附加项

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

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

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

142713 次浏览

Bundle的get(String key)方法返回一个对象。最好的方法是旋转键集,在每个键上调用get(String),并在对象上使用toString()来输出它们。这对于基本类型最有效,但是对于没有实现toString()的对象,可能会遇到问题。

你可以使用for (String key : keys) { Object o = get(key);返回一个对象,在它上面调用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());
}
}

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

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

如果这太啰嗦或太迟,我很抱歉,但这是我能找到的完成工作的唯一方法。最复杂的因素是java没有传递引用函数,因此get——Extra方法需要返回一个默认值,并且不能修改布尔值来判断是否偶然返回了默认值,还是因为结果不好。出于这个目的,让方法引发一个异常要比让它返回一个默认值更好。

我在这里找到了我的信息:Android意图文档

    //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 . sh Set Documentation . sh

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

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

如果为了调试你想要的只是一个字符串(某种程度上由OP暗示,但没有显式声明),只需在额外的Bundle上使用toString:

intent.getExtras().toString()

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

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

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

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

我想要一种方法来输出一个意图的内容到日志中,并且能够很容易地读取它,所以我想到了这里。我已经创建了一个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());
}
}
}

希望这能帮助到一些人!

我注意到在Android源代码中,几乎每个操作都迫使Bundle解包它的数据。因此,如果(像我一样)你需要经常这样做以调试目的,下面是非常快速的输入:

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

你可以在一行代码中完成:

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的意图数据,以及描述动作、类别、类型、标志、包、组件和额外内容的额外片段。< / p >

Kotlin版本的Pratik的效用法,它转储一个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解决方案:

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


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

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

将它作为一个字符串,用","在芬兰湾的科特林!

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

基于ruX的答案。