Intent.setData vs Intent.putExtra

2019-01-18 02:10发布

I'm trying to follow this tutorial:

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

I understand what putExtra does

but I fail to understand what setData() means?

Android Docs, wasn't much helpful:

Set the data this intent is operating on.

what does this mean for the constant

intent.setData(CalendarContract.Events.CONTENT_URI); ?

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

4条回答
聊天终结者
2楼-- · 2019-01-18 02:32

setData() is used for the Android System to find an application component that matches the data attribute in implicit intent.


putExtra() is mainly used to pass some information to the selected application component,by the Android system.

查看更多
女痞
3楼-- · 2019-01-18 02:35

I think that .putExtra is to transfer a string or something. like Aramex :P

while .setData is to set the intent's data type.

see in the intent it's Intent.ACTION_INSERT. So it's waiting for something to be inserted. That's why you set the data. .setData(CalendarContract.Events.CONTENT_URI); You inserted the calendar events.

查看更多
时光不老,我们不散
4楼-- · 2019-01-18 02:40

I've found a good answer here: https://google-developer-training.gitbooks.io/android-developer-fundamentals-course-concepts/content/en/Unit%201/21_c_understanding_activities_and_intents.html

Use the intent data field (Intent.setData): - When you only have one piece of information you need to send to the started activity. - When that information is a data location that can be represented by a URI.

Use the intent extras (Intent.putExtra): - If you want to pass more than one piece of information to the started activity. - If any of the information you want to pass is not expressible by a URI.

Intent data and extras are not exclusive; you can use data for a URI and extras for any additional information the started activity needs to process the data in that URI.

查看更多
该账号已被封号
5楼-- · 2019-01-18 02:52

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

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

查看更多
登录 后发表回答