12) 10 minutes to learn the simple data transmission of ANDROID--APP communication transmission message

Source: Internet
Author: User

Inter-Program communication is one of the best features of Android programs. When a feature already exists in another app and is not a core feature of the program, there is absolutely no need to re-write it.

This section describes some common ways to send and receive content between different programs by using intent APIs and Actionprovider objects.

Lessons
    • Send a simple data to another app-sending single-data to other apps

      Learn how to use intent to send text and binary data to other apps.

    • Receive data returned from another app-receiving simple data from other apps

      Learn how to receive text and binary data from other apps through intent in our app.

    • Add sharing function to Actionbar-Adding an easy Share Action

      Learn how to add a sharing feature on Acitonbar.

Send simple data to other apps

When building a intent, you must specify the actions that the intent needs to trigger. Android defines actions such as Action_send, which indicates that the intent is used to send data from one activity to another activity, or even to send data across processes.

In order to send data to another activity, we only need to specify the type of data and data, and the system will automatically identify the activity that is compatible with the accepted data. If there are multiple choices, the activity is displayed to the user for selection, and if there is only one, the activity is started immediately. Similarly, we can add the accepted data types in the activity description of the manifest file.

Using intent to send and receive data between different programs is the most common way to share content socially. Intent enables users to share information quickly and easily through the most commonly used programs.

Note: the best way to add share functionality for Actionbar is to use Shareactionprovider, which runs on systems with API level 14. Shareactionprovider will be described in detail in the 3rd lesson.

Share text contents (Send text content)

The most direct use of action_send is to send text content from one activity to another activity. For example, the Android built-in browser can share the URL of the currently displayed page as text content to other programs. This feature is useful for sharing articles or URLs to friends via email or social networks. Here is a sample Code:

New"This was my text to send." ); Sendintent.settype ("Text/plain"); StartActivity (sendintent) ;

If a program is installed on the device that matches action_send and the MIME type is Text/plain, the Android system executes it immediately. If there are multiple matching programs, then the system will filter them out and present dialog to the user to choose.

If Intent.createchooser () is called for intent, then Android will always show up for selection. This has some benefits:

    • Even if the user has previously set the default action for this intent, the selection screen will be displayed.
    • If there are no matching programs, Android displays system information.
    • We can specify the title of the selection interface.

The following is the updated code:

