The intent of Android learning

Source: Internet
Author: User

What is intent

For an application, he will have multiple activities, and the jump data transfer between activities can be achieved through intent. Intent is an important way to interact with components in an Android program, not only to indicate what actions the current component wants to perform, but also to pass data between different components. Intent can typically be used to launch events, start services, and send broadcasts, among other scenarios.

Using intent with an explicit intent

To now modify the Click event of the button in Firstactivity, the code is as follows:

Button1.setonclicklistener (new  Onclicklistener () {    @Override    publicvoid  OnClick (View v) {        new Intent (firstactivity.  this, secondactivity. class );        StartActivity (intent);    }});  

First we created a new intent, passed in Firstactivity.this, as a context, Incoming Second.class as the target activity, so our intention is to firstactivity this activity to click button and then open secondactivity this activity, and then through the startactivity () method to perform this intent.
The intent intent in this way is obvious, so called explicit intent.

Using an implicit intent

Implicit Intent is a lot more subtle than explicit Intent, it does not explicitly indicate which activity we want to start, but instead specifies a series of more abstract actions and category information, which is then referred to the system to analyze the Intent.
By configuring the content under the tag, you can specify the action and category that the current activity responds to, open androidmanifest.xml, and add the following code:

<ActivityAndroid:name=". Secondactivity " >    <Intent-filter>        <ActionAndroid:name= "Com.example.activitytest.ACTION_START" />        <categoryAndroid:name= "Android.intent.category.DEFAULT" />    </Intent-filter></Activity>  

In the Action tab We indicate that the activity secondactivity can respond to the Com.example.activitytest.ACTION_START action, and the category The tag contains additional information (note that action can only have one, category can have multiple), and more precisely indicates which intent the current activity responds to. This activity responds to intent only if the contents of the action and category match the action and category specified in the intent.
Modify the Click event code of the button in the firstactivity as follows:

Button1.setonclicklistener (new  Onclicklistener () {    @Override    publicvoid  OnClick (View v) {        new Intent ("Com.example.activitytest.ACTION_START");        StartActivity (intent);    }});  

Here we specify ACTION as Com.example.activitytest.ACTION_START, but we do not specify category. Because Android.intent.category.DEFAULT is a default category, our code in Androidmanifest.xml is as follows:

<ActivityAndroid:name=". Secondactivity ">    <Intent-filter>        <ActionAndroid:name= "Com.example.activitytest.ACTION_START" />        <categoryAndroid:name= "Android.intent.category.DEFAULT"/>        <categoryAndroid:name= "Com.example.activitytest.MY_CATEGORY"/>    </Intent-filter>        </Activity>  

So although we did not specify category in the Firstactivity button click event code, we registered the default category in the. xml file, and therefore responded to this activity.

More on the use of implicit intent

With implicit intent, not only can we start activities within our own programs, but we can also start the activities of other programs. This makes it possible to share functionality between multiple programs.
Now modify the Firstactivity button in the Click event code as follows:

Button1.setonclicklistener (new  Onclicklistener () {    @Override    publicvoid  OnClick (View v) {        new  Intent (intent.action_view);        Intent.setdata (Uri.parse ("http://www.baidu.com"));        StartActivity (intent);    }});  

Here we have specified the action of intent as Intent.action_view, which is an action built into the Android system with a constant value of Android.intent.action.VIEW. With the Uri.parse () method, you can parse a URL string into a Uri object, and in the call to Intent's SetData () method, the URI object is passed in.
Clicking on the button will open your own browser to visit Baidu.
Of course we can also configure the data tag in the intent-filter tag to specify what type of information the current activity responds to. Now we create a new layout and activity, and he registers with the data tag specified as the HTTP protocol. So when we have an event where his action and category correspond to our new, and the event protocol is HTTP, we also respond to this activity.
In addition to the HTTP protocol, GEO represents a geographic location, and Tel represents a call.

Passing data to an activity down

It was all about intent start-up activity, and intent can also pass data when the activity is started.
The Intent provides a series of overloads of the PutExtra () method that can temporarily present the data we want to pass in Intent, and once another activity is initiated, it is only possible to remove the data from the Intent.
Now there is a string in the firstactivity activity, now to pass the string to Secondactivity, the Firstactivity code is as follows:

Button1.setonclicklistener (new  Onclicklistener () {    @Override    publicvoid  OnClick (View v) {        = "Hello secondactivity";         New Intent (firstactivity.  this, secondactivity. class );        Intent.putextra ("Extra_data", data);        StartActivity (intent);    }});  

Here we start secondactivity in the way shown, passing a string through the Putextra () method. The first parameter in the PutExtra () method is a key, and the second is a value.
Get the value passed in secondactivity:

 Public class extends Activity {    @Override    protectedvoid  onCreate (Bundle savedinstancestate) {         Super . OnCreate (savedinstancestate);        Requestwindowfeature (window.feature_no_title);        Setcontentview (r.layout.second_layout);         = getintent ();         = Intent.getstringextra ("Extra_data");        LOG.D ("secondactivity", data);}    }  

The Getintent () method can be active to start the currently active intent, and then call the Getstringextra () method to get the data. If the value passed in is an integer, then the remaining types are similar with Getintextra ().

Return data to previous activity

         We can pass data to the next activity then of course we can return the data to the previous activity. There is also a Startactivityforresult () method in the
        activity that is used to start the activity. But this method expects to be able to return a result to the previous activity when the activity is destroyed. The
        startactivityforresult () method is also used to start the activity, But this method expects to be able to return a result to the previous activity when the activity is destroyed. The second parameter is the request code, and the secondactivity activity destroys the currently active Onactivityresult () method, and the first parameter of the method specifies the request code.
         We modify the Click event of the button in Firstactivity, the code is as follows:

Button1.setonclicklistener (new  Onclicklistener () {    @Override    publicvoid  OnClick (View v) {        new Intent (firstactivity.  this, secondactivity. class );         1);}    )  ;

Next we register the click event with the button in secondactivity and add the logic to return the data in the Click event, as shown in the code below:

 Public classSecondactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);        Setcontentview (r.layout.second_layout); Button Button2=(Button) Findviewbyid (r.id.button_2); Button2.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Intent Intent=NewIntent (); Intent.putextra ("Data_return", "Hello firstactivity");              Setresult (RESULT_OK, intent);          Finish ();    }        }); }}  

Here we have a new intent, but we don't specify any intention, because this intent is just for passing data. This invokes the Setresult () method, which is used to return data to the previous activity . It has 2 parameters, the first parameter is used to return processing results to the previous activity, typically only use RESULT_OK or result_canceled, and the second parameter is to pass the Intent with the data back.
Because we use the Startactivityforresult () method to start the current activity, the current activity is destroyed and the previous activity's Onactivityresult () method is called back, so we need to write the following code:

@Overrideprotected voidOnactivityresult (intRequestcode,intResultCode, Intent data) {    Switch(requestcode) { Case1:        if(ResultCode = =RESULT_OK) {String Returneddata= Data.getstringextra ("Data_return"); LOG.D ("Firstactivity", Returneddata); }         Break; default:    }} 

The method has 3 parameters, the first parameter represents the request code, there may be more than one returned data, the request code can correspond, the second parameter is to return data when the processing results, is RESULT_OK or result_canceled, the third parameter is a intent with data.

If the user is not secondactivity by clicking the button, but by pressing the back key to return to firstactivity, we can resolve the problem by overriding the Onbackpressed () method, as shown in the following code:

@Override  Public void onbackpressed () {    new  Intent ();    Intent.putextra ("Data_return", "Hello firstactivity");    Setresult (RESULT_OK, intent);    Finish ();}  

In this case, when the user presses the back key, the code in the Onbackpressed () method is executed, and the effect is the same as when the button was clicked.

To learn intent here.

The intent of Android learning

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.