Android four components of activity and access to network resources of the breakpoint continue to pass

Source: Internet
Author: User

DAY05 data storage and multi-threaded breakpoint Continuation
1. Advantages and disadvantages of data submission to the server two ways
* GET Request
Pros: Easy to use, only need to group the data behind the URL.
Cons: Data is spelled in the back of the URL and is not secure. There is a data length limit.
* POST Request
Pros: Security, data is not spelled in the back of the URL but is written to the server through the stream. Unlimited data length
Cons: Writing trouble.

2. Data submission
* GET Request
1. Need to group the submitted data after the URL
* POST Request
1. Do not need to spell any data
2. The requested data type must be specified, which is a URL-encoded form data. Content-type
3. Stream the data to the server, so you must specify the length of the commit data. Content-length
Important: Set the length of data written to the server: Conn.setrequestproperty ("Content-length", String.valueof (Data.length ()));
Remember to specify that you want to write data to the server: Conn.setdooutput (TRUE);

3. Problem solving and details of Chinese and English garbled characters
Tomcat Default Code table Iso-8859-1
Tomcat defaults to a local code table if it finds a string that is not recognized
byte[] bytes = string.getbytes (String charsetname)
Converts a string to a byte array by the specified encoding, using the Local Code table by default
New string (byte[] bytes, string charsetname)
Converts a byte array to a string by a specified encoding
When the submitted data contains Chinese, the string QQ is encoded according to the code UTF-8
Client
Urlencoder.encode (QQ, "UTF-8");
Service side
String QQ = Request.getparameter ("QQ");//tomcat the code used is iso-8859-1
System.out.println ("QQ:" +new String (Qq.getbytes ("iso-8859-1"), "Utf-8"));

4.httpclient
GET request
1. Open the browser
HttpClient client = new Defaulthttpclient ();
2. Enter the address or data
HttpGet httpget = new HttpGet (path);
3. Hit Enter
HttpResponse response = Client.execute (HttpGet);
Get Status Code
int code = Response.getstatusline (). Getstatuscode ();
Post mode
1. Open the browser
HttpClient client = new Defaulthttpclient ();
2. Enter the address or data
HttpPost HttpPost = new HttpPost (path);
list<namevaluepair> parameters = new arraylist<namevaluepair> ();
Parameters.Add (New Basicnamevaluepair ("QQ", QQ));
Parameters.Add (New Basicnamevaluepair ("pwd", pwd));
Httppost.setentity (new urlencodedformentity (Parameters, "Utf-8"));
3. Hit Enter
HttpResponse response = Client.execute (HttpPost);
Get Status Code
int code = Response.getstatusline (). Getstatuscode ();

