[Android App Development] 03. Network Programming

Source: Internet
Author: User
Tags message queue

Objective
  • Network programming is not difficult, mainly to master a few points can be.
  • Use HttpURLConnection for network programming.
  • If you are doing network programming on the main thread, Android throws an exception, and another thread is doing the logical operation of the network code.
  • To update the UI interface, use handler and message. Learn about the looper mechanism.
  • Familiarize yourself with GET requests and post requests, and know the difference.
  • Let's take a few examples below to learn more about how to do network programming.

    • Network Picture Viewer
    • Smart-image-view (project), recommended to read the next source
    • Download the image , put it in the cache directory (data/data/"project package Name"/cache), about the cache directory, see [Android Application Development 02]/Use the path API read and write storage read and write files section.
    • page Source Viewer .
    Network Picture Viewer

    Determine the URL of the image

  • Send HTTP request

      URL url = new URL(address);  //获取连接对象,并没有建立连接  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  //设置连接和读取超时  conn.setConnectTimeout(5000);  conn.setReadTimeout(5000);  //设置请求方法,注意必须大写  conn.setRequestMethod("GET");  //建立连接,发送get请求  //conn.connect();  //建立连接,然后获取响应吗,200说明请求成功  conn.getResponseCode();
  • The image of the server is returned to the browser in the form of a stream.

      //拿到服务器返回的输入流  InputStream is = conn.getInputStream();  //把流里的数据读取出来,并构造成图片  Bitmap bm = BitmapFactory.decodeStream(is);
  • Set the picture to the ImageView display

      ImageView iv = (ImageView) findViewById(R.id.iv);  iv.setImageBitmap(bm);
  • Add permissions

The main thread cannot be blocked
    • In Android, the main thread being blocked can cause the app to not refresh the UI interface, not respond to user actions, and the user experience will be very poor

    • The system throws a ANR exception when the main thread is blocked for too long

      • UI stops refreshing, app cannot respond to user action
    • Time-consuming operations should not be performed on the main thread

    • Anr

      • Application Not Responding

      • Apply non-responsive exception

      • When the main thread blocks too long, the ANR will be thrown

    • Any time-consuming operation cannot be written in the main thread

    • Because network interaction is a time-consuming operation, if the speed is slow, the code blocks, so the code for network interaction cannot run on the main thread

    • The main thread is also called the UI thread, because the UI can be refreshed only in the main thread

Only the main thread can refresh the UI
    • The code that refreshes the UI can only run on the main thread, and running on a child thread is not any effect

    • If you need to refresh the UI in a child thread, use the Message Queuing mechanism

Message Queuing
  • Looper once a message is found in the queue, it takes the message out and throws the message to the handler object, handler calls its own Handlemessage method to process the message.

  • The Handlemessage method runs on the main thread

  • When the main thread is created, the message queue and the polling object are created, but the Message Processor object, when it needs to be used, creates itself

  • Summary: As long as Message Queuing has a message, the Handlemessage method calls

  • Child threads If you need to refresh the UI, just send a message to the message queue and trigger the Handlemessage method

  • A child thread sends a message using the SendMessage method of the Processor object

      //消息队列  Handler handler = new Handler(){      //主线程中有一个消息轮询器looper,不断检测消息队列中是否有新消息,如果发现有新消息,自动调用此方法,注意此方法是在主线程中运行的      public void handleMessage(android.os.Message msg) {      }  };
  • Send a message to the message queue in a child thread

      //创建消息对象  Message msg = new Message();  //消息的obj属性可以赋值任何对象,通过这个属性可以携带数据  msg.obj = bm;  //what属性相当于一个标签,用于区分出不同的消息,从而运行不能的代码  msg.what = 1;  //发送消息  handler.sendMessage(msg);
  • Distinguish different messages by switch statements

      public void handleMessage(android.os.Message msg) {      switch (msg.what) {      //如果是1,说明属于请求成功的消息      case 1:          ImageView iv = (ImageView) findViewById(R.id.iv);          Bitmap bm = (Bitmap) msg.obj;          iv.setImageBitmap(bm);          break;      case 2:          Toast.makeText(MainActivity.this, "请求失败", 0).show();          break;      }         }
The ability to add cached images
    • Reads the data from the stream returned by the server and writes it to the local file via the file input stream.

        //1.拿到服务器返回的输入流  InputStream is = conn.getInputStream();  //2.把流里的数据读取出来,并构造成图片  FileOutputStream fos = new FileOutputStream(file);  byte[] b = new byte[1024];  int len = 0;  while((len = is.read(b)) != -1){      fos.write(b, 0, len);  }
    • The code to create the bitmap object is changed to

        Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    • Detects if there is a picture with the same name in the cache before each request is sent, and if so, reads the cache

Get a Web site with open source code
    • This smart Picture SDK is very useful!

    • Github.com

    • Search Smart-image-view on GitHub

    • Download Open Source Project Smart-image-view

    • Label name to write package name when using custom components

        <com.sinyee.babybus.SmartImageView/>
    • Use of Smartimageview

        SmartImageView siv = (SmartImageView) findViewById(R.id.siv);  siv.setImageUrl("http://192.168.1.10:8080/dd.jpg");
HTML Source File Viewer
    • Send a GET request

        URL url = new URL(path);  //获取连接对象  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  //设置连接属性  conn.setRequestMethod("GET");  conn.setConnectTimeout(5000);  conn.setReadTimeout(5000);  //建立连接,获取响应吗  if(conn.getResponseCode() == 200){  }
    • Gets the stream returned by the server and reads the HTML source from the stream

        byte[] b = new byte[1024];  int len = 0;  ByteArrayOutputStream bos = new ByteArrayOutputStream();  while((len = is.read(b)) != -1){      //把读到的字节先写入字节数组输出流中存起来      bos.write(b, 0, len);  }  //把字节数组输出流中的内容转换成字符串  //默认使用utf-8  text = new String(bos.toByteArray());
Handling of garbled characters
    • garbled appearance due to inconsistent server and client code table

        //手动指定码表  text = new String(bos.toByteArray(), "gb2312");
Submit data get method submit data
    • The data submitted by the Get method is directly stitched at the end of the URL

        final String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + name + "&pass=" + pass;
    • Send a GET request, the code is the same as before

        URL url = new URL(path);  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  conn.setRequestMethod("GET");  conn.setReadTimeout(5000);  conn.setConnectTimeout(5000);  if(conn.getResponseCode() == 200){  }
    • The browser will URL-encode the data when it sends the request, and we need to encode the code in Chinese when we write it.

        String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
Post mode submit data
    • The post submission data is written to the server using a stream

    • Two more properties in the protocol header

      • Content-type:application/x-www-form-urlencoded, describing the mimetype of the submitted data

      • CONTENT-LENGTH:32, describing the length of the submitted data

          //给请求头添加post多出来的两个属性  String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass;  conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  conn.setRequestProperty("Content-Length", data.length() + "");
    • Set the stream that allows the post request to be opened

        conn.setDoOutput(true);
    • Gets the output stream of the connection object, writes the data to be submitted to the server in the stream

        OutputStream os = conn.getOutputStream();  os.write(data.getBytes());

This site article is for baby bus SD. Team Original, reproduced must be clearly noted: (the author's official website: Baby bus )
Reprinted from "Baby bus Superdo Team" original link: http://www.cnblogs.com/superdo/p/4890916.html

[Android App Development] 03. Network Programming

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.