Network programming in Android is the core technology of Android development, so learning network programming in Android is very important, very important, very important!
Firstly, the core knowledge points used in this paper are explained.
1. child thread
Before Android 4.0, access to the network could be written directly to the main thread. After Android 4.0, Google officially stipulated that access to the network must be written to sub-threads.
2. HttpURLConnection class
This class is the one that sends HTTP requests on Android.
3. Reading and Writing of Documents
4. Use of Handler (Key and Difficult Points in Android)
When Activity is created, message queue objects and poller objects are created in the main thread. We need to create a message processing object (Handler) ourselves, send messages through Handler in the sub-thread (usually: Handler.sendMessage(msg); and call handleMessage() method to process messages in the main thread's Handler.
The results achieved are as follows:
(1) First of all, I built a Tomcat server on my computer. My picture was downloaded from my Tomcat server.
The image placement directory is: under the installation path / Tomcat 7.0/webapps/ROOT/xiao.jpg
Tip: After starting Tomcat, type http://localhost:8080/xiao.jpg in the browser to see if it can be accessed.
Note: Tomcat's website accessing the computer in the simulator is 10.0.2.2. You can test http://10.0.2.2:8080/xiao.jpg with the browser in the simulator.
Never use 127.0.0.1 to access the computer in the simulator. It is the simulator itself that uses 127.0.0.1 to access the computer. Access to the computer that installs the simulator in the simulator should use: 10.0.2.2. 10.0.2.2 is the specific IP set by the simulator for the computer, which is the alias of your computer.
(2) activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.imageviewer.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="click" android:text="display picture"/> <ImageView android:id="@+id/im" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
(3) MainActivity.java code
(4) Android Manifest. XML filepackage com.example.imageviewer; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { private ImageView imageView; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: Toast.makeText(MainActivity.this, "The request failed!", Toast.LENGTH_SHORT).show(); break; case 1: imageView.setImageBitmap((Bitmap) msg.obj); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) this.findViewById(R.id.im); } public void click(View v) { //Download pictures //1. Determining the Web Site final String path = "http://10.0.2.2:8080/xiao.jpg"; //Access to the address of the computer installed with the simulator //Read the data from the stream returned by the server, write the data to the local file, and cache it. final File file = new File(getCacheDir(), getFileName(path)); //Determine if the file exists in the cache if (file.exists()) { //If the cache exists, read the picture from the cache Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); imageView.setImageBitmap(bitmap); } else { //If the cache does not exist, download the picture from the network Thread th = new Thread() { @Override public void run() { super.run(); //2. Encapsulating a Web Site into a Url Object try { URL url = new URL(path); //3. Obtain the link object between client and server, and no connection has been established at this time. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //4. Initialization of Connection Objects //Set the request method, pay attention to capitalization conn.setRequestMethod("GET"); //Setting connection timeout conn.setConnectTimeout(5000); //Setting Read Timeout conn.setReadTimeout(5000); //Send a request to establish a connection with the server conn.connect(); //If the response code is 200, the request is successful if (conn.getResponseCode() == 200) { //Get the midstream in the server response header, where the data is the data requested by the client InputStream in = conn.getInputStream(); //Caching data into memory FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) != -1) { fos.write(b, 0, len); } fos.close(); Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); Message msg = new Message(); msg.what = 1; msg.obj = bitmap; mHandler.sendMessage(msg); } else { Message msg = mHandler.obtainMessage(); msg.what = 0; mHandler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } }; th.start(); } } public String getFileName(String path) { int index = path.lastIndexOf("/"); return path.substring(index + 1); } }
Because you need to access the network, you need to add permissions to the configuration file that can access the network.<uses-permission android:name="android.permission.INTERNET"></uses-permission>