New"This was my text to send." ); Sendintent.settype ("Text/plain"); StartActivity (Intent.createchooser (Sendintent, Getresources (). GetText (r.string.send_to));

As follows:

In addition, we can set some standard value for intent, for example: Extra_email, EXTRA_CC, EXTRA_BCC, Extra_subject, etc. However, if the receiving program does not do special processing for those, there will be no corresponding response.

Note: some e-mail programs, such as Gmail, correspond to receive Extra_email and EXTRA_CC, they are all string type, can use Putextra (string,string[]) method to add to the intent.

Sharing binary contents (Send binary content)

Sharing binary data requires a combination of setting a specific MIME type ,需要在 Extra_stream ' inside the URI that contains the data, below is an example of sharing the image, which can also be modified to share any type of binary data:

New Intent (); shareintent.setaction (intent.action_send); Shareintent.putextra (Intent.extra_stream, uriToImage); Shareintent.settype ("Image/jpeg"); StartActivity (Intent.createchooser (Shareintent, Getresources (). GetText (r.string.send_to));

Please note the following:

    • We can */* specify MIME types in such a way, but this will only match to those that can handle the general data type (i.e. the general activity cannot be exhaustive for all MIME types)
    • The received program requires permission to access the URI resource. Here are some ways to deal with this problem:
      • Store the data in ContentProvider, ensuring that other programs have access to provider. A better way to provide access is to use Per-uri permissions, which is only temporarily holding the permission for the receiving program. An easy way to create contentprovider like this is to use the Fileprovider helper class.
      • Use the Mediastore system. Mediastore system is mainly used for audio and video and image MIME type. But after Android3.0, it can also be used to store non-multimedia types.
Send multiple contents (send multiple Pieces of content)

To share many different types of content at the same time, you need to use action_send_multiple with the URIs list assigned to those data. MIME types vary depending on the blended content you share. For example, if you share a picture of 3 jpeg, the MIME type is still image/jpeg . If you have a different image format, you should use image/* to match activity that can receive any type of image. If you need to share many different types of data, you can use */* to represent mime. As described earlier, this depends on the programs that are received to parse and process our data. Here's an example:

New arraylist<uri>//  Add your image URIsherenew  Intent (); Shareintent.setaction (intent.action_send_multiple); Shareintent.putparcelablearraylistextra (Intent.EXTRA_STREAM , Imageuris); Shareintent.settype ("image/*""Share images to.."));

Of course, make sure that the URIs that you specify to the data can be accessed by the receiving program (add access).

Receive data sent from other apps

Just as our program can share data with other programs, it can also easily receive data from other programs. What you need to consider is how the user interacts with our program, and what type of data we want to receive from other programs. For example, a social networking program might want to be able to accept text data from other programs, such as an interesting URL link. Google + 's Android client accepts text data with a single sheet or multiple images. Users can simply select an image from the gallery program to launch Google + and use it to publish text or images.

Update our Manifest file (update Your Manifest)

Intent filters tells the Android system that a program is willing to accept data types. Similar to the previous lesson, we can create intent filters to indicate the type of action the program can receive. The following is an example of three activit to accept a single picture, text and multiple pictures. (Intent filter related information, please refer to intents and Intent Filters)

<activity android:name= ". UI. MyActivity ">    <intent-filter>        <action android:name=" Android.intent.action.SEND "/>        <category android:name= "Android.intent.category.DEFAULT"/>        <data android:mimetype= "image/*"/>    </intent-filter>    <intent-filter>        <action android:name= "Android.intent.action.SEND"/ >        <category android:name= "Android.intent.category.DEFAULT"/>        <data android:mimetype= "text/ Plain "/>    </intent-filter>    <intent-filter>        <action android:name=" Android.intent.action.SEND_MULTIPLE "/>        <category android:name=" Android.intent.category.DEFAULT "/>        <data android:mimetype= "image/*"/>    </intent-filter></activity>

When a program tries to share something by creating a intent and passing it to startactivity, our program is rendered in a list to allow the user to make a selection. If the user chooses our program, the corresponding activity will be called to open, this time is how we handle the data obtained the problem.

Processing received data (Handle the Incoming Content)

To handle the data brought from intent, you can get to the intent object by calling the Getintent () method. When we get to this object, we can judge the data on the surface, and decide the next behavior. Keep in mind that if an activity can be started by another program, we need to consider this when checking intent (which is initiated by another program).

voidonCreate (Bundle savedinstancestate) {...//Get Intent, action and MIME typeIntent Intent =getintent (); String Action=intent.getaction (); String type=Intent.gettype (); if(Intent.ACTION_SEND.equals (ACTION) && type! =NULL) {        if("Text/plain". Equals (Type) {Handlesendtext (intent);//Handle text being sent}Else if(Type.startswith ("image/") {handlesendimage (intent);//Handle single image being sent        }    } Else if(Intent.ACTION_SEND_MULTIPLE.equals (ACTION) && type! =NULL) {        if(Type.startswith ("image/") {handlesendmultipleimages (intent);//Handle multiple images being sent        }    } Else {        //Handle Other intents, such as being started from the home screen    }    ...}voidHandlesendtext (Intent Intent) {String Sharedtext=Intent.getstringextra (Intent.extra_text); if(Sharedtext! =NULL) {        //Update UI to reflect text being shared    }}voidhandlesendimage (Intent Intent) {Uri Imageuri=(Uri) Intent.getparcelableextra (Intent.extra_stream); if(Imageuri! =NULL) {        //Update UI to reflect image being shared    }}voidhandlesendmultipleimages (Intent Intent) {ArrayList<Uri> Imageuris =Intent.getparcelablearraylistextra (Intent.extra_stream); if(Imageuris! =NULL) {        //Update UI to reflect multiple images being shared    }}

Note that because it is not possible to know whether the data content sent by other programs is text or other types of data, if the amount of data is large, it will require a lot of processing time, so we should avoid processing those acquired data in the UI thread.

Updating the UI can be as simple as updating the edittext, or it can be a more complex operation, such as filtering out images of interest. It all depends on what our application is going to do next.

Add a simple sharing feature

The introduction of Actionprovider in the system after Android4.0 makes it easier to add sharing functionality to the Actionbar. It will handle the appearance and behavior that appear share function. In the case of shareactionprovider, we only need to provide a share intent, and the rest will be given to Shareactionprovider.

Updating the menu declaration (update Declarations)

The first step in using Shareactionprovider is to define the properties in the menu resources corresponding item android:actionProviderClass .

<menu xmlns:android= "Http://schemas.android.com/apk/res/android" >    <item android:id= "@+id/menu_item_ Share "        android:showasaction=" Ifroom "        android:title=" Share "        android: Actionproviderclass= "Android.widget.ShareActionProvider"/>    ... </menu>

This indicates that the appearance and function of the item need to match the Shareactionprovider. Also, you need to tell provider what you want to share.

Set the Share Intent (settings shared Intent)

In order to realize the function of Shareactionprovider, we must provide a intent for it. The share intent should, as the first lesson says, have ACTION_SEND and append data (for example, EXTRA_TEXT with EXTRA_STREAM ). Examples of using Shareactionprovider are as follows:

Privateshareactionprovider Mshareactionprovider; @Override Public BooleanOncreateoptionsmenu (Menu menu) {//Inflate Menu resource file.getmenuinflater (). Inflate (R.menu.share_menu, menu); //Locate MenuItem with ShareactionproviderMenuItem item =Menu.finditem (R.id.menu_item_share); //Fetch and store ShareactionproviderMshareactionprovider =(Shareactionprovider) Item.getactionprovider (); //Return True to display menu    return true;}//Call to update the share intentPrivate voidsetshareintent (Intent shareintent) {if(Mshareactionprovider! =NULL) {mshareactionprovider.setshareintent (shareintent); }}

Maybe you just need to set up a share intent when creating a menu, or we might want to set up share intent first, and then update the intent based on the changes in the UI. For example, when you view a picture in gallery, share intent changes when you switch the picture. For more information on Shareactionprovider, please see action Bar.

12) 10 minutes to learn the simple data transmission of ANDROID--APP communication transmission message

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.