Intent idiom _android in Android

Source: Internet
Author: User
Tags getmessage

Intent in Android is a very important class, and if you're not particularly knowledgeable about intent, see "How to use intent in Android." If you are not particularly familiar with intent filter, see "Detailed Android Intent object and Intent filter filter matching process."

This article focuses on some of the common intent usages of Android, such as how to send text messages through intent, send emails, launch video cameras, set up alarms, open WiFi settings, and so on.

Limited to space, this article is divided into two chapters, this is the last chapter.

Send SMS

When sending text messages, the ACTION we want to use is intent.action_sendto, and to specify that its URI is Smsto: protocol, which ensures that SMS applications receive and process our intent objects, not other applications. So as to realize the purpose of sending text messages accurately. If our ACTION is not intent.action_sendto, but Intent.action_send and does not specify Smsto: The URI of the protocol, then Android will not start the SMS application directly after receiving the intent object, Instead of popping up app Chooser, let's choose which apps to start, such as emails, QQ, and so on, so in order to ensure that we start the SMS application directly, we should use Intent.action_sendto and specify the Smsto: The URI of the Protocol.

The sample code is as follows:

Use Action_sendto instead of action_send
Intent Intent = new Intent (intent.action_sendto);
Specifies that the URI uses the Smsto: protocol, followed by the object URI URI of the receiving SMS
= Uri.parse ("smsto:10086");
Intent.setdata (URI);
Set the message body
Intent.putextra ("Sms_body", "a little tight, borrow some money ~ ~");

ComponentName componentname = intent.resolveactivity (Getpackagemanager ());
if (componentname!= null) {
 startactivity (intent);
}

When constructing a URI that sends a text message, the front is smsto: protocol, followed by the receiver's cell phone number. If you are building a URI, only write Smsto: without writing the phone number of the following, then the intent can also successfully start the SMS application, but in this case, after the launch of the SMS application, we also need to manually enter the phone number to receive information. We set the content of the SMS through key for Sms_body extra.

Note that, after the implementation of the StartActivity (intent), although the SMS application started, but the message did not send directly, we need to click to send a message can.

Send mail

When sending the message, the ACTION we want to use is also intent.action_sendto, and to specify that its URI is mailto: protocol, which ensures that the mail application receives and processes our intent objects, not other applications receive So as to realize the purpose of sending the message exactly. If our ACTION is not intent.action_sendto, but intent.action_send, and does not specify the mailto: the URI of the protocol, then Android will not directly mail the application after receiving the intent object. Instead of popping up app Chooser, let's choose which apps to start, such as SMS, QQ, and so on, so to make sure that we start the mail application directly, we should use Intent.action_sendto and specify the mailto: the URI of the Protocol.

The sample code is as follows:

Use Action_sendto instead of action_send
Intent Intent = new Intent (intent.action_sendto);
Specifies that the URI uses the mailto: protocol to ensure that only the mail 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 = "National Day normal work ~ ~";
Set the recipient
Intent.putextra (Intent.extra_email, addresses) of the message;
Set the CC side
Intent.putextra (INTENT.EXTRA_CC, CC) of the message;
Set the message's Bcc
Intent.putextra (INTENT.EXTRA_BCC, BCC);
Set message headers
Intent.putextra (Intent.extra_subject, SUBJECT);
Set the message content
Intent.putextra (intent.extra_text, content);
Set up mail attachment
//intent.putextra (Intent.extra_stream, Uri.parse (...));
ComponentName componentname = intent.resolveactivity (Getpackagemanager ());
if (componentname!= null) {
 startactivity (intent);
}

The screenshot that starts the mail application looks like this:

We set the recipient, Cc, and Bcc of the message by key for Intent.extra_email, INTENT.EXTRA_CC, and INTENT.EXTRA_BCC respectively, and the values are string arrays. We set the message title by key for Intent.extra_subject EXTRA, and set the message content by key for Intent.extra_text EXTRA. If you want to send an attachment, you can encapsulate the attachment in the form of a URI and then set the message attachment through the key for Intent.extra_stream EXTRA.

Note that after the execution of startactivity (intent), although the mail application started open, but the mail is not sent directly, we need to click on the top right hand button to send the message.

Call

To make a call through Intent, we have two Action:Intent.ACTION_DIAL and intent.action_call to use, and there is a certain difference.

If you use Intent.action_dial as an ACTION for a intent object, then when you execute startactivity (intent), you start the call application and automatically enter the specified cell number, but not automatically. We need to manually press the Dial button to actually call each other.

If you use Intent.action_call as an ACTION for the intent object, then when you execute startactivity (intent), you start the phone application and call the phone number we specify without having to manually press the Dial button. Note, however, that the action requires permission Android.permission.CALL_PHONE, and if the permission is not added in the applied androidmanifest.xml file, then when the startactivity is specified ( Intent) This code, will throw an exception, application crash exit.

Here is the sample code:

Intent.action_dial only dials, does not call
//intent Intent = new Intent (intent.action_dial);
Intent.action_call directly dial the specified phone, need Android.permission.CALL_PHONE permissions
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 example code, we used Intent.action_call as the ACTION for the intent object and added the following permissions in Androidmanifest.xml:

Copy Code code as follows:
<uses-permission android:name= "Android.permission.CALL_PHONE" ></uses-permission>

We use Tel: the URI of the Protocol, the number to dial after the protocol, and the URI as the data for the intent object.

Photo

To start the camera with intent, we need to set the action value of the intent object to the Mediastore.action_image_capture action. Then we set the output path of the picture with key for Mediastore.extra_output EXTRA, finally call the Startactivityforresult () method to start the camera application and rewrite our Onactivityresult ( In order to know that the camera is complete in this method.

The sample code is as follows:

Represents the Requestcode private final int request_code_image_capture = 1 for photographing;

 We store the output path of the photo so that subsequent use of the private Uri Imageoutputuri = null;

 Photo private void Captureimage () {Packagemanager pm = Getpackagemanager (); First determine if the machine has camera capability on the hardware if (Pm.hassystemfeature (Packagemanager.feature_camera)) {Intent Intent = new Intent (
 Mediastore.action_image_capture);
 ComponentName componentname = intent.resolveactivity (PM);
 Determine if there is a camera on the phone apply if (componentname!= null) {//Create a picture file so that the corresponding URI file ImageFile = Createimagefile () is generated via Uri.fromfile ();
  if (imagefile!= null) {//The corresponding Uri is generated according to imagefile Imageoutputuri = Uri.fromfile (ImageFile);
  Using this URI as the storage path after the photo is taken, note that once the storage path is set, we cannot get the thumbnail Intent.putextra (mediastore.extra_output, Imageoutputuri); Call the Startactivityforresult () method so that the Onactivityresult () method is handled appropriately startactivityforresult (intent, Request_code_image_
 CAPTURE); }else{Toast.maketext (This, "Cannot create an image file!")
 ", Toast.length_long). Show (); }else{Toast.maketext (This, "not found camera application in this machine, can't take photos!") ", Toast.length_lonG). Show ();
 }else{Toast.maketext (This, "No camera on this machine, no photo!", Toast.length_long). Show ();

 }//Create a picture file so that the corresponding URI private file Createimagefile () {file image = null is generated via Uri.fromfile ();
 Use timestamp to splice file names to prevent duplicate file name 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 Storagedir//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 to determine if the if is completed correctly (RESULTC  Ode = = RESULT_OK) {switch (requestcode) {case request_code_image_capture://Here, we can get the picture String we want by Imageoutputuri
  ImagePath = Imageoutputuri.tostring ();
  LOG.I ("Demolog", "Photo path is:" + ImagePath); Toast.maketext (This, "Photo path is:" + ImagePath, toAst.

  Length_long). Show (); The following code attempts to get the thumbnail//if setting Mediastore.extra_output as EXTRA, the intent here is null and needs to be judged if (intent!= null) {Bitmap = i
  Ntent.getparcelableextra ("Data");
  Some mobile phones do not give pictures of the picture generated thumbnails, so here also to determine if (thumbnail!= null) {LOG.I ("Demolog", "get Thumbnails");
 }} Default:break;

 }
 }
 }

Let's analyze the code snippet above:

Not all Android devices can take pictures, so first we call the Packagemanager hassystemfeature (Packagemanager.feature_camera) method, Determine whether the current device has the ability to take photos at the hardware level.

Then we created a intent object with ACTION as Mediastore.action_image_capture.

We then call the Intent.resolveactivity (PM) method to determine whether the current device has a camera application so we can start. If there is no camera application but we pass the intent object to StartActivity () or Startactivityforresult (), the exception is thrown and the application crashes out.

We wrote a Createimagefile method ourselves, by which we created a picture file on the peripheral memory card corresponding to our application. It should be noted that this step requires Write_external_storage permissions and is registered as follows in Androidmanifest.xml:

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"
 android:maxsdkversion= ">" </uses-permission>

We generated the corresponding URI using the image file generated above and stored it in the field Imageoutputuri in the activity type URI, after which we executed the Intent.putextra (Mediastore.extra_output, Imageoutputuri), using the URI as the storage path for the photo after the camera is completed.
The special note here is that once the storage path is set, we cannot get the thumbnail in Onactivityresult ().

Finally we need to call the method Startactivityforresult (intent, request_code_image_capture) to start the camera application to take photos, where Request_code_image_ Capture is our custom designated Requestcode for photographing.