5.async-http Open Source Framework
GET request
String Path = "http://192.168.1.103:8080/web/LoginServlet?qq=" +urlencoder.encode (QQ) + "&pwd=" + Urlencoder.encode (PWD);
Asynchttpclient client = new Asynchttpclient ();
Client.get (Path, new Asynchttpresponsehandler ()
POST request
String Path = "Http://192.168.1.103:8080/web/LoginServlet";
Asynchttpclient client = new Asynchttpclient ();
Requestparams params = new Requestparams ();
Params.put ("QQ", QQ);
Params.put ("pwd", PWD);
Client.post (path, params, new Asynchttpresponsehandler ()
Request successfully called Onsuccess () method request failed call OnFailure () method
When the file is uploaded
Put adds a File object

6. Important APIs for multi-threaded downloads
1. Create a blank file locally on the client, the file size is identical to the server
Randomaccessfile RAF = new Randomaccessfile (GetFileName (path), "RW");
Raf.setlength (length);
Raf.close ();

3. The I thread only takes a piece of data from a server
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setrequestproperty ("Range", "bytes=" +startindex+ "-" +endindex);
InputStream is = Conn.getinputstream ();

4. After retrieving data from the I thread, write the data from a location
Randomaccessfile RAF = new Randomaccessfile (GetFileName (path), "RW");
Raf.seek (StartIndex);//The start location of each thread's write file is different.

Ensure synchronous use of synchronize code blocks

The use of FileOutputStream data is not necessarily written to the storage device every time, it is possible to write to the cache of the hard disk, using Randomaccessfile to set the mode to RWD, to ensure that the data written to disk each time
Httputils http = new Httputils ();
First parameter: server address
Second parameter: Where to download
Whether the breakpoint continues to pass
Some of the callback functions that are downloaded
Http.download (Path, "/mnt/sdcard/xxx.exe", True, New requestcallback<file> ()
Download Successful callback: onsuccess (responseinfo<file> arg0)
Callback for Progress update: Onloading (Long, Long, Boolean isuploading)
Download failed callback: OnFailure (HttpException arg0, String arg1)


Day06activity

1. The process of developing an interface in Android
The interface's corresponding class in Android is activity
Create a class to inherit activity, set the layout file of the interface through the Setcontentview (r.layout.xxx) method in the OnCreate method
Configure the activity in the application node of the manifest file Androidmanifest.xml
<activity
Android:name= the full class name of the "com.itheima.mutliuiapp.MainActivity"//configuration class, you must configure
Android:label= "@string/app_name" >//The text displayed on the title bar can not be configured

The application's launch page must be configured with the following Intent-filter node, action and category integral
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

2. How to set activity without title bar
To configure the subject of a single activity node in a manifest file

<activity
Android:theme= "@android: Style/theme.light.notitlebar"
Android:name= "Com.itheima.rpcalc.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>

Configure the theme of the entire application node in the manifest file, after which the app has no title bar for all interfaces

<application
Android:allowbackup= "true"
android:icon= "@drawable/ic_launcher"
Android:label= "@string/app_name"
1. Find the theme of the style file, hold down the CTRL key with the left mouse button click to
Android:theme= "@style/apptheme" >
...
...
</application>

2. Add the corresponding entry in the corresponding style file
<style name= "Apptheme" parent= "Appbasetheme" >
<item name= "Android:windownotitle" >true</item>
</style>

Set in the activity's OnCreate

Requestwindowfeature (Window.feature_no_title);

3. How do I jump through the interface?
Explicitly
Intent Intent = new Intent ();//Intent Object
Intent.setclass (this, secondactivity.class); Secondactivity.class the interface to jump to
StartActivity (Intent);
How to close an activity
Call the Finish () method
Do not use the Thread.Sleep () method in the main thread (UI thread) to get the interface stuck

How to pass data when 4.Activity jumps
First interface, passing data

Intent Intent = new Intent (this, resultactivity.class);

To add the data to be passed, the data types that can be passed are:
1. 8 basic data types and their arrays: byte, short, int, long, float, double, Boolean, Char, and their arrays
2. string and its array: Charsequence and its array, string, and array
3. Collection: Charsequence ArrayList, String ArrayList, Integer arraylist
4. Objects: Serializable, parcelable and their arrays, ArrayList inherited from Parcelable
Intent.putextra (Key,value);

StartActivity (Intent);
Second interface, receiving data

Get the data passed over
Intent Intent = Getintent ();
Intent.getxxxextra ();

5. Explicit Intent & Implicit intent
Explicit intent, you must specify the class name or path name of the activity being opened. Activating components within your own application, using explicit intent, high efficiency

Intent Intent = new Intent ();
Intent.setclassname ("Com.itheima.twointent", "com.itheima.twointent.Activity01");
StartActivity (Intent);
Implicit intent, you only need to specify the action (action) and data. An interface that is typically used to activate another application, or an interface of its own application that needs to be exposed to other application calls, is inefficient.

Intent Intent = new Intent ();
Intent.setaction ("com.itheima.twointent.OPEN02");
Intent.addcategory ("Android.intent.category.DEFAULT");
StartActivity (Intent);
The activity needs to be configured with intent filters if it wants to be implicitly activated.

<activity android:name= "Com.itheima.twointent.Activity02" >
<intent-filter >
<action android:name= "com.itheima.twointent.OPEN02"/>
<category android:name= "Android.intent.category.DEFAULT"/>
</intent-filter>
</activity>

6. Detailed parameters of implicit intent
The Android system finds the most appropriate component to handle this intent based on the action (action), category, data (URI, and data type) set in the implicit intent.
When SetData () and Settype () are to be used together, use the Setdataandtype () method

7. Open the system to apply an interface to the idea
Find the application source code
See what activity the interface is in Logcat
Find the activity in the source manifest file to see its implicit intent
Activates the activity with implicit intent

Click events for 8.ListView entries
Lv.setonitemclicklistener (New Onitemclicklistener () {

method to invoke when the ListView entry is clicked
@Override
public void Onitemclick (adapterview<?> parent, view view, int position, long ID) {
Parent: The ListView
View: view of the line
Position: Click on the first line, starting from 0
}
});

9. Turn on another activity to get data
Prerequisite: A opens B and wants to get the data from B
A call Startactivityforresult

Intent Intent = new Intent (this, contactlistactivity.class);
Startactivityforresult (Intent, 2);
b Interface Settings Data

The data from the current interface is returned to the open my interface.
Intent data = new Intent ();
Data.putextra ("message", message);
Setresult (0, data);
Close the current interface
Finish ();
Returns a interface, the system calls the Onactivityresult () method

@Override
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
if (Requestcode = = 1) {
System.out.println ("We opened the new select SMS interface was closed, the result data returned to here");
if (data! = NULL) {
String message = Data.getstringextra ("message");
Et_message.settext (message);
}
}else if (Requestcode = = 2) {
System.out.println ("We opened the new select contact interface was closed, the result data returned here");
}
Super.onactivityresult (Requestcode, ResultCode, data);
}

10. Request code and result code
Request code: If you call Startactivityforresult () more than once in a, you can use the request code to distinguish the data from other interfaces.
Result code: B can set the result code, to inform a returns whether the result is successful or other information

Life cycle of 11.Activity
The method that an object is bound to execute from creation to garbage collection is called a life cycle method.

OnCreate was created
OnDestroy was destroyed.

OnStart visible

OnStop not visible

Onresume Get Focus

OnPause loses focus

After the Onrestart interface is not visible, return to the interface again

12. Important concepts of the life cycle
Entire lifetime
Full life cycle Oncreate--onstart--onresume--onpause--onstop--ondestroy
Visible lifetime
Visual life cycle OnStart--->onresume---onpause----ondestroy
Foreground lifetime
Front desk life cycle onresume---> OnPause

13. How to handle the screen switch
Specify the screen orientation
Configure android:screenorientation= "Landscape" in the activity of the manifest file (horizontal screen, portrait is vertical screen);
Do not re-create activity when setting screen rotation
Configure android:configchanges= "Keyboardhidden|orientation|screensize" in the activity that corresponds to the manifest file, preferably configured for all three, otherwise it will not fit all models or SDK versions.
The Onconfigurationchanged () method of the activity when the screen is switched on or off

@Override
public void onconfigurationchanged (Configuration newconfig) {
When the screen layout mode is horizontal when the new setting
if (newconfig.orientation = = Activityinfo.screen_orientation_landscape) {
TODO Some actions
}else{
TODO Some actions
}
Super.onconfigurationchanged (Newconfig);

14. Task Stack
Task stack
Task: An application typically consists of multiple activity, and each activity is a task to handle user interaction

Stack: Stack, is overall special data structure (last in first out). Queue if a special data structure (FIFO)

The task stack is used to record the user's operation, the record is the activity open order, after the open interface is closed, if the entire task stack open activity is closed, is the application is exited.

An application typically has only one task stack, but it may also have multiple task stacks

15.Activity Start-up mode
1.standard: Standard Start-up mode
Default Application Scenario
2.singleTop: Single Top mode
If the activity is already open and is at the top of the stack, it will not create a new activity, but instead reuse the activated activity.
To prevent some strange user experience, it is recommended to use a single top mode where multiple instances of the entire task stack can exist.
Application scenario: SMS Sending interface
3.singletask: Single Task stack
Only one instance of the current activity is allowed in the entire task stack
If the activity to be opened already exists in the task stack, reuse the existing activity and empty all other activity on the activity.
Scenario: If an activity consumes memory and CPU resources very much, it is recommended that the activity be made into a singletask mode. Browser's browseractivity
4.singleinstance: Single instance.
Only one instance of the entire mobile operating system exists and is running in its own separate task stack.
Application scenario: Activity on the call screen

Android four components of activity and access to network resources of the breakpoint continue to pass

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.