Android development-Get network images and read progress bars

Source: Internet
Author: User

This chapter describes how to write a program to read network images, enable a function to read an image on the server, and then download it to a local program. This program uses multiple threads to read network images, including automatic judgment of cache files and progress bars. Not to mention anything. I wrote the implementation process into the program as a comment, which is completely complete. Hope to help beginners!

 

1. Read the progress bar

2. The image is successfully read.

 

1. First, Activity

Package CN. itcast. PIC; import android. app. activity; import android. app. progressdialog; import android. graphics. bitmap; import android. OS. bundle; import android. OS. handler; import android. view. view; import android. widget. imageview; import android. widget. textview; import android. widget. toast; public class mainactivity extends activity {private textview addresset; private imageview imageiv; private handler Han Dler = new handler (); // create handler private progressdialog dialog; private imageservice service; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // 1. Obtain the ID addresset = (textview) this of the dialog box. findviewbyid (R. id. addresset); imageiv = (imageview) This. findviewbyid (R. id. imageiv); service = new imageservice (this);} public void onclick (Vie W v) {// put the image in a new thread for reading. new thread () {// create a new thread public void run () {try {string address = addresset. gettext (). tostring (); handler. post (New runnable () {// here an anonymous internal class is used. runnable automatically sends the message to the handler created and processed by the main thread, and the main thread automatically updates the message. Public void run () {dialog = new progressdialog (mainactivity. this); dialog. setprogressstyle (progressdialog. style_spinner); // sets the progress bar Style dialog. setmessage ("Please wait... "); dialog. setcancelable (false); // determines whether to cancel the progress bar dialog. show () ;}}); // perform final bitmap image = service in the new thread because network operations are time-consuming. getimage (Address); handler. post (New runnable () {public void run () {dialog. dismiss (); imageiv. setimagebitmap (image); // The interface for updating new threads. To use handler});} catch (exception e) {e. printstacktrace (); toast. maketext (getapplicationcontext (), "the server is busy. Please try again later! ", 0). Show () ;}}. start ();}}

2. Then the service that reads the image

Package CN. itcast. PIC; import Java. io. file; import Java. io. fileoutputstream; import java.net. httpurlconnection; import java.net. URL; import java.net. urlencoder; import android. accounts. networkerrorexception; import android. content. context; import android. graphics. bitmap; import android. graphics. bitmap. compressformat; import android. graphics. bitmapfactory; public class imageservice {private context; P Ublic imageservice (context) {super (); this. context = context;} public bitmap getimage (string address) throws exception {// 1. encapsulate the URL object URL url = new URL (Address); httpurlconnection conn = (httpurlconnection) URL through a URL object. openconnection (); Conn. setreadtimeout (3000); // 2. determine whether there is a cached file cachefile = new file (context. getcachedir (), urlencoder. encode (Address); // cache file if (cachefile. exists () // judge Indicates whether the cache conn exists. setifmodifiedsince (cachefile. lastmodified (); // last modification time of the cached file to be sent // 3. obtain the status code and determine the next operation based on the status. Reading files? Write cache. When writing cache, remember to use multiple threads int code = Conn. getresponsecode (); If (code = 200) {byte [] DATA = util. read (Conn. getinputstream (); bitmap Bm = bitmapfactory. decodebytearray (data, 0, Data. length); // convert to image weitecache (cachefile, BM); Return bm;} else if (code = 304) {return bitmapfactory. decodefile (cachefile. getabsolutepath (); // read local data and convert it to an image for display} // if it fails, throw an exception and display throw new networkerrorexception ("Access Server Error: "+ code);} // 4. write cache file private void weitecache (final file cachefile, final bitmap BM) {// use a new thread to write, the advantage is that when the page is opened, it will not wait for the new thread () {public void run () {try {fileoutputstream Fos = new fileoutputstream (cachefile); BM because of the write cache. compress (compressformat. JPEG, 100, FOS); // The specified format is stored in the local FOS. close () ;}catch (exception e) {Throw new runtimeexception (e );}}}. start ();}}

3. A tool class for reading network files

package cn.itcast.pic;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class Util {    public static byte[] read(InputStream in) throws IOException {        ByteArrayOutputStream baos = new ByteArrayOutputStream();        byte[] buffer = new byte[1024];        int len;        while ((len = in.read(buffer)) != -1)            baos.write(buffer, 0, len);        baos.close();        byte[] data = baos.toByteArray();        return data;    }    }

4. Main Interface XML

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <EditText            android:id="@+id/addressET"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:inputType="textEmailAddress" >            <requestFocus />        </EditText>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="onClick"            android:text=" GO " />    </LinearLayout>    <ImageView        android:id="@+id/imageIV"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>
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.