Android Basics Summary (iv)

Source: Internet
Author: User

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
    • Anr:application not Response; application unresponsive
    • 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
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

    //消息队列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
    • Code.google.com
    • 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.loopj.android.image.SmartImageView/>
    • Use of Smartimageview

      SmartImageView siv = (SmartImageView) findViewById(R.id.siv);siv.setImageUrl("http://192.168.1.102: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-8text = 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());

Android Basics Summary (iv)

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.