Basic usage of Intent
Introduction to this section:
After the end of the previous section, it means that we have finished studying the four major components of Android~, and what we want to learn in this section is the relationship between the four major components Hub - Intent (intent), the bridge of Android communication, for example, we can pass:
- startActivity(Intent)/startActivityForResult(Intent ): to start an Activity
- startService(Intent)/bindService(Intent): to start a Service
- sendBroadcast: Send broadcast to the specified BroadcastReceiver
- Also don’t forget that we wrote a lot when registering the four major componentsIntent-FilterOh~
Okay, without further ado, let’s start this section! In addition, we have already used Intent before, so we won’t talk about conceptual things~ Old rules, official API: Intent
1. The difference between explicit Intent and implicit Intent
- Explicit Intent: Specify the target component to start through the component name, such as startActivity(new Intent(A.this,B.class)); There is only one component started each time~
- Implicit explicit Intent: Do not specify the component name, but specify the Action, Data, or Category of the Intent. When we start the component, It will match the Intent-filter of the relevant components in AndroidManifest.xml and match the components that meet the attributes one by one. When more than one meets the requirements, A dialog box will pop up allowing us to choose which one to start~
2. The seven properties of Intent:
1) ComponentName (component name )
2)Action
3)Category
4) Data (data), Type (MIME type)
5) Extras (Extra)
6) Flags(mark)
3.Explicit Intent Usage example:
This is used a lot, so let’s go straight to the example:
Example 1: Click the button to return to the Home interface: Running rendering:
Core code:
it.setAction(Intent.ACTION_MAIN);
it.addCategory(Intent.CATEGORY_HOME);
startActivity(it);
Example 2: Click the button to open the Baidu page: Running rendering:
##Core code:
it.setData(Uri.parse( "http://www.baidu.com"));
startActivity(it);
4. Detailed explanation of implicit Intent
1) Implicit Intent example of predefined actions:
Code example:After clicking the button, all Activities whose Action is VIEW are filtered out and selected by the user Further selection:
Core code:
Create the layout of the second Activity, and the corresponding Activity, add the code in the button click event of the first Activity :startActivity(it);
< # </intent-filter>
2) Implicit Intent example of custom action:
Core code:
Establish the layout of the second Activity, and the corresponding Activity, add the code in the button click event of the first Activity:Intent it = new Intent();it.setAction("my_action");
it.addCategory("my_category");startActivity(it);
Finally add the following code to the Intent of the second Activity:
android:label="Second Activity"> ;
<intent-filter>
name="android.intent.category.DEFAULT"/>
But you still need to add this default, otherwise an error will be reported:
<category android:name="android.intent.category.DEFAULT"/>
5. Collection of commonly used system Intents
Please post a collection of commonly used system Intents. If there are any that are not listed above, please suggest them~
//1. Call
// Call mobile customer service 10086
Uri uri = Uri.parse ("tel:10086");
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
//========== ================================================== ===
//2. Send a text message
// Send a text message with the content "Hello" to 10086
Uri uri = Uri.parse("smsto:10086");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Hello");
startActivity(intent);
//3. Send MMS ( Equivalent to sending a text message with attachments)
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("sms_body", "Hello");
Uri uri = Uri.parse("content ://media/external/images/media/23");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/png");
startActivity(intent) ;
//============================================ ======================
//4. Open the browser:
//Open Baidu homepage
Uri uri = Uri.parse("http://www.baidu.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
//= ================================================== ============
//5. Send an email: (It’s useless to castrate Google services!!!)
// Send to someone@domain.com Mail
Uri uri = Uri.parse("mailto:someone@domain.com");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(intent);
/ / Send an email to someone@domain.com Send an email with the content "Hello"
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, "someone@domain.com") ;
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.setType("text/plain");
startActivity(intent);
//Send emails to multiple people
Intent intent=new Intent(Intent.ACTION_SEND);
String[] tos = {"1@abc.com", "2@abc .com"}; // Recipient
String[] ccs = {"3@abc.com", "4@abc.com"}; // Cc
String[] bccs = {" 5@abc.com", "6@abc.com"}; // Bcc
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_BCC, bccs);
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.setType("message/rfc822");
startActivity(intent);
//======================== ========================================
//6. Display map:
// Open Google Maps Beijing, China location (39.9 north latitude, 116.3 east longitude)
Uri uri = Uri.parse("geo:39.9,116.3");
Intent intent = new Intent(Intent .ACTION_VIEW, uri);
startActivity(intent);
//============================ ===================================
//7. Path planning
// Path planning: from somewhere in Beijing (39.9 north latitude, 116.3 east longitude) to a place in Shanghai (31.2 north latitude, 121.4 east longitude)
Uri uri = Uri.parse("http://maps.google.com/maps? f=d&saddr=39.9 116.3&daddr=31.2 121.4");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
//===== ================================================== ========
//8. Multimedia playback:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:// /sdcard/foo.mp3");
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
//Get all the audio files in the SD card, and then Play the first song =-=
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity (intent);
//====================================== =========================
//9. Open the camera to take pictures:
//Open the photo program
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
// Get photo data
Bundle extras = intent.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
//Another one:
//Call the system camera application and store the photos taken
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
time = Calendar.getInstance().getTimeInMillis();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
.getExternalStorageDirectory().getAbsolutePath()+"/ tucue", time + ".jpg")));
startActivityForResult(intent, ACTIVITY_GET_CAMERA_IMAGE);
//==================== ============================================
//10. Get and cut pictures
// Get and cut pictures
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true"); // Turn on cropping
intent.putExtra("aspectX", 1); // The aspect ratio of cropping is 1:2
intent.putExtra ("aspectY", 2);
intent.putExtra("outputX", 20); // Save the width and height of the image
intent.putExtra("outputY", 40);
intent.putExtra("output", Uri.fromFile(new File ("/mnt/sdcard/temp"))); // Save path
intent.putExtra("outputFormat", "JPEG"); // Return format
startActivityForResult(intent, 0);
// Cut a specific picture
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera. CropImage");
intent.setData(Uri.fromFile(new File("/mnt/sdcard/temp")));
intent.putExtra("outputX", 1); // Crop width The height ratio is 1:2
intent.putExtra("outputY", 2);
intent.putExtra("aspectX", 20); // Save the width and height of the image
intent.putExtra(" aspectY", 40);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", Uri.parse(" file:///mnt/sdcard/temp"));
startActivityForResult(intent, 0);
//================== =============================================
//11. Open Google Market
// Open Google Market and directly enter the detailed page of the program
Uri uri = Uri.parse("market://details?id=" + "com.demo.app ");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
//================ ================================================
//12. Enter the mobile phone settings interface:
// Enter the wireless network settings interface (others can draw inferences)
Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
startActivityForResult (intent, 0);
//==================================== ===========================
//13. Install apk:
Uri installUri = Uri.fromParts( "package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
//================ ===============================================
//14. Uninstall apk:
Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity( it);
//======================================== ========================
//15.Send attachment:
Intent it = new Intent(Intent.ACTION_SEND) ;
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/eoe.mp3");
sendIntent.setType("audio /mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));
//================== =============================================
//16. Enter the contact page:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(People.CONTENT_URI);
startActivity( intent);
//========================================== ========================
//17. View the specified contact person:
Uri personUri = ContentUris. withAppendedId(People.CONTENT_URI, info.id);//info.id contact ID
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(personUri );
startActivity(intent);
//================================== ===============================
//18. Call the system editor to add contacts (higher version SDK valid):
Intent it = newIntent(Intent.ACTION_INSERT_OR_EDIT);
it.setType("vnd.android.cursor.item/contact");
//it.setType(Contacts.CONTENT_ITEM_TYPE) ;
it.putExtra("name","myName");
it.putExtra(android.provider.Contacts.Intents.Insert.COMPANY, "organization");
it.putExtra(android. provider.Contacts.Intents.Insert.EMAIL,"email");
it.putExtra(android.provider.Contacts.Intents.Insert.PHONE,"homePhone");
it.putExtra(android.provider. Contacts.Intents.Insert.SECONDARY_PHONE,"mobilePhone");
it.putExtra( android.provider.Contacts.Intents.Insert.TERTIARY_PHONE,"workPhone");
it.putExtra(android.provider.Contacts. Intents.Insert.JOB_TITLE,"title");
startActivity(it);
//======================== ========================================
//19. Call the system editor to add contacts (all valid):
Intent intent = newIntent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(People.CONTENT_ITEM_TYPE);
intent.putExtra(Contacts.Intents.Insert.NAME , "My Name");
intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890");
intent.putExtra(Contacts.Intents.Insert.PHONE_TYPE,Contacts.PhonesColumns.TYPE_MOBILE);
intent.putExtra(Contacts.Intents.Insert.EMAIL, "com@com.com");
intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE, Contacts.ContactMethodsColumns.TYPE_WORK);
startActivity(intent);
//===============================================================
//20.打开另一程序
Intent i = new Intent();
ComponentName cn = new ComponentName("com.example.jay.test",
"com.example.jay.test.MainActivity");
i.setComponent(cn);
i.setAction("android.intent.action.MAIN");
startActivityForResult(i, RESULT_OK);
//===============================================================
//21.打开录音机
Intent mi = new Intent(Media.RECORD_SOUND_ACTION);
startActivity(mi);
//===============================================================
//22.从google搜索内容
Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);
//===============================================================
6.Action在哪里查?
本来想直接贴以前收集到的Intent Action的,后来想想还是算了,授之以鱼,还不如授之以渔, 如果你下载了Android的文档的话,可以在下述路径:
sdk-->docs-->reference-->android--->content--->Intent.html
找到这个玩意,然后从这个Constants开始就是了:
遇到陌生的自己来这里查即可~
本节小结:
好的,关于Intent的基本使用就到这里,下一节我们会来继续学习在日常开发中使用Intent可能会遇到 的一些问题或者说需求吧,敬请期待,谢谢~