A comprehensive analysis of the usage of activity classes in Android application development _android

Source: Internet
Author: User

The activity class is in the Android.app package, the inheritance system is as follows:
1.java.lang.object
2.android.content.context
3.android.app.applicationcontext
4.android.app.activity
The activity is separate and is used to handle user actions. Almost all activity has to do with the user, so the activity class creates a window through which the developer can place the UI on the window where the activity is created, and when the activity points to the Full-screen window, the Setcontentview It can also be implemented in other ways: as a floating window (through a windowisfloating collection of topics), or embedded in another activity (using Activitygroup). Most activity subclasses need to implement the following two interfaces:
The OnCreate (Bundle) interface is where the activity is initialized. Here you can usually call Setcontentview (int) to set the UI defined in the resource file, using Findviewbyid (int) to get the Windows defined in the UI.
The OnPause () interface is where the user is prepared to leave the activity, where any modifications should be submitted (usually for ContentProvider to save the data).
In order to be able to use context.startactivity (), all activity classes must define the associated "work" item in the Androidmanifest.xml file.
The activity class is an important part of the Android application lifecycle. Here's a concrete summary of the various elements of the activity:
I. The life cycle of activity

Ii. transfer of data between the activity
1. Passing Data through intent
The Intent.putextra method allows you to save a simple data type or serializable object in a intent object, and then use Getint, GetString, and so on in another activity to get the data. The sample code is as follows:

Intent Intent =new Intent (currentactivity.this,otheractivity.class);
 Create an email with "Recipient address" 
 Bundle Bundle =new Bundle ();//Create email content
 Bundle.putboolean ("Boolean_key", true);/write Content
 bundle.putstring ("String_key", "string_value"); 
 Intent.putextra ("key", bundle);/Package Email 
 startactivity (Intent)//Start new activity

Here's how to get the data:

 Intent Intent =getintent ()/email 
 Bundle Bundle =intent.getbundleextra ("key");/Open Email 
 Bundle.getboolean ("Boolean_key");/read content
 bundle.getstring ("String_key");

But using bundle to pass data is a bit tricky, if you only need to pass a value of one type:

Intent Intent =new Intent (ex06.this,otheractivity.class); 
 Intent.putextra ("Boolean_key", true); 
 Intent.putextra ("String_key", "string_value"); 
 StartActivity (Intent);

Get Data:

Intent intent=getintent (); 
 Intent.getbooleanextra ("Boolean_key", false); 
 Intent.getstringextra ("String_key");

2. Passing data through static variables
for a simple object that is not serializable, but it is not recommended to use static code blocks

public class Mainactivity extends activity {private Button btn; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    BTN = (Button) Findviewbyid (r.id.btopenotheractivity); 
        Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//define an intent 
        Intent Intent = new Intent (mainactivity.this,otheractivity.class); 
        Change the value of the three static variables of the otheractivity otheractivity.name = "Wulianghuan"; 
        Otheractivity.age = "22"; 
        otheractivity.address = "Shanghai Minhang"; 
      StartActivity (Intent); 
  } 
    }); 
  The public class Otheractivity extends the activity {public static String name; 
  public static String age; 
  public static String address; 
  Private TextView Text_name; 
  Private TextView text_age; 

  Private TextView text_address; @Override public void OnCreate (Bundle savedinstancestate) {Super.oncReate (savedinstancestate); 
    Setcontentview (R.layout.other); 
    Text_name = (TextView) Findviewbyid (r.id.name); 
    Text_age = (TextView) Findviewbyid (r.id.age);   
    Text_address = (TextView) Findviewbyid (r.id.address); 
    Set the data text_name.settext for the text box ("Name:" +name); 
    Text_age.settext ("Age:" +age); 
  Text_address.settext ("Address:" +address);

 } 
}

3. Passing data through global objects
If you want some data to reside in memory for a long time so that your program can call at any moment, we recommend that you use a global object. Application global classes do not need to define static variables as long as you define ordinary member variables, but there must be a parameterless construction method in the global class, after writing the application class, you need to make the global class name in the <application> tag. Otherwise, the system does not automatically create global objects.

public class MainApplication extends application {private String username;
  Public String GetUserName () {return username;
  } public void Setusername (String username) {this.username = username;

  } public class Mainactivity extends activity {private mainapplication application;
    public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Application = (mainapplication) getapplication ();
  Application.setusername ("SUNZN");
    public void open (view view) {Intent Intent = new Intent (this, otheractivity.class);
  StartActivity (Intent);
  } public class Otheractivity extends activity {private TextView tv_data;
  Private MainApplication Application;

  Private String username;
    protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_other);
   Application = (mainapplication) getapplication (); Username = Application.getusername ();
    Tv_data = (TextView) Findviewbyid (r.id.tv_data);
  Tv_data.settext ("The data obtained from the previous activity is:" + username);

 }
}

Iii. return of data from activity
to return data from an activity, you need to use the Startactivityforresult method to display the activity.
Jump from Activity1 to Activity2:

Intent Intent = new Intent ();
 Intent = Intent.setclass (Activityintent.this, anotheractivity.class);
 Bundle Bundle = new Bundle ();
 Bundle.putstring ("string", Et_string.gettext (). toString ());
 Intent.putextras (bundle);
 Startactivityforresult (intent,0); It's just different here.

Return data from Activity2 to Aactivity1:

Intent Intent = new Intent ();
Intent = Intent.setclass (Anotheractivity.this, activityintent.class);
Bundle Bundle = new Bundle ();
Bundle.putint ("Result", "Activity2 processing Results");
Intent.putextras (bundle); 
AnotherActivity.this.setResult (RESULT_OK, intent); RESULT_OK is the return status code
AnotherActivity.this.finish ();

Rewrite the Onactivityresault method in Activity1 to accept the data:

protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
          Super.onactivityresult (requestcode , ResultCode, data);
          Switch (ResultCode) {//According to the status code, processing return result case
          RESULT_OK: 
             Bundle Bundle =data.getextras (); Get Intent object inside Bundle
               String result = bundle.getint (' result '); 
          break; 
          Default: Break
          ;
          } 

       }

Iv. four types of activity creation patterns
in the process of developing a project, we will involve a jump between multiple activity components in the application, or a reusable activity with other applications. For example, we might want to jump to a previous activity instance instead of producing a lot of repetitive activity. This requires that we configure a specific load mode for the activity, instead of using the default load mode. Set the location of the startup mode Android:launchmode properties of the activity in the Manifest.xml file

1.standard mode
This is the default mode, with no settings, and an activity instance is created and placed on the task stack every time that you activate it. Equivalent to the stack, press the back key to return to the previous activity equivalent to the back stack.

2.singleTop mode
if an instance of the activity exists at the top of the task, the instance is reused (the onnewintent () of the instance is invoked), or a new instance is created and placed on top of the stack, and a new instance is created whenever there is an instance on the stack that is not on top of the stack. Can be used to solve the problem of the stack repeating the same activity at most

3.singleTask mode
if an instance of the activity is already on the stack, the instance is reused (the onnewintent () of the instance is invoked). When reused, the instance is returned to the top of the stack, so the instance above it is moved out of the stack. If the instance does not exist in the stack, a new instance will be created into the stack. Singletask mode can be used to exit the entire application. The main activity is set to Singtask mode, then the activity to be exited is transferred to the main activity, then the Onnewintent function of the main activity is overridden and a finish is added to the function.

4.singleInstance mode
create an instance of the activity in a new stack and have multiple applications share the activity instance in the stack. Once an activity instance of the pattern already exists in a stack, any application that activates the active event reuses the instance (Onnewintent () that invokes the instance). The effect is equivalent to multiple applications sharing an application, no matter who activates the activity will enter the same application.

v. Activity onsite Save Status
in general, the activity instance after invoking the OnPause () and OnStop () methods still exists in memory, and all the information and state data for the activity will not disappear , all changes will be preserved when the activity returns to the foreground. However, when the system is low on memory, the activity after invoking the OnPause () and OnStop () method may be destroyed by the system, and the instance object of the activity will not be present in memory. If the activity comes back to the foreground, the changes that have been made will disappear. You can invoke the state of saving each instance before the activity is killed, and the developer can override the Onsaveinstancestate () method. The Onsaveinstancestate () method accepts a Bundle type of parameter that allows the developer to store state data in the Bundle object to ensure that the state is in OnCreate (Bundle) or Onrestoreinstancestate (Bundle) (incoming Bundle parameters are restored by onsaveinstancestate encapsulation). This method is called before an activity is killed and can revert to its previous state when it returns at some point in the future. If you call the Onsaveinstancestate () method, the call will occur before the OnPause () or OnStop () method, and it is not a lifecycle method.
If you insert a record into a database, the operation to save persisted data should be placed in OnPause (). The Onsaveinstancestate () method is only suitable for saving transient data, such as the state of the UI control, the value of the member variable, and so on.

public class Mainactivity extends activity { 
  private String temp;  
  @Override public 
  void OnCreate (Bundle savedinstancestate) { 
    super.oncreate (savedinstancestate); 
    Recover data from Savedinstancestate, if no data needs to be restored savedinstancestate is null if 
    (savedinstancestate!= null) { 
      temp = Savedinstancestate.getstring ("temp"); 
      System.out.println ("oncreate:temp =" + temp); 
    } 

  public void Onrestoreinstancestate (Bundle saveinstancestate) { 
    super.onrestoreinstancestate (saveinstancestate ); 
    String temp = saveinstancestate.getstring ("temp"); 
    System.out.println ("onresume:temp =" + temp); 

  } 

  Saves data to a Outstate object that is passed to the OnCreate method and Onrestoreinstancestate method when the activity is rebuilt
  @Override 
  protected void Onsaveinstancestate (Bundle outstate) { 
    super.onsaveinstancestate (outstate); 
    Outstate.putstring ("temp", temp); 
  }

Vi. some tips on activity
1. Set the direction of the activity

android:screenorientation= "Portrait" >//vertical screen, when the value is landscape for horizontal screen

2. Set Activity Full Screen
Add the following code to the OnCreate method:

Set Full-screen mode
GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, 
 WindowManager.LayoutParams.FLAG_FULLSCREEN); 
Remove title bar
requestwindowfeature (window.feature_no_title);

Change window size, position, transparency
Add the following code to the OnCreate method:

Window W=getwindow ();
W.setbackgrounddrawableresource (ResourceID)//Set window background
windowmanager.layoutparams layoutparams = W.getattributes ();
Layoutparams.height =; 
layoutparams.width=;
layoutparams.gravity = Gravity.top;
Distance layoutparams.y=50 of layoutparams.x=50;//distance gravity attribute
;
Layoutparams.alpha = 0.5;//0: Completely transparent, 1: Opaque
w.setattributes (layoutparams);

3. Close all Windows

Intent Intent = new Intent (); 
Intent.setclass (Android123.this, cwj.class); 
Intent.setflags (Intent.flag_activity_clear_top); Note the flag Settings 
startactivity (Intent)

Another method: Write the Myapplication.getinstance () in the call exit method. Exit ();

public class MyApplication extends application {

   private list<activity> activitylist = new linkedlist< Activity> ();
   private static MyApplication instance;

   Private MyApplication () {
   }

   ///single case mode gets a unique MyApplication instance public
   static MyApplication getinstance () {
       if (null = = instance) {
           instance = new MyApplication ();
       }
       return instance;

   }

   Add an activity to the container public
   void addactivity (activity activity) {
       activitylist.add (activity);
   }

   Traverse all activity and finish
   /* Add the activity to the MyApplication object instance container in each activity's OnCreate method *
   * 
   Myapplication.getinstance (). addactivity (this);
   * * 
   Call exit Method * Myapplication.getinstance () When all activity needs to be terminated 
   . exit ();
   */Public
   void Exit () {for

       (activity activity:activitylist) {
           activity.finish ();
       }

       System.exit (0);

   }


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.