Easy Tutorial
❮ Verilog2 Tf Hadoop Tutorial ❯

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:

>

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

>


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:

WeChat Subscription

❮ Verilog2 Tf Hadoop Tutorial ❯