Activity details 1 configure, start, and close an activity. activity details

Source: Internet
Author: User

Activity details 1 configure, start, and close an activity. activity details

First look:


Android provides four application components: Activity, Service, Broadcast receivers, and Content providers. These components constitute the foundation for developing an Android Application. The system can enter the developed application through the entry points provided by different components. For users, not all components are actually the starting points, but they are mutually dependent. Each of them acts as an existing entity and plays a specific role, as a unique cornerstone, it helps developers Define the behavior of Android applications. Below I will organize my own Activity learning experience:

An Acitvity interface is a user interaction interface displayed on the screen. For example, in an email application, an Activity is used to display the receiving list and an Activity used to write emails, an Activity that reads the content of an email. Activity is used to provide a user experience. When multiple activities with different experiences are combined, the user experience of an Android Application can be formed. Each Activity is independent of each other. In addition to accessing your own Activity, the APP can also access the Acitivity of other apps (which must be permitted by the APP ).

1. How to create an Activity?

You must create a subclass of an Activity. In this subclass, you must implement the functions called back by the system (onCreate, onStart, onResume, onPause, onStop, and onDestroy) when the Activity status is switched during the lifecycle ), of course, not all functions need to be implemented again. Two of the most important functions are onCreate and onPause:

OnCreate (), which must be overwritten. The system calls this method to create an activity, which is an important step for you to initialize the Activity you created. The most important thing is to call setContentView () to define the layout of the user interface to be displayed.

OnPause (), this method is called when the system task user leaves this interface. At this time, an Activity is not destroyed. Generally, we need to deal with some changes that persist beyond user sessions, such as data storage.

To ensure smooth user experience and processing, you can call other callback functions to stop or destroy your Atctivity. In the onStop () method, release large resource goods objects, such as network or database connections. You can load the required resources in onResume.

2. Create an Activity
Public class MainActivity extends Activity {// method that must be rewritten @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // activity layout }}



2. After an Activity is created, it must be declared and registered to the AndroidManifest. xml file of the application for its access to the system:

<activity      android:name="com.zy.demo.activity.MainActivity"      android:label="@string/app_name" >      <intent-filter>          <action android:name="android.intent.action.MAIN" />          <category android:name="android.intent.category.LAUNCHER" />      </intent-filter>  </activity>  

<Activity> there are many attributes for developers to define Activity with different characteristics, such as lable, icon, theme, and style. Android: name is a required attribute to define the name of an activity. It cannot be changed after the application is published.

<Activity> it also provides various intent-filters and uses <intent-filter> to declare how other application components activate (start) the Activity, <intent-filter> contains two elements: <action> and <category>. In the preceding example, <action android: name = "android. intent. action. MAIN "/> indicates that this Activity needs to respond to android. intent. action. MAIN (indicates the MAIN entry of the Application), <category android: name = "android. intent. category. LAUNCHER "/> indicates that the Activity is the LAUNCHER category, that is, the application is listed in the Launcher, allowing users to start directly. The preceding Declaration method is required for the MAIN activity of an Application: a MAIN action and a LAUNCHER category. If you want the Activity to respond to the implicit intent of other applications, you must declare the corresponding action for the Activity and add categor and data.

3. Start Activity 3.1 startActivity

Call startActivity (intent) to start the Activity. intent is used to accurately describe the Activity you want to start, or the action you want to perform. intent can also be used to carry small data to the acitiworkflow to be started.

When another Activity needs to be simply started in the middle of the same application, intent clearly defines that you need to start the Activity class:

// Define an intent, indicating the activity to be started: ToStartActivity Intent intent = new Intent (MainActivity. this, ToStartActivity. class); // use startActivity () to start the activity startActivity (intent );


When your application needs to execute behaviors that do not have any Activity, we can use the Activity of other apps on the mobile phone instead. For example, sending a mail, viewing an image, and searching for a word. This is also the important point of Intent. You can define an intent to describe what you want to do. After you send it to the system, the system will start the appropriate Acitivty for your execution, if the Activity of multiple applications can process this line, the system will ask the user to select one. After the Activity is executed

// Search for Intent intent = new Intent (Intent. ACTION_WEB_SEARCH); intent. putExtra (SearchManager. QUERY, "zy"); startActivity (intent) from the google interface across applications );


When a cross-application starts an Activity, you must specify the specific acitvity for the intent when defining the intent, provided that the activity must be exposed outside your application (android: exported = "true "):

Intent intent = new Intent (); // specifies the complete package name to be started. The object name is ComponentName cn = new ComponentName ("com. android. settings "," com. android. settings. runningServices "); intent. setComponent (cn); // use context. startActivity () requires a new task intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (intent );


3.2 startActivityForResult

Call startActivityForResult (intent) to receive the result of the startup Acitivity. To receive the results of the subsequent Activity, you need to override the onActivityResult () callback function. After the called activity is completed, it returns an intent containing the result to onActivityResult () for processing. For example, in an application Activity, you need to select one of the contacts, and the Activity needs to obtain some information about the contacts:

Intent intent = new Intent (Intent. ACTION_PICK, Contacts. people. CONTENT_URI); // start an activity startActivityForResult (intent, PICK_CONTACT_REQUEST) with the returned result of the selected contact; The PICK_CONTACT_REQUEST here is the custom int type Request feedback result code. // Reonactivityresult () is used to process the received returned result @ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {// if the request requestCode is successful, the resultCode returned by the request is the PICK_CONTACT_REQUEST if (resultCode = Activity. RESULT_ OK & requestCode = PICK_CONTACT_REQUEST) {// process the data returned by Intent, and find the contact name in the contact database: Cursor cursor = getContentResolver (). query (data. getData (), new String [] {Contacts. people. NAME}, null); if (cursor. moveToFirst () {// If the cursor is not empty, find the contact name int columnIndex = cursor. getColumnIndex (Contacts. people. NAME); String name = cursor. getString (columnIndex); // Add other functions }}}


Here we want to explain that onActivityResult () is used to process the returned results. First we need to check whether the request is successful, whether there are returned results, and whether the result is required in startActivityForResult, if yes, the data returned through Intent is processed.

4. Disable Activity

1 Activity can call the finish () method to close itself, or call the finishActivity () method to close an independent previously started Activity.

2. Call finishActivity () to close an independent previously started Activity.

// This method is used to disable the Activity enabled with startActivityForResult (requestCode ).

This. finishActivity (requestCode );

When to close an Activity, it is generally managed by the system. However, when you confirm that the user does not need to return the Activity, we call the above method to close the corresponding Activity.


5 Demo code:
Package testusea; import android. content. intent; import android. support. appCompatActivity; import android. OS. bundle; import android. view. view; public class TestUseAActivity extends AppCompatActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_test_use_a);} // start the first activity public void startFirstActivity (View view) {Intent intent = new Intent (this, TestUseAActivity2.class); startActivity (intent );} // start the second activity public void startSecondActivity (View view) {Intent intent = new Intent (this, TestUseAActivity3.class); startActivity (intent);} // start the third activity, this activity will be closed after 4 seconds. public void startThirdActivity (View view) {Intent intent = new Intent (this, TestUseAActivity4.class); startActivityForResult (intent, 1); new Thread () {@ Override public void run () {try {Thread. sleep (4000); finishActivity (1);} catch (InterruptedException e) {e. printStackTrace ();}}}. start ();}}

 Download Demo
Finally, the above examples are source and Android worry-free, please go to the app or pea pod download: ApkName = com. shandong. mm. androidstudy. The source code example documentation is exhausted.

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: 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.