Intent.setData VS Intent.putExtrasetData、Intent、putExtra、VS

2023-09-06 15:05:27 作者:爱已错别成往事*

我想按照这个教程:

http://www.vogella.com/articles/AndroidCalendar/article.html

我明白putExtra确实

I understand what putExtra does

但我不明白使用setData()意味着什么?

but I fail to understand what setData() means?

Android的文档,是没有多少帮助的:

Android Docs, wasn't much helpful:

设置此意图是经营上的数据。

这是什么意思为恒

intent.setData(CalendarContract.Events.CONTENT_URI);

目前似乎没有任何影响,当我注释掉此行。

There doesn't seem to be any affect when I comment out this line.

推荐答案

使用setData()用于指向一个数据的位置对象(例如像一个文件),而 putExtra()添加简单数据类型(如SMS文本字符串,例如)。

setData() is used to point to the location of a data object (like a file for example), while putExtra() adds simple data types (such as an SMS text string for example).

下面是两个例子来阐明:

Here are two examples to clarify:

使用setData()来设置要共享的文件的位置。

setData() used here to set the location of a file that you want to share.

File fileToShare = new File("/sdcard/somefile.dat");
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.setData(Uri.fromFile(fileToShare));
startActivity(i);

putExtra()来设置你想要共享的文本内容。

putExtra() used here to set the text content that you want to share.

Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
string textBodyString = "some text";
i.putExtra(Intent.EXTRA_TEXT, textBodyString);
i.setType(HTTP.PLAIN_TEXT_TYPE);

有关更多信息,我建议一些阅读有关意图和使用setData()的setType() setDataAndType()

For more information I suggest some reading about Intents and the setData(), setType() and setDataAndType()