4.5.1 Basic Usage of Intent
Category Android Basic Tutorial
Introduction:
After completing the previous section, we have finished learning about the four major components of Android. In this section, we will explore the hub between these components—Intent, the bridge of Android communication. For example, we can use:
>
startActivity (Intent)/startActivityForResult (Intent): to start an Activity
startService (Intent)/bindService (Intent): to start a Service
sendBroadcast: to send a broadcast to a specified BroadcastReceiver
Also, don't forget the Intent-Filter we often write when registering the four major components.
Enough said, let's get started with this section! We have already used Intent before, so we won't go over the conceptual stuff. As usual, here is the official API: Intent
1. Differences between Explicit and Implicit Intents
>
Explicit Intent: Specifies the target component by its name, such as startActivity(new Intent(A.this, B.class)); Only one component is started each time.
Implicit Intent: Does not specify the component name but specifies the Action, Data, or Category of the Intent. When starting a component, it matches the Intent-filter in the AndroidManifest.xml. If more than one component matches, a dialog appears for the user to choose which one to start.
2. Seven Attributes of Intent:
1) ComponentName (Component Name)
2) Action (Action)
3) Category (Category)
4) Data (Data), Type (MIME Type)
5) Extras (Extra)
6) Flags (Flags)
3. Example of Explicit Intent Usage:
This is commonly used, so let's go straight to the examples:
Example 1: Click a button to return to the Home screen: Runtime Effect:
Core Code:
Intent it = new Intent();
it.setAction(Intent.ACTION_MAIN);
it.addCategory(Intent.CATEGORY_HOME);
startActivity(it);
Example 2: Click a button to open the Baidu page: Runtime Effect:
Core Code:
Intent it = new Intent();
it.setAction(Intent.ACTION_VIEW);
it.setData(Uri.parse("http://www.baidu.com"));
startActivity(it);
4. Detailed Explanation of Implicit Intent
1) Example of Implicit Intent with Predefined Action:
Code Example: After clicking the button, all Activities with the VIEW action are filtered out for the user to choose from:
Core Code:
Create the layout for the second Activity and the corresponding Activity. Add the following code to the button click event in the first Activity:
Intent it = new Intent();
it.setAction(Intent.ACTION_VIEW);
startActivity(it);
Finally, add the following code to the Intent of the second Activity:
<activity android:name=".SecondActivity"
android:label="Second Activity">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Runtime Effect:
2) Example of Implicit Intent with Custom Action:
Code Example: Activate another Activity using a custom Action and Category
Core Code:
Create the layout for the second Activity and the corresponding Activity. Add the following code to the button click event in 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:
<activity android:name=".SecondActivity"
android:label="Second Activity">
<intent-filter>
<action android:name="my_action"/>
<category android:name="my_category"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Note that even though we have defined a custom category, we still need to add this default one, otherwise, an error will occur:
<category android:name="android.intent.category.DEFAULT"/>
5. Common System Intent Collection
Here are some common system Intents. If there are any missing, feel free to add them:
//===============================================================
//1. Make a call
// Call mobile customer service 10086
Uri uri = Uri.parse("tel:10086");
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
//===============================================================
//2. Send SMS
// Send a message with 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 SMS 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 browser:
// Open Baidu homepage
Uri uri = Uri.parse("http://www.baidu.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
//===============================================================
//5. Send email: (No Google services, no play!!!!)
// Send an email to [email protected]
Uri uri = Uri.parse("mailto:[email protected]");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(intent);
// Send an email with content "Hello" to [email protected]
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, "[email protected]");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.setType("text/plain");
startActivity(intent);
// Send email to multiple recipients
Intent intent = new Intent(Intent.ACTION_SEND);
String[] tos = {"[email protected]", "[email protected]"}; // To
String[] ccs = {"[email protected]", "[email protected]"}; // CC
String[] bccs = {"[email protected]", "[email protected]"}; // 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 at a location in Beijing, China (latitude 39.9, longitude 116.3)
Uri uri = Uri.parse("geo:39.9,116.3");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
//===============================================================
//7. Route planning
// Route planning: From a location in Beijing (latitude 39.9, longitude 116.3) to a location in Shanghai (latitude 31.2, longitude 121.4)
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 audio files under the SD card and play the first one Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
//===============================================================
//9. Open Camera to Take a Photo: // Open the camera app Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 0); // Retrieve photo data Bundle extras = intent.getExtras(); Bitmap bitmap = (Bitmap) extras.get("data");
// Alternatively: // Call the system camera app and save the captured photo 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 Crop Image // Get and crop image Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); intent.putExtra("crop", "true"); // Enable cropping intent.putExtra("aspectX", 1); // Crop aspect ratio 1:2 intent.putExtra("aspectY", 2); intent.putExtra("outputX", 20); // Saved image width and height 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); // Crop a specific image 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 aspect ratio 1:2 intent.putExtra("outputY", 2); intent.putExtra("aspectX", 20); // Saved image width and height 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 directly to the detailed page of the app Uri uri = Uri.parse("market://details?id=" + "com.demo.app"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
//===============================================================
//12. Enter Phone Settings Interface: // Enter wireless network settings interface (other settings can be deduced by analogy) 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 Contacts Page: Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(People.CONTENT_URI); startActivity(intent);
//===============================================================
//17. View Specific Contact: Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, info.id); // info.id is the contact ID Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(personUri); startActivity(intent);
//===============================================================
//18. Call System to Edit and Add Contact (valid for higher SDK versions):
Intent it = new Intent(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 System to Edit and Add Contact (all versions valid):
Intent intent = new Intent(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);
startActivity(intent);
intent.putExtra(Contacts.Intents.Insert.EMAIL, "[email protected]");
intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE, Contacts.ContactMethodsColumns.TYPE_WORK);
startActivity(intent);
//===============================================================
//20. Open another application
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. Open the recorder
Intent mi = new Intent(Media.RECORD_SOUND_ACTION);
startActivity(mi);
//===============================================================
//22. Search content from Google
Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);
//===============================================================
6. Where to find Actions?
I originally thought about directly pasting the Intent Actions I had collected before, but then I decided against it. It's better to teach you how to fish rather than just giving you the fish. If you have downloaded the Android documentation, you can find it in the following path:
sdk --> docs --> reference --> android --> content --> Intent.html
You can find this file, and the Constants section is where you start:
- 3.4 TouchListener vs OnTouchEvent + Multi-touch
- 3.5 Listening to EditText Content Changes
- 3.6 Responding to System Settings Events (Configuration Class)
- 3.7 AsyncTask Asynchronous Tasks
- 3.8 Gestures
- 4.1.1 Activity Beginner
- 4.1.2 Activity Intermediate
- 4.1.3 Activity Advanced
- 4.2.1 Service Beginner
- 4.2.2 Service Intermediate
- 4.2.3 Service Advanced
- 4.3.1 BroadcastReceiver Beginner
- 4.3.2 BroadcastReceiver Intermediate
- 4.4.1 ContentProvider Beginner
- 4.4.2 ContentProvider Intermediate - Document Provider
- 4.5.1 Basic Usage of Intent
- 4.5.2 Passing Complex Data with Intent
- 5.1 Fragment Overview
- 5.2.1 Fragment Example - Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example - Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example - Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example - Bottom Navigation Bar + ViewPager Page Swiping
- 5.2.5 Fragment Example - Simple Implementation of News (Shopping) App List Fragment
- 6.1 Data Storage and Access - File Storage and Reading
- 6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access - Introduction to SQLite Database
- 6.3.2 Data Storage and Access - Advanced SQLite Database
- 7.1.1 Android Network Programming Essentials and HTTP Protocol Study
- 7.1.2 Android HTTP Request and Response Headers Study
- 7.1.3 Android HTTP Request Method: HttpURLConnection
- 7.1.4 Android HTTP Request Method: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android Calling WebService
- 7.5.1 WebView (Web View) Basic Usage
- 7.5.2 WebView and JavaScript Interaction Basics
- 7.5.3 WebView Considerations After Android 4.4
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Webpage Error Codes
- 7.6.1 Socket Network Basics Preparation
- 7.6.2 TCP Protocol Based Socket Communication (1)
- 7.6.3 TCP Protocol Based Socket Communication (2)
- 7.6.4 UDP Protocol Based Socket Communication
- 8.1.1 13 Drawable Types in Android Summary Part 1
- 8.1.2 13 Drawable Types in Android Summary Part 2
- 8.1.3 13 Drawable Types in Android Summary Part 3
- 8.2.1 Bitmap (Bitmap) Comprehensive Analysis Part 1
- 8.2.2 Bitmap OOM Issues
- 8.3.1 Detailed Explanation of Three Drawing Tools
- 8.3.2 Drawing Tool Practical Examples
- 8.3.3 Paint API - MaskFilter (Mask)
- 8.3.4 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 1)
- 8.3.5 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 2)
- 8.3.6 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 3)
- 8.3.7 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 4)
- 8.3.8 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 5)
- 8.3.9 Paint API - ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API - ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API - ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API - PathEffect (Path Effect)
- 8.3.13 Paint API - Shader (Image Rendering)
- 8.3.14 Paint Enum/Constants and ShadowLayer Shadow Effect
- 8.3.15 Paint API - Typeface (Font Style)
- 8.3.16 Canvas API Detailed Explanation (Part 1)
- 8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection
- 8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Android Animation Collection - Frame Animation
- 8.4.2 Android Animation Collection - Tween Animation
- 8.4.3 Android Animation Collection - Property Animation - Introduction
- 8.4.4 Android Animation Collection - Property Animation - Advanced
- 9.1 Using SoundPool to Play Sound Effects (Duang~)
- 9.2 MediaPlayer for Audio and Video Playback
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord for Audio Recording
- 10.1 TelephonyManager (Phone Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Series (1) – Introduction
- 10.11 Sensor Series (2) – Orientation Sensor
- 10.12 Sensor Series (3) – Accelerometer/Gyroscope Sensor
- 10.12 Sensor Series (4) – Understanding Other Sensors
- 10.14 Introduction to Android GPS
- 11.0 Completion of the 2015 Latest Android Basic Beginner's Tutorial
- 12.1 Android Practice: DrySister Viewing Girls App (Version 1) – Project Setup and Simple Implementation
- 12.2 DrySister Viewing Girls App (Version 1) – 2. Parsing Backend Data
- 12.3 DrySister Viewing Girls App (Version 1) – 3. Image Loading Optimization (Creating a Small Image Cache Framework)
- 12.4 DrySister Viewing Girls App (Version 1) – 4. Adding Data Caching (Introducing SQLite)
- 12.5 DrySister Viewing Girls App (Version 1) – 5. Code Review, Adjustment, and Logging Class Writing
- 12.6 DrySister Viewing Girls App (Version 1) – 6. Icon Creation, Obfuscation, Signing and Packaging, APK Slimming, App Release