We have overridden the Onactivityresult method, which triggers the execution of the method after the photo is completed. First we have to determine whether the ResultCode is equal to the RESULT_OK, only equal to indicate the success of the photo, and then we judge if the Requestcode equals request_code_image_capture, if the equality indicates the result of the photo return. So at this point, we can get the photo we just finished with the Imageoutputuri we stored before, and its URI string is as follows:
file:///storage/sdcard0/Android/data/com.ispring.commonintents/files/Pictures/JPEG_20150919_112704_533002075.jpg
Note that if we set mediastore.extra_output as the photo output path in step 5th, then we cannot get the intent from the camera application in Onactivityresult, which is null, This will not get the thumbnail. Conversely, if the 5th step is not set mediastore.extra_output as a photo output path, intent is not empty, you can try to execute bitmap thumbnail = Intent.getparcelableextra ("Data ") gets the thumbnail, and if thumbnail is not empty, the thumbnail can be obtained successfully. But some phones do not give pictures of the picture generated thumbnails, so the thumbnail here may also be null, so before using to judge.

Camera

The steps for photographing with the intent boot camera are very similar to the steps just mentioned above for taking photos through the intent boot camera, slightly different. To start the camera for camera, we need to set the intent value to Mediastore.action_video_capture ACTION, and then we use key for Mediastore.extra_ The output path of the extra is set, and the Startactivityforresult () method is finally invoked to start the camera application and rewrite our Onactivityresult () to know that the camera is complete in this method.

Here is the sample code:

Represents the Requestcode private final int request_code_video_capture = 2 for video recording;

 We store the output path of the video so that subsequent use of the private Uri Videooutputuri = null;

 Camera private void Capturevideo () {Packagemanager pm = Getpackagemanager (); First determine if the machine has camera capability on the hardware if (Pm.hassystemfeature (Packagemanager.feature_camera)) {//Intent ACTION set to Mediastore.action_
 Video_capture Intent Intent = new Intent (mediastore.action_video_capture);
 ComponentName componentname = intent.resolveactivity (PM);
 Determine if there is a camera on the phone apply if (componentname!= null) {//create video file so that the corresponding URI file Videofile = Createvideofile () is generated via Uri.fromfile ();
  if (videofile!= null) {//The corresponding Uri is generated according to videofile Videooutputuri = Uri.fromfile (videofile);
  The Intent.putextra (Mediastore.extra_output, Videooutputuri) is used as the memory path of the video after the camera is completed. Call the Startactivityforresult () method so that the Onactivityresult () method is handled appropriately startactivityforresult (intent, Request_code_video_
 CAPTURE); }else{Toast.maketext (This, "Cannot create a video file!")
 ", Toast.length_long). Show (); }else{Toast.maketext (This, "not found on this machine cameRA application, no camera!
 ", Toast.length_long). Show ();
 }else{Toast.maketext (This, "No camera on this machine, no camera!", Toast.length_long). Show ();

 }//Create a video file so that the corresponding URI private file Createvideofile () {file Videofile = null is generated via Uri.fromfile ();
 Use timestamp to splice file names to prevent duplicate file name 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",//suffix 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 to determine if the if is completed correctly (RESULTC Ode = = RESULT_OK) {switch (requestcode) {case Request_code_video_capture://If Mediastore.extra_output is set as EXTRA,/ /On some phones, the intent here is not NULL, but it is null on some phones,//So it is not recommended to get the video path from Intent.getdata ()///We should record the vid ourselves.Eooutputuri to know the video path, the following annotated code does not recommend the use of/*if (intent!= null) {Uri Videouri = Intent.getdata (); if (Videouri!= null) {//path format such as content://media/external/video/media/130025 log.i ("Demolog", "Video path is:" + Videouri.tostrin
  g ());
  }}*/String Videopath = videooutputuri.tostring (); 1. If you do not set Mediastore.extra_output as the video file storage path, the path format is as follows://path format such as content://media/external/video/media/130025//2. If you set the Mediastore.extra_output as the video file storage path, the path format looks like this://path format such as file:///storage/sdcard0/Android/data/
  Com.ispring.commonintents/files/movies/mp420150919_184132_533002075.mp4 log.i ("DemoLog", "Video path is:" + VideoPath);
  Toast.maketext (This, "Video path is:" + Videopath, Toast.length_long). Show ();
 Break
 Default:break;

 }
 }
 }

You can see that the code that starts the camera camera is almost exactly the same as the code for the photo shoot, which is explained in detail in the description of the camera code. In the example code, we set the video store path through Mediastore.extra_output, and we also set the image's output path through it, but the two are slightly different:

    • 1. For photographs, after setting the Mediastore.extra_output, the intent parameter in Onactivityresult is null and cannot be learned from the intent of the stored path of the photograph.
    • 2. For the camera, set the Mediastore.extra_output, the Onactivityresult in the intent parameter on some mobile phone is null, but on some mobile phone is not NULL, My cell phone millet 1s get the intent object is not NULL, so here is very strange. If intent is not NULL, you can get the storage path to the video file through Intent.getdata (), but because intent is null-indeterminate, try not to get its path through the Intent.getdata () method. Instead, you should store a field in the activity to save the file path that we set up before, so that's fine.

The above is about the common intent usage of Android, hope to be helpful to everybody's study.

Source code: "Intent usage in Android "

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.