Android Intent Tutorials

Source: Internet
Author: User
Tags case statement constant definition switch case home screen

Original: Android:intents Tutorial
Darryl Bayliss
Translator: Kmyhy

People don't wander aimlessly, and most of the things they do--like watching TV, shopping, writing the next killer app----have a specific purpose or intent, namely intent.

Android is the same. Before an app does something, it needs to know the purpose or intent of the thing before it can do the whole thing correctly.
This shows that people are not different from Android.
In this article, you will use Intent to create a memes software (a spoof of the picture-making software, very popular abroad, you can use this software to simple PS later black people or entertain themselves). With this demo, you can learn:

    • Intent is what it is, and it's widely used in Android.
    • How to create and retrieve content from other apps using Intent and use them in your app.
    • How to receive and respond to a Intent that is sent from a different app.

If you are a novice, it is highly recommended that you read the Android Tutorial for Beginners tutorial to learn the most basic tools and concepts.

Get ready for a photo of memes. This tutorial will elevate your Android development skills to 9000 + +!

Begin

Download the start item from here.

In the start project, you'll find XML layouts and related activities, some modeled code, helper classes for stretching bitmaps, and some of the resources that will be used later, such as Drawable and String.

If you have already opened Android Studio, click File\import Project and select the top-level directory of the START project you downloaded. Otherwise, open Android Studio and select Open an existing Android studio project from the Welcome screen, and select the top-level directory to start the project.

Take the time to browse to the start project. Takepictureactivity contains a ImageView, click it to turn on the device camera. When you click LETS memeify!, you pass the file path of the bitmap in ImageView to Entertextactivity, and the real fun in the activity begins, You can enter a piece of spoof text here and convert your photo to the next viral memes!

Create the first Intent

Run the app. You will see:

Now there is no function, if you follow the prompts to do and click ImageView, nothing will happen!

You'll add some code to make things interesting.

Open Takepictureactivity.java Add a constant definition to the class:

privatestaticfinalint1;

This constant is used to uniquely identify your intent--back when you know it.

Note: This article assumes that you will solve the class without introducing a warning and does not need to specifically explain the need to introduce a class. Simply note that if you forget to introduce a class, you can put your mouse on a class that prompts the class not to introduce a warning, and then press ALT + ENTER to import it.

Add the necessary import statements yourself by adding the following code under the OnClick () method:

privatevoidtakePictureWithCamera() {  // 创建一个 intent 用于从摄像头拍照  new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  File photoFile = createImageFile();  selectedPhotoPath = Uri.parse(photoFile.getAbsolutePath());  captureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));  startActivityForResult(captureIntent, TAKE_PHOTO_REQUEST_CODE);}

This method has a bit more code, so it's a few steps into adding code.
The first line declares a Intent object. It's easy to say, but what does that mean?

A Intent is an abstraction of a task or function that will be executed by the app at some point in the future. Simply put, it tells you what the app needs to do. The most basic intent consists of a few parts:

    • Actions: This is what intent needs to do, such as dialing a phone number, opening a URL, and editing some data. An action is a simple string constant that describes what should be done.
    • Data: The resource that intent needs to use. In Android it is represented by a URI (unique resource identifier) or URI object. The data type needs to change according to action. For example, in a phone intent, you can't make a picture of a phone number?

By combining action and data, Android will be able to know what this intent is and what it does with it.
It's that simple!

Back to the Takepicturewithcamera () method, we used action_image_capture as the intent ACTION when we created intent. You may have guessed that this intent is used for taking pictures, which happens to be something that a memes software must use!

The following two lines create a temporary file to save the photo. You can take a look at the code in the start project that already has the code to create the temporary file. Understand how it is implemented.

About Extra

The 4th line of code adds a extra to the newly created intent.
What are you talking about, extra?

Extra is a key-value storage object that is passed to intent that contains additional information so that intent can be used to complete a particular action. For example, if you prepare something beforehand, people can do a task better, and Android is the same. A good intent always needs to be prepared with necessary appendages (extra).

A intent extra type is known and depends on the action, which is the same as the type of data provided to the action.

An excellent example is the creation of an action-action_web_search intent. This action receives a extra that is a key to query, which represents the query string you want to search. This key is usually a string constant, indicating that you should not change it. Opening a intent with such action and extra will display a Google search page and list your search results.

Take a look at Captureintent.putextra (), Extra_output says you'll save the camera's captured photos to a file-so that the Uri is used to point to the empty file you created earlier.

Call Intent

Now a functioning intent is ready to attach a classic intent mental model:

The only thing left is the last line of the Takepicturewithcamera () method that allows intent to accomplish its mission. This is the sentence:

startActivityForResult(captureIntent, TAKE_PHOTO_REQUEST_CODE);

This allows Android to open an activity and execute the action specified by captureintent: Take a picture and save to a file. Once the activity has completed the action, you need to get the captured photos. Take_photo_request_code is our pre-defined constant, which is used to identify this intent when intent returns.

In the R.id.picture_imageview branch of the switch case statement of the OnClick (), join before the break statement:

takePictureWithCamera();

When you click on the image view, the Takepicturewithcamera method is called.

Check out the results of your work! To run the app, click ImageView to open the camera:

You can take a picture at this point, but you can't do anything with it, we'll fix it in the next section.

Note: If you are running in the emulator, you need to edit the camera settings in the AVD. Open the TOOLS\ANDROID\AVD Manager menu and click on the Green Pencil icon on the right side of the virtual machine you want to set. Then click Show Advanced Settings in the lower left corner of the window. In the camera section, make sure that the options in all enabled Camera drop-down boxes are set to emulated.

Implicit intent

If you run the app on a real machine and there are many camera apps installed on the device, you'll find that sometimes this happens:

Will ask you which app you need to use to handle this type of intent.
When you create a intent, you can either display the specified or not specify which app will be used to complete the intent action. Action_image_capture is an excellent example of an implicit intent.

The implicit intent tells Android to be selected by the user. If users already have an app that they like to use to accomplish some sort of task, what's wrong with using the app's functionality to serve you? At the very least, this avoids repeating the invention of the wheel in your app.

An implicit intent tells Android that it needs an app to perform an action on it. The Android system asks each installed app who can handle the action and is then processed by the app. If more than one app can handle this type of intent, the user is prompted to choose:

If only one app can handle it, intent automatically uses it to execute the action. If no app can handle it, Android will not return anything, give you an empty, and cause the app to crash!

To avoid this problem, we can check the return result to ensure that at least one app can handle the action before opening intent. Or declare in Androidmanifest.xml that you have a webcam on your device to install the app.

This demo uses a second method.
You take a photo with an implicit intent, but you don't get the photos in the app. Without a photo, your memes app can't go on.

Add a method after Takepictureactivity's Takepicturewithcamera ():

@OverrideprotectedvoidonActivityResult(intint resultCode, Intent data) {  super.onActivityResult(requestCode, resultCode, data);  if (requestCode == TAKE_PHOTO_REQUEST_CODE && resultCode == RESULT_OK) {    setImageViewWithImage();  }}

This method is executed when activity opened with the Startactivityforresult () method in the Takepicturewithcamera () method is closed and returned to the app.

The If statement above determines whether the returned Requestcode matches your incoming take_photo_request_code to ensure that the returned intent is the intent we want. Also determine that ResultCode is equal to an Android constant RESULT_OK, which means that the operation succeeds.

If everything is OK, our photos are ready, so call Setimageviewwithimage ().

This method is now defined.
First, at the top of the takepictureactivity, add a Boolean variable:

privatefalse;

This variable records whether or not it was taken, and if you take several shots in a row, this variable is useful. Soon we'll be using it.

Then, after Onactivityresult (), add the following:

privatevoidsetImageViewWithImage() {  Bitmap pictureBitmap = BitmapResizer.ShrinkBitmap(selectedPhotoPath.toString(),                                                      takePictureImageView.getWidth(),                                                        takePictureImageView.getHeight());  takePictureImageView.setImageBitmap(pictureBitmap);  lookingGoodTextView.setVisibility(View.VISIBLE);  true;}

Bitmapresizer is an assistant class that comes with the start project to make sure that the photos you get from the camera are compressed to the size that's appropriate for your device's screen. Although the device also stretches the photo, compressing the photo can save memory.

Run the app and choose your favorite camera app--If you're asked--and then take a picture.
This time, the photos will be compressed and displayed in ImageView:

You will also be in the bottom TextView, see a sentence, praise your shooting skills! It's a good thing to be educated! :]

An explicit Intents

Next go to the second stage of the Memes app, but first let your photos pass to another activity because you're worried about the tension in the screen space.

is still takepictureactivity, added after the other constants:

privatestaticfinal"IMAGE_URI";privatestaticfinal"BITMAP_WIDTH";privatestaticfinal"BITMAP_HEIGHT";

These keys are used in the extra you want to pass to the next activity.

Then, in Takepictureactivity, add the following methods, and import the related classes yourself:

privatevoidmoveToNextScreen() {  if (pictureTaken) {    new Intent(this, EnterTextActivity.class);    nextScreenIntent.putExtra(IMAGE_URI_KEY, selectedPhotoPath);    nextScreenIntent.putExtra(BITMAP_WIDTH, takePictureImageView.getWidth());    nextScreenIntent.putExtra(BITMAP_HEIGHT, takePictureImageView.getHeight());    startActivity(nextScreenIntent);  else {    Toast.makeText(this, R.string.select_a_picture, Toast.LENGTH_SHORT).show();  }}

This determines whether Picturetaken is true, which indicates that your ImageView has obtained a picture from the camera. If not, your activity will display a TOAST message, allowing you to take a photo. If true, creates a intent that uses the previously defined constant key to set its extra.

Next, this method is called before the break of the R.id.enter_text_button branch in the OnClick () method:

moveToNextScreen();

Run the app and click LETS memeify! , if you don't take pictures, you'll see a Toast display:

If already photographed, the Movetonextscreen () method walks to the activity that created the intent and enters the input text. It also attaches extra to the intent, such as the Uri and height of the photo. This will be used in the next activity.

You have created your first explicit intent. Explicit intent is much more secure than implicit intent because it describes a component that is used to create and open intent. It may be another activity from your app, or it might be a service in the app, like downloading a file in the background.

This intent specifies a context when constructing (for example, this here) and the Class (Entertextactivity.class) intent wants to open. Because you've already explicitly explained how intent can find b,android from A to make a simple call. The user cannot control how intent is done:

Run the app. Take a picture, but this time click LETS memeify!, your explicit intent will hand the action to the next activity:

This activity has been declared in Manifest in the Start Project, and you do not have to do this step.

The second stage of memes

It looks like this intent is awesome. But where did your extra pass to? Did they turn the wrong corner at the last piece of memory? We should find them and get them to work!

Add the following constants at the top of the entertextactivity:

privatestaticfinal"IMAGE_URI";privatestaticfinal"BITMAP_WIDTH";privatestaticfinal"BITMAP_HEIGHT";

We simply copy the constants from the previous activity here.

Then, after the last line in the OnCreate () method, add:

pictureUri = getIntent().getParcelableExtra(IMAGE_URI_KEY);int100);int100);Bitmap selectedImageBitmap = BitmapResizer.ShrinkBitmap(pictureUri.toString(), bitmapWidth, bitmapHeight);selectedPicture.setImageBitmap(selectedImageBitmap);

When you create an activity, assign the Uri of the previous activity to Pictureuri, and to get the current intent, use the Getintent () method. Once you get intent, you can access the values stored in the extra.

Because variables and objects are stored in different forms, it takes a different approach to access them from intent. For example, to access the Uri object, you need to use Getparcelableextra (). Other extra methods are used to access other types of variables such as strings and raw data types.

The original Getextra () method can also let you specify a default value. If the value to be accessed is not provided, or if key is missing, the default value is used.

Once you have obtained the desired extra, you can create a bitmap with the Uri and the size specified by Bitmap_width, Bitmap_height. Finally, set the image of ImageView to display the photo

In addition to ImageView, there are 2 EditText view on the screen, users can enter their spoof text. The start project has done the work for you, and the spoof text PS to the photo.

All you need to do is modify the OnClick (). In the switch case statement, the R.id.write_text_to_image_button branch joins:

createMeme();

When when to be! Run the App. Take a photo, enter your spoof text in the second activity, and click LETS memeify!:

You wrote your own memes, app!. But don't get too excited-you'll have to do some polishing work for the app.

How to save?

If you can save your spoof image and share it with the world! It does not carry out viral transmission by itself! :]

Fortunately, the beginning of the project has already done most of the work-you just need to connect the wires together.

Add the following code to the Saveimagetogallery () method, just behind the try block and before the second Toast.maketext ():

// 创建一个 intent,请求扫描新建的文件,将照片 uri 传递给 intent,然后广播 intent。new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);mediaScanIntent.setData(Uri.fromFile(imageFile));sendBroadcast(mediaScanIntent);

This intent uses a Action_media_scanner_scan_file ACTION to request the Android library and adds the URL of the image to the Media library. This allows the app to access the Media Library using the Uri of the image.

Action_media_scanner_scan_file action requires intent to provide additional data, the data needs to be a URI, which we construct with the file object of the saved bitmap.

Finally, the intent is broadcast via the Android system so that all interested people--this is the media scanner--. Because media scanner does not have a user interface, you cannot start an activity, so we can only replace it with broadcast intent.

Now, before the break of the R.id.save_image_button branch of the OnClick () method is added:

saveImageToGallery(viewBitmap);

When the user clicks on SAVE IMAGE, the above code will do some error handling, and if everything works, open intent.

Run the app, take a photo, enter the spoof text, click LETS memeify!, and when the image is composited, click SAVE Image.

Close the app and open the Photos program. If you are testing with the simulator, open the Gallery program. You'll see a new photo with the spoof text:

Your spoof photos are not limited by the app and can be sent to social media or shared in any way you want. Your memes app is ready!

Intent Filtration

Now you have a good idea of using different intent for different tasks. But there is another episode in this honest intent story: when sending an implicit intent, how your app knows which intent needs to be handled.

Under the App/manifests folder, open Androidmanifest.xml in the First Activity tab you will see:

The key is the Intent-filter node. A Intent Filter allows your app's components to respond to an implicit Intent.

When Android tries to implement an implicit intent from another app, it's like a banner. An app can have more than one intent filter, waving like a banner, hoping that the person Android is looking for is it.

It's like intent and the app are on an online date! :]
To prove that you are a app,intent filter that matches a intent, you need to provide three things:

    • Intent action: Action that the app can complete, such as the camera app that performs action_image_capture actions for your app.
    • Intent data: This Intent can be accepted by the type. The range of values may be a file path, port, MIME type such as image and video. You can have one or more attributes, and you can strictly and broadly control the type of data the app obtains from intent.
    • Category Intent: Acceptable categories of Intent. This is an additional way to specify which action in an implicit intent can be handled.

It's a good idea to have memeify (sample app) share pictures and other apps through an implicit intent-it's a simple process that surprises you.

Add code after the first intent filter in the Manifest file:

<intent-filter>    <action android:name="android.intent.action.SEND" />    <category android:name="android.intent.category.DEFAULT" />    <data android:mimeType="@string/image_mime_type" /></intent-filter>

This new filter indicates that your app will handle the implicit intent of the action as SEND. Specifying the intent category as DEFAULT also indicates that we do not need any special settings for the category in this case. Only data with a MIME type of image is required.

Open Takepictureactivity.java Add the following method to the class:

privatevoidcheckReceivedIntent() {  Intent imageRecievedIntent = getIntent();  String intentAction = imageRecievedIntent.getAction();  String intentType = imageRecievedIntent.getType();  ifnull) {    if (intentType.startsWith(MIME_TYPE_IMAGE)) {      Uri contentUri = imageRecievedIntent.getParcelableExtra(Intent.EXTRA_STREAM);      selectedPhotoPath = getRealPathFromURI(contentUri);      setImageViewWithImage();    }  }}

Here we get the Intent that opens the activity and find out its action and type, comparing them to the definition in Intent filter to see if its data is mime_type_image type.

If so, continue to get the Uri of the picture, get the bitmap by starting with the helper method provided in the project, and let ImageView display the bitmap.

Then add it after the OnCreate () method:

@OverridepublicvoidonWindowFocusChanged(boolean hasFocus) {  super.onWindowFocusChanged(hasFocus);  checkReceivedIntent();}

Check the intent when your app's window switches focus to your activity. This allows the activity to display a bitmap as soon as it is displayed on the screen.

Run the app. Go back to the home screen now, then go back to the Photos program, or the Gallery program-if you're using a simulator. Select a photo, click the Share button, and choose Memeify from the pop-up menu:

Memeify is ready to accept your photos! Click Memeify to see what happens--memeify will open and display your selected photos in ImageView.

Your app is now accepting this intent! with no courtesy.

End

You can download the completed project from here.

Intent is one of the bricks that build Android. Without it, Android prides itself on being open and connected at all. Learn how to take advantage of good intent and you will gain a strong ally.

If you want to learn more about intent and intent filters, please refer to Google's Intents documentation.
If you have any questions or suggestions, please leave a comment below.

Android Intent Tutorials

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.