2.1 What is the event?
Activity, a component that contains a user interface, primarily for interacting with users
2.2 Basic usage of activities
The creation process for a complete activity:
2.2.1 Creating an activity manually
New→class, inherit from Activity, click Finish to complete the creation.
2.2.2 Creating and loading layouts
1) Create a layout file
Right-click the res/layout directory →new→android xmlfile
2) load the layout file in the activity's OnCreate () method
Setcontentview (r.layout.first_layout);
2.2.3 registering activity in the Androidmanifest file
<activity
Android:name= ". Firstactivity "
Android:label= "This is firstactivity" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
2.2.4 Hide title bar
Requestwindowfeature (Window.feature_no_title);
2.2.5 using Toast in an activity
Toast a short pop-up information hint
Toast.maketext (Firstactivity.this, "You clicked Button 1", Toast.length_short). Show ();
2.2.6 using the menu in the event
1) First create a new menu folder in the Res directory, right-click on the res directory →new→folder, then create a new one in the folder named Main, right-click the menus folder →new→android XML file, and then write the menu options:
<item
Android:id= "@+id/add_item"
android:title= "Add"/>
<item
Android:id= "@+id/remove_item"
android:title= "Remove"/>
2) Deploy the menu in activity and implement it through the Oncreateoptionsmenu () method
public boolean Oncreateoptionsmenu (Menu menu) {
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
3) Define a response event for the menu, implemented by onoptionsitemselected (MenuItem item)
public boolean onoptionsitemselected (MenuItem item) {
Switch (Item.getitemid ()) {
Case R.id.add_item:
Toast.maketext (This, "You clicked Add", Toast.length_short). Show ();
Break
Case R.id.remove_item:
Toast.maketext (This, "You clicked Remove", Toast.length_short). Show ();
Break
Default
}
return true;
}
2.2.7 Destroy an activity
Button1.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
Finish ();
}
});
2.3 Using Intent to shuttle between activities
Intent (Intent), defines an action, an important way of interacting between components, as well as data transfer, which is divided into explicit Intent and implicit Intent
2.3.1 using an explicit Intent
Intent Intent = new Intent (firstactivity.this, Secondactivity.class);
StartActivity (Intent);
2.3.2 using an implicit Intent
1) Configure the Activity's filter statement in the configuration file
<intent-filter>
<action android:name= "Com.example.activitytest.ACTION_START"/>
<category android:name= "Android.intent.category.DEFAULT"/>
</intent-filter>
<action/> indicates which actions the activity can respond to, and when an activity's intent action condition matches it, the activity is aroused.
2) Set the intent action to match in the activity
Intent Intent = new Intent ("Com.example.activitytest.ACTION_START");
StartActivity (Intent);
A. A Intent Filter can contain multiple actions, you can specify an action list to identify the "action" that Activity can accept, and you can specify multiple category, calling the Addcategory () method in Intent to add.
B. If you are using the default category, you will automatically add the category to the intent when you call the StartActivity () method later, otherwise you will need to addcategory () method to manually add a category, such as
(Intent.addcategory ("Com.example.activitytest.MY_CATEGORY");)
C. If multiple components match successfully, the user will be selected as a list of dialog boxes.
D. Only one action can be specified in each intent, but more than one category is specified, the more the class, the more specific the action, and the more explicit the intent (and the need for the matched component to meet the multiple categories at the same time to match the success).
E. When the intent matching successful component has multiple, display priority components, if the priority level is the same, the display list lets the user choose
F. Priority is from 1000 to 1000, and one of them must be negative to be valid. Set priority by Android:priority
<activity
Android:name= ". Secondactivity ">
<intent-filter android:priority= "-1" >
<action android:name= "Android.intent.action.VIEW"/>
<category android:name= "Android.intent.category.DEFAULT"/>
<data android:scheme= "http" android:host= "www.baidu.com"/>
</intent-filter>
</activity>
2.3.3 more about the use of implicit Intent
1) Call the System browser
Intent Intent = new Intent (Intent.action_view);
Intent.setdata (Uri.parse ("http://www.baidu.com"));
StartActivity (Intent);
<data> tags, configured in <intent-filter>, indicate which data requests can be responded to, and the current activity is only able to respond to intent if the intent is in full agreement with the one in which it is carried.
2) Call
Intent Intent = new Intent (intent.action_dial);
Intent.setdata (Uri.parse ("tel:10086"));
StartActivity (Intent);
2.3.4 Passing data down an activity
The Intent provides a series of PutExtra () methods that temporarily present the data that you want to pass in Intent, and then remove the data from the Intent after initiating another activity.
1) Passing Data
String data = "Hello secondactivity";
Intent Intent = new Intent (firstactivity.this, Secondactivity.class);
Intent.putextra ("Extra_data", data);
StartActivity (Intent);
PutExtra () method The first parameter is the key, which is used to take a value from the intent later
2) Take out the data
Intent Intent = Getintent ();
String data = Intent.getstringextra ("Extra_data");
Gets the Intent used to start the current Activity through the Getintent () method.
2.3.5 return data to previous activity
1) Use the Startactivityforresult () method to start the next activity
Intent Intent = new Intent (firstactivity.this, Secondactivity.class);
Startactivityforresult (Intent, 1);
The Startactivityforresult () method receives two parameters, the first parameter is Intent, the second parameter is the request code, which is used to determine the source of the data in subsequent callbacks, as long as the request code is a unique value.
2) return data to the previous activity
Intent Intent = new Intent ();
Intent.putextra ("Data_return", "Hello firstactivity");
Setresult (RESULT_OK, intent);
The intent here is just for passing data, and the Setresult () method is designed to return data to the previous activity, as well as to rewrite the code in the Onbackpressed () method.
3) Read the returned data
The Onactivityresult () method of the previous activity is called back after the activity is destroyed, so the method needs to be rewritten to obtain the data from the callback
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
Switch (requestcode) {
Case 1:
if (ResultCode = = RESULT_OK) {
String returneddata = Data.getstringextra ("Data_return");
LOG.D ("Firstactivity", returneddata);
}
Break
Default
}
}
2.4 Life cycle of the activity 2.4.1 return stack
Android is a task to manage activities, a task is a set of activities stored in the stack, the stack is a last-in-first-out data structure, by default, whenever we start a new activity, it will be in the return stack, and at the top of the stack position. And every time we press the back key or call the finish () method to destroy an activity, the activity at the top of the stack will be out of the stack, and the previous stack activity will be back at the top of the stack. The system always displays the activity at the top of the stack to the user.
2.4.2 Activity Status
1) Operating Status
The activity is at the top of the stack.
2) Pause Status
When an activity is no longer in the top position of the stack, but is still visible, the activity enters a paused state.
3) Stop State
When an activity is no longer at the top of the stack and is completely invisible, it enters a stop state.
4) Destruction Status
When an activity is removed from the return stack, it becomes a destroyed state.
2.4.3 Lifetime of activity
Corresponds to seven callback methods, covering every aspect of the activity life cycle.
1) onCreate ()
Called when the activity is first created, and completes the initialization of the activity, such as loading layouts, binding events, and so on.
2) OnStart ()
Called when an activity becomes visible by invisible.
3) Onresume (Resume: restart, resume)
is ready to be called when interacting with the user, at which point the activity must be at the top of the stack and is in a running state.
4) OnPause () (Pause: Pause)
Called when the system is ready to start or resume another activity. We usually release some CPU-consuming resources in this method and save some key data, but this method must be executed quickly, otherwise it will affect the use of the new stack top activity.
5) OnStop ()
Called when the activity is completely invisible, when a dialog box is started and the activity is not completely invisible, only OnPause () is started and the OnStop () is not started.
6) OnDestroy ()
Called before the activity is destroyed, and then the state of the activity becomes the destroy state.
7) Onrestart ()
Called by the stop state before it becomes a running state, that is, the activity is restarted.
2.4.4 Lifetime of activity
In addition to the Onrestart () method, the other is 22 relative, which allows the activity to be divided into three lifetimes:
1) Full Life time
What goes through between the OnCreate () method and the OnDestroy () method is the complete survival period. In general, a variety of initialization operations are done in the OnCreate () method, and the memory-freeing operation is done in the OnDestroy () method.
2) Visible lifetime
Between the OnStart () method and the OnStop () method is the visible lifetime. These two methods allow us to reasonably manage resources that are visible to the user, such as loading the resource in the OnStart () method, and freeing the resource in the OnStop () method.
3) Foreground lifetime
Between the Onresume () method and the OnPause () method, is the foreground lifetime. Activities are always running, and activities at this time can interact with the user.
What to do if the 2.4.5 activity is recycled
To prevent data loss from being filled in, the current data state of the activity can be saved through the onsaveinstancestate (bundle Outstate) method, and the callback is passed OnCreate (bundle Savedinstancestate) method to restore the saved data.
1) Save data
protected void Onsaveinstancestate (Bundle outstate) {
Super.onsaveinstancestate (outstate);
String TempData = "Something you just typed";
Outstate.putstring ("Data_key", TempData);
}
Bundles provide a series of methods for saving data, each saving method needs to pass in two parameters, the first parameter is the key, and the second parameter is the actual content to be saved.
2) Take out the data
protected void OnCreate (Bundle savedinstancestate) {
if (savedinstancestate! = null) {
String TempData = savedinstancestate.getstring ("Data_key");
LOG.D (TAG, TempData);
}
......
}
The OnCreate () method has a parameter of bundle type, which in general is null, but if the activity is saved by the Onsaveinstancestate () method before the system is reclaimed, this parameter will have all the data that was previously saved. The data can be taken out by the corresponding value method.
2.5 Active Startup mode
Select the startup mode in Androidmanifest.xml by assigning the Android:launchmode property to the <activity> tag.
2.5.1 Standard Mode
Standard is the active default startup mode, which is automatically used by all activities without explicit designation. Whenever a new activity is started, it is placed on the stack in the return stack and at the top of the stack, regardless of whether the activity has already been present in the return stack, and each startup creates a new instance of the activity.
2.5.2 Singletop Mode
When you start an activity, if you find that the stack at the top of the stack is already the activity, you think you can use it directly and no longer create a new activity instance.
2.5.3 singletask Mode
Each time the activity is started, the system first checks to see if there is an instance of the activity in the return stack, uses the instance directly if found to exist, and puts all the activities on top of the activity out of the stack, creating a new activity instance if it is not found.
2.5.4 singleinstance Mode
There will be a separate return stack to manage this activity, regardless of which application accesses the activity, the same return stack is shared, and the problem of shared activity instances is resolved.
2.6 Best Practices for activities 2.6.1 know which activity is currently in
Write a baseactivity class and let all other activity classes inherit from the class
public class Baseactivity extends Activity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
LOG.D ("Baseactivity", GetClass (). Getsimplename ());
}
}
The name of the activity will be printed when entering any activity.
2.6.2 exit the program anytime, anywhere
Solution: Manage all activities with a dedicated collection class
1) Create a new Activitycollector class as the activity manager, managed by the collection
public class Activitycollector {
public static list<activity> activities = new arraylist<activity> ();
public static void addactivity (activity activity) {
Activities.add (activity);
}
public static void removeactivity (activity activity) {
Activities.remove (activity);
}
public static void Finishall () {
for (Activity activity:activities) {
if (!activity.isfinishing ()) {
Activity.finish ();
}
}
}
}
2) called in the corresponding method of the public parent class of the other class,
public class Baseactivity extends Activity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
LOG.D ("Baseactivity", GetClass (). Getsimplename ());
Activitycollector.addactivity (this);
}
@Override
protected void OnDestroy () {
Super.ondestroy ();
Activitycollector.removeactivity (this);
}
}
3) Just call Activitycollector.finishall () when you want to exit the program directly in an activity.
2.6.3 best practices for initiating activities
1) Add a ACTIONStart () method to the activated activity
public static void ACTIONStart (context context, string data1, String data2) {
Intent Intent = new Intent (context, secondactivity.class);
Intent.putextra ("param1", data1);
Intent.putextra ("param2", data2);
Context.startactivity (Intent);
}
2) You can call the ACTIONStart () method directly when you need to invoke the activity
Button1.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
Secondactivity.actionstart (Firstactivity.this, "data1", "data2");
}
});
The 2nd chapter starts from the view, explores the activity