Common Intent usage in Android-Part 1 (source code download)

Source: Internet
Author: User

Common Intent usage in Android-Part 1 (source code download)

 

Send SMS

When sending a text message, the action we want to use isIntent.ACTION_SENDTOAnd the URI issmsto:Protocol to ensure that the SMS application receives and processes our intent objects, rather than other applications, so as to accurately send SMS messages. If our action is notIntent.ACTION_SENDTO,Intent.ACTION_SENDAnd is not specifiedsmsto:If the URI of the protocol is used, Android will not start the text message application directly after receiving the intent object, but will pop up the App Chooser. Let's choose which application to start, such as email and QQ, therefore, we should useIntent.ACTION_SENDTOAnd specifysmsto:The URI of the Protocol.

The sample code is as follows:

// Use ACTION_SENDTO instead of ACTION_SENDIntent intent = new Intent (Intent. ACTION_SENDTO); // specify the URI using the smsto: Protocol. The protocol is followed by the object Uri uri = Uri. parse (smsto: 10086); intent. setData (uri); // sets the message body intent. putExtra (sms_body, it's a little tight, please borrow some money ~~); ComponentName componentName = intent. resolveActivity (getPackageManager (); if (componentName! = Null) {startActivity (intent );}

When constructing the URI for sending text messages, the front issmsto:Protocol, followed by the phone number of the recipient receiving the text message. If onlysmsto:If the phone number is not followed, the intent can also start the text message application. However, in this case, after the text message application is started, we also need to manually enter the mobile phone number for receiving information. We use the keysms_bodySet the content of the text message.

Note thatstartActivity(intent)After that, even though the text message application was started, the text message was not directly sent. We need to click to send the message.

Send email

When sending an email, the action we want to use is alsoIntent.ACTION_SENDTOAnd the URI ismailto:Protocol to ensure that the email application receives and processes our intent objects, rather than other applications, so as to accurately send emails. If our action is notIntent.ACTION_SENDTO,Intent.ACTION_SENDAnd is not specifiedmailto:If the URI of the protocol is used, Android will not directly send emails to the App after receiving the intent object, but will pop up the App Chooser. Let's choose which application to start, such as SMS and QQ, therefore, to make sure that the email application is started directly, we should useIntent.ACTION_SENDTOAnd specifymailto:The URI of the Protocol.

The sample code is as follows:

// Use ACTION_SENDTO instead of ACTION_SENDIntent intent = new Intent (Intent. ACTION_SENDTO); // specify the URI using mailto: Protocol, ensure that only the email application can receive this intent object Uri = uri. parse (mailto :); intent. setData (uri); String [] addresses = {zhangsan@126.com, lisi@126.com}; String [] cc = {boss@126.com}; String [] bcc = {girlfriend@126.com}; String subject = overtime; string content = normal work on the National Day ~~; // Set the receiver intent of the email. putExtra (Intent. EXTRA_EMAIL, addresses); // sets the CC intent of the email. putExtra (Intent. EXTRA_CC, cc); // sets the email's BCC intent. putExtra (Intent. EXTRA_BCC, bcc); // sets the mail title intent. putExtra (Intent. EXTRA_SUBJECT, subject); // sets the mail content intent. putExtra (Intent. EXTRA_TEXT, content); // set email attachments // intent. putExtra (Intent. EXTRA_STREAM, Uri. parse (...)); componentName componentName = intent. resolveActivity (getPackageManager (); if (c OmponentName! = Null) {startActivity (intent );}

The email application is started as follows:

We use the keyIntent.EXTRA_EMAIL,Intent.EXTRA_CCAndIntent.EXTRA_BCCSet the recipient, CC, and BCC of the email in sequence. The values are String arrays. We use the key to set the mail title for the extra of Intent. EXTRA_SUBJECT, and the key isIntent.EXTRA_TEXTTo set the mail content. If you want to send an attachment, You can encapsulate the attachment into a Uri, and then use the keyIntent.EXTRA_STREAMSet email attachments.

Note thatstartActivity(intent)After the email application is started, the email is not sent directly. You need to click the send button in the upper right corner to send the email.

Call

To call using Intent, we have two actions available:Intent.ACTION_DIALAndIntent.ACTION_CALLThere are some differences between the two.

If you useIntent.ACTION_DIALAs the intent object action, when you executestartActivity(intent)Then, the call application will be started and the specified mobile phone number will be automatically entered, but the call will not be made automatically. You need to manually press the call button to make a call to the other party.

If you useIntent.ACTION_CALLAs the intent object action, when you executestartActivity(intent)Then, the call application is started and the specified mobile phone number is called directly. You do not need to manually press the call button. However, you must note that this action requires permissions.android.permission.CALL_PHONEIf the permission is not added to the AndroidManifest. xml file of the applicationstartActivity(intent)In this Code, an exception is thrown and the application crashes and exits.

The following is the sample code:

// Intent. ACTION_DIAL: only dial-up, no call // Intent intent = new Intent (Intent. ACTION_DIAL); // Intent. ACTION_CALL calls the specified phone number directly. android is required. permission. CALL_PHONE permission Intent intent = new Intent (Intent. ACTION_CALL); Uri uri = Uri. parse (tel: 10086); intent. setData (uri); ComponentName componentName = intent. resolveActivity (getPackageManager (); if (componentName! = Null) {startActivity (intent );}

In the sample code, we useIntent.ACTION_CALLAs the action of the intent object, and the following permissions are added to AndroidManifest. xml:


  

We usetel:The URI of the protocol, which is followed by the number to be called and uses the Uri as the data of the intent object.

Photograph

To start the camera to take a photo using Intent, we need to set the action value of the intent objectMediaStore.ACTION_IMAGE_CAPTURE. Then we use the keyMediaStore.EXTRA_OUTPUTSet the output path of the image, and callstartActivityForResult()Method to start the camera application and rewrite ouronActivityResult()In this way, you can learn that the photo is complete.

The sample code is as follows:

// Indicates the requestCode private final int REQUEST_CODE_IMAGE_CAPTURE = 1; // The output path of the stored photo for future use of private Uri imageOutputUri = null; // The private void captureImage () {PackageManager pm = getPackageManager (); // first, determine whether the machine has camera capabilities on hardware if (pm. hasSystemFeature (PackageManager. FEATURE_CAMERA) {Intent intent = new Intent (MediaStore. ACTION_IMAGE_CAPTURE); ComponentName componentName = intent. resolveActivity (pm); // judge the operator Whether the camera application is on the machine if (componentName! = Null) {// create an image File to generate the corresponding Uri File imageFile = createImageFile () through Uri. fromFile (); if (imageFile! = Null) {// generate the Uri imageOutputUri = Uri Based on the imageFile. fromFile (imageFile); // use this Uri as the storage path for the photos. Note that once the storage path is set, we cannot get the thumbnail intent. putExtra (MediaStore. EXTRA_OUTPUT, imageOutputUri); // call the startActivityForResult () method to process startActivityForResult (intent, REQUEST_CODE_IMAGE_CAPTURE) in the onActivityResult () method;} else {Toast. makeText (this, the image file cannot be created !, Toast. LENGTH_LONG). show () ;}} else {Toast. makeText (this, the Camera application is not found on the local machine and cannot be taken !, Toast. LENGTH_LONG). show () ;}} else {Toast. makeText (this, the machine does not have a camera and cannot take pictures !, Toast. LENGTH_LONG ). show () ;}// create an image file to use Uri. fromFile () generates the corresponding Uri private File createImageFile () {File image = null; // splice the File name with a timeStamp to prevent the File from being renamed String timeStamp = new SimpleDateFormat (yyyyMMdd_HHmmss ). format (new Date (); String imageFileName = JPEG _ + timeStamp + _; File storageDir = getExternalFilesDir (Environment. DIRECTORY_PICTURES); try {image = File. createTempFile (imageFileName, // prefix. jpg, // suffix st OrageDir // folder);} catch (IOException e) {image = null; e. printStackTrace (); Log. e (DemoLog, e. getMessage ();} return image;} @ Override protected void onActivityResult (int requestCode, int resultCode, Intent intent) {// first, judge whether the request is completed correctly if (resultCode = RESULT_ OK) {switch (requestCode) {case REQUEST_CODE_IMAGE_CAPTURE: // here, we can obtain the image String imagePath = imageOutputUri through imageOutputUri. toString (); Lo G. I (DemoLog, photo path: + imagePath); Toast. makeText (this, photo path: + imagePath, Toast. LENGTH_LONG ). show (); // the following code tries to get the thumbnail // if you set MediaStore. when EXTRA_OUTPUT is used as extra, The intent here is null and you need to determine if (intent! = Null) {Bitmap thumbnail = intent. getParcelableExtra (data); // some mobile phones do not generate thumbnails for the photos. Therefore, if (thumbnail! = Null) {Log. I (DemoLog, get thumbnail) ;}} default: break ;}}}

Let's analyze the above code snippet:

Not all Android devices can take photos, so we callPackageManagerOfhasSystemFeature(PackageManager.FEATURE_CAMERA)Method to Determine whether the current device can take photos at the hardware level.

Then we create an actionMediaStore.ACTION_IMAGE_CAPTUREIntent object.

Then we callintent.resolveActivity(pm)Method to Determine whether the current device has a camera application so that we can start the device. If there is no camera application, but we pass the intent objectstartActivity()OrstartActivityForResult()The application crashes and exits.

We wrotecreateImageFileBy using this method, we create an image file on the peripheral memory card corresponding to our application. Note that this step requiresWRITE_EXTERNAL_STORAGEPermission, which is registered in AndroidManifest. xml as follows:


  

For more information about this permission, see WRITE_EXTERNAL_STORAGE.

We use the image file generated above to generate the corresponding Uri and store it in the imageOutputUri field of the Uri type in the Activity. Then we runintent.putExtra(MediaStore.EXTRA_OUTPUT, imageOutputUri)The Uri is used as the storage path for the photos after being taken.
Note that once the storage path is set, you cannot obtain the thumbnail in onActivityResult.

Finally, we need to call the MethodstartActivityForResult(intent, REQUEST_CODE_IMAGE_CAPTURE)To start the camera app to take a photo, whereREQUEST_CODE_IMAGE_CAPTUREIs the custom requestCode used for photographing.

We OverwriteonActivityResultMethod. First, we need to determineresultCodeWithRESULT_OKEqual. Only equal indicates that the photo was taken successfully.requestCodeEqualREQUEST_CODE_IMAGE_CAPTUREIf they are equal, the result is returned by the photo. In this case, we can use the previously stored imageOutputUri to obtain the photo we just took. Its URI string is as follows:
File: // storage/sdcard0/Android/data/com. ispring. commonintents/files/Pictures/__20150919_112704_533002075.jpg
Note that if we set MediaStore. EXTRA_OUTPUT as the photo output path in step 2onActivityResultYou cannot obtain the Intent returned from the camera application, that is, null. In this way, you cannot obtain the thumbnail. If MediaStore. EXTRA_OUTPUT is not set as the photo output path in step 1, intent is not empty. You can try to executeBitmap thumbnail = intent.getParcelableExtra(data)Obtain the thumbnail. If thumbnail is not empty, the thumbnail is obtained successfully. However, some mobile phones do not generate thumbnails for the pictures they take. Therefore, thumbnail here may be null. Therefore, you must determine before using thumbnail.

Camera

The procedure for starting a camera with Intent is similar to the procedure for starting a camera with Intent. To start Camera for video recording, we need to set the intent valueMediaStore.ACTION_VIDEO_CAPTUREAnd then we use the keyMediaStore.EXTRA_OUTPUTSet the output path of the image, and callstartActivityForResult()Method to start the camera application and rewrite ouronActivityResult()In this way, the video is completed.

The following is the sample code:

// Specifies the requestCode private final int REQUEST_CODE_VIDEO_CAPTURE = 2; // specifies the output path of the stored video so that private Uri videoOutputUri = null is used later; // camera private void captureVideo () {PackageManager pm = getPackageManager (); // first checks whether the local machine has camera capabilities on hardware if (pm. hasSystemFeature (PackageManager. FEATURE_CAMERA) {// set intent action to MediaStore. ACTION_VIDEO_CAPTURE Intent intent = new Intent (MediaStore. ACTION_VIDEO_CAPTURE); ComponentNa Me componentName = intent. resolveActivity (pm); // determines whether there is a camera application on the phone if (componentName! = Null) {// create a video File to generate the corresponding Uri File videoFile = createVideoFile () through Uri. fromFile (); if (videoFile! = Null) {// generate the corresponding Uri videoOutputUri = Uri Based on videoFile. fromFile (videoFile); // uses this Uri as the video storage path intent. putExtra (MediaStore. EXTRA_OUTPUT, videoOutputUri); // call the startActivityForResult () method to process startActivityForResult (intent, REQUEST_CODE_VIDEO_CAPTURE) in the onActivityResult () method;} else {Toast. makeText (this, cannot create video files !, Toast. LENGTH_LONG). show () ;}} else {Toast. makeText (this, the Camera application is not found on the local machine and cannot be photographed !, Toast. LENGTH_LONG). show () ;}} else {Toast. makeText (this, this machine does not have a camera and cannot camera !, Toast. LENGTH_LONG ). show () ;}// creates a video file to facilitate the use of Uri. fromFile () generates the corresponding Uri private File createVideoFile () {File videoFile = null; // concatenate the File name with a timeStamp to prevent the File from being renamed String timeStamp = new SimpleDateFormat (yyyyMMdd_HHmmss ). format (new Date (); String imageFileName = MP4 + timeStamp + _; File storageDir = getExternalFilesDir (Environment. DIRECTORY_MOVIES); try {videoFile = File. createTempFile (imageFileName, // prefix. mp4, // After StorageDir // folder);} catch (IOException e) {videoFile = null; e. printStackTrace (); Log. e (DemoLog, e. getMessage ();} return videoFile;} @ Override protected void onActivityResult (int requestCode, int resultCode, Intent intent) {// first, judge whether the request is completed correctly if (resultCode = RESULT_ OK) {switch (requestCode) {case REQUEST_CODE_VIDEO_CAPTURE: // If MediaStore is set. when EXTRA_OUTPUT is used as extra, // on some mobile phones, intent here is not null, but in some It is null on the mobile phone, // It is not recommended from intent. get the video path from getData (). // we should record videoOutputUri to learn the video path. We do not recommend using the Code Annotated below/* if (intent! = Null) {Uri videoUri = intent. getData (); if (videoUri! = Null) {// path format such as content: // media/external/video/media/130025 Log. I (DemoLog, the video path is: + videoUri. toString () ;}} */String videoPath = videoOutputUri. toString (); // 1. if MediaStore is not set. EXTRA_OUTPUT is used as the video file storage path. The path format is as follows: // The path format is content: // media/external/video/media/130025 // 2. if MediaStore. EXTRA_OUTPUT is used as the video file storage path. The path format is as follows: // The path format is file: // storage/sdcard0/Android/data/com. ispring. commonintents/files/Movies/MP420150919_184132_533002075.mp4 Log. I (DemoLog, video path: + videoPath); Toast. makeText (this, video path: + videoPath, Toast. LENGTH_LONG ). show (); break; default: break ;}}}

You can see that the code for starting the Camera is almost the same as that for the photo code. For more information, see the description of the photo code. In the sample code, we useMediaStore.EXTRA_OUTPUTThe video storage path is set. When taking a photo, we also use it to set the photo output path, but the two are slightly different:
1. For the photo, SetMediaStore.EXTRA_OUTPUTAfter,onActivityResultThe Intent parameter in is null, and the photo storage path cannot be obtained from the Intent.
2. For camera, SetMediaStore.EXTRA_OUTPUTAfter,onActivityResultThe Intent parameter in is null on some mobile phones, but not null on some mobile phones. The intent object obtained by Xiaomi 1 s on my mobile phone is not null, so it is strange here. If intent is not null, you can use intent. getData () obtains the storage path of the video file, but the intent is null or not, so try not to use intent. the getData () method gets its path. Instead, you should store a field in the Activity to save the file path we set previously. This makes it okay.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.