Learning andriod Development Asynchronous loading pictures (ii)---use other progress bars

Source: Internet
Author: User

Hello, I'm Akira. We talked about using the Asynctask class for asynchronous downloads

Mainly involves some images of the update this time we continue the previous demo improvements.

Do not know if you have found a problem in the previous section we left two bug 1 in the absence of network conditions click will collapse

We say that the most taboo of software development is crash and this is the first level in the bug solution to be solved so this problem

We have to take care of 2. We'll find that the progress is not updated and the picture is displayed 3 is an extension this time I will bring

Daimajia's new library is also used to make Kukaoda's latest work Numberprogressbar.

1 first of all, let's solve the problem one by one the first click will crash then we need to know why

That is why the click will crash to solve the source of the problem to be seen from the original code

The following code

try {              HttpURLConnection connection = (httpurlconnection) imageurl.openconnection ();              Connection.setdoinput (true);              Connection.connect ();              InputStream =  connection.getinputstream ();              downloadimg =  Bitmapfactory.decodestream (inputstream);            }
In fact, we can see at a glance that you don't get a stream if you don't have a net, because I didn't do the picture cache, which means that every click goes to get.

No flow will cause InputStream to be null and then to load a null naturally on XXX so we find the source is to determine whether the resulting stream is null

But it's just that it's obviously not our best to find out from the source why there's no net or a Network Monitor.

When it comes to the web, people naturally think WiFi says WiFi is a natural way to think of a class called Wifimanager good I will meet your needs

To parse the next Wifimanager will not provide a way to determine whether there is a net

First look at the instantiation of the Wifimanager

Wifimanager manager = (Wifimanager) getsystemservice (wifi_service); wifistate =  manager.getwifistate ();//wifi status
The first code is for many managers such as InputManager Actvitymanager and so on.

And the second sentence is what a lot of people want, is that what they want? We keep looking down.

I also wrote down the status of this.

Private  Final int  wifi_state_disabling = 0;//indicates deactivation.    private  Final int  wifi_state_disabled  = 1;//indicates not available.    private  Final int  wifi_state_enabling  = 2;//indicates startup.    private  Final int  wifi_state_enabled   = 3;//indicates readiness.    private  Final int  Wifi_state_unknown   = 4;//indicates an unknown state.
What would you think of when you saw this? My first thought was my own network router. This is a network loading process and still WiFi

We find that the most reliable start-up does not seem to meet our needs at this time some people may start to doubt that life forgot to say

If you want to monitor the status of WiFi, you need to add permission.

As follows

<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>    <uses-permission android: Name= "Android.permission.ACCESS_NETWORK_STATE"/>

But the fundamental problem is still unsolved.

So don't doubt it, let's start over.

At this time, someone mentioned Connectivitymanager, eh? This is not a good line.

Let's see.

Connectivitymanager Cmanager =  (Connectivitymanager) Getsystemservice (Connectivity_service); Networkinfo mInfo =  cmanager.getnetworkinfo (connectivitymanager.type_wifi);

yahoo!!! Yes, looks pretty good, keep digging.

Minfo.isavailable ()

This API is to tell you whether the network is available in front of the type has a lot of here said the WiFi is relatively simple we don't go to the official website to see

And then what do you want to do is to determine if the current network is available click Nono in case the URL is empty take into account rigor and code robustness we

To make and judge.

And go to set whether the button is available.

Button downbtn = (button) Findviewbyid (R.ID.DOWNBTN);        if (minfo.isavailable () &&! Textutils.isempty (URL)) {                downbtn.setclickable (true);                Downbtn.setonclicklistener (New View.onclicklistener () {                @Override public                void OnClick (view view) {                    new Imagedownloadtask (Mainactivity.this,img,bar). Execute (URL);}}             );        else{            downbtn.setclickable (false);            Downbtn.setonclicklistener (null);            Toast.maketext (Mainactivity.this, "Currently no WiFi", Toast.length_short). Show ();        


OK, we're done with the logic outside. 1 crash

PS: In fact, the solution of the network is not professional generally in the formal project we will write a broadcast to observe whether the network can be used to put it to the future

I'll talk about it on the radio.

2 about update Progress first, I'm pretty clear. If I'm going to update a progress I'm sure I need to know a

Overall progress A current progress there is a way to inform its brush

OK See the key code

int totallength;//total length url imageUrl = null;//picture url int length =-1;        InputStream inputstream = null;            try {imageUrl = new URL (params[0]);            HttpURLConnection connection = (httpurlconnection) imageurl.openconnection ();            Connection.setdoinput (TRUE);            Connection.connect ();            InputStream = Connection.getinputstream ();            Totallength = Connection.getcontentlength ();                if (inputstream!=null) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();                byte[] buffer = new byte[1024];                int count = 0;                    while (length = inputstream.read (buffer))! =-1) {baos.write (buffer, 0, length);                    Count + = length;                This notification upxxx update Progress publishprogress ((int) ((Count/(float) totallength) * 100)); } byte[] Data=baos.tobytearray ();//declare byte array DownloadimG=bitmapfactory.decodebytearray (data, 0, data. length);            return "OK"; }        }

Here we use a flow to write and then load the time from the fluency to get the total length has a getcontentlength method

Last refresh, see that publishprogress, that's the Refresh method.

@Override    protected void onprogressupdate (Integer ... progress) {          super.onprogressupdate (progress[0]);          Mbar.setprogress (Progress[0]);          LOG.E ("Akira", progress[0]+ "...");    

Also here to refresh note that progress is a mutable array

Below I use the log print does not print does not matter

Last Post Method not modified

3

Daimajia's library first we need to find Daimajia's library.

The following URL

Https://github.com/daimajia/NumberProgressBar

It's very, very, very, very clearly written.

Both Eclipse and Andriodstudio have their own way of importing and not repeating it.

Some if you find that you can't find a style after importing, you can manually copy the style inside it.

Here's my layout code.

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "xmlns:custom=" Http://schemas.android.com/apk/res-auto "android:layout_width=" Match_ Parent "android:layout_height=" Match_parent "tools:context=". Mainactivity "> <textview android:id=" @+id/hello "android:text=" @string/hello_world "Android:lay Out_width= "Wrap_content" android:layout_height= "wrap_content"/> <button android:layout_below= "@id/ Hello "android:id=" @+id/downbtn "android:text=" Down "android:textsize=" 20SP "Android:textcolor = "@android: Color/black" android:layout_width= "match_parent" android:layout_height= "wrap_content"/> &L T;imageview android:layout_centerinparent= "true" android:layout_below= "@id/downbtn" android:id= "@+id/ IMG "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android: scaletype= "Fitxy" android:visibility= "Gone"/> <com.daimajia.numberprogressbar.numberprogressbar style= "@style/numberprogressbar_funny_orange" android:id= "@+id/bar" android:layout_centerinparent= "Tru         E "android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:visibility=" Gone " /> <!--<progressbar android:id= "@+id/bar" android:layout_centerinparent= "true" an Droid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:visibility= "Gone"/&gt ;--></relativelayout>

You'll find out that my custom namespace is not used for hair because I've got some things in a style that represent

No, you see.

<style name= "Numberprogressbar_funny_orange" >        <item name= "Android:layout_height" >wrap_content </item>        <item name= "android:layout_width" >match_parent</item>        <item name= "Max" > 100</item>        <item name= "Progress" >0</item>        <item name= "Progress_unreached_color" > #CCCCCC </item>        <item name= "Progress_reached_color" > #FF530D </item>        <item name= " Progress_text_size ">10sp</item>        <item name=" Progress_text_color "> #FF530D </item>        <item name= "Progress_reached_bar_height" >1.5dp</item>        <item name= "Progress_unreached_bar_ Height ">0.75dp</item>    </style>

You'll find that he defines the max progress color, font color size, and so on.

So you can use it directly.

Main code Modification

public class Mainactivity extends Activity {String URL;    Private final int wifi_state_disabling = 0;//indicates deactivation. Private final int wifi_state_disabled = 1;    Indicates not available. Private final int wifi_state_enabling = 2;    Represents the startup. Private final int wifi_state_enabled = 3;    Indicates readiness. Private final int wifi_state_unknown = 4;    Indicates an unknown state.    Private Networkinfo MInfo;    Private Connectivitymanager Cmanager;    Private Button downbtn;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        if (textutils.isempty (URL)) url = "Http://bbra.cn/Uploadfiles/imgs/20110303/fengjin/015.jpg";        Final Numberprogressbar bar = (Numberprogressbar) Findviewbyid (R.id.bar);        Final ImageView img = (ImageView) Findviewbyid (r.id.img);        Final Wifimanager manager = (Wifimanager) getsystemservice (Wifi_service); int wifistate = Manager.getwifistate ();//wiFi state Cmanager = (Connectivitymanager) getsystemservice (Connectivity_service);        MInfo = Cmanager.getnetworkinfo (Connectivitymanager.type_wifi);        DOWNBTN = (Button) Findviewbyid (R.ID.DOWNBTN); if (minfo.isavailable () &&!                Textutils.isempty (URL)) {downbtn.setclickable (true); Downbtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View V                Iew) {new Imagedownloadtask (Mainactivity.this,img,bar). Execute (URL);        }             });            }else{downbtn.setclickable (FALSE);            Downbtn.setonclicklistener (NULL);        Toast.maketext (Mainactivity.this, "Currently no WiFi", Toast.length_short). Show (); }    }}

IMAGEDOWNXXX Code Modification

/** * Created by Akira on 2015/1/27.    */public class Imagedownloadtask extends asynctask<string,integer,string> {private Bitmap downloadimg;    Private Numberprogressbar MBar;    Private Context Mcontext;    Private ImageView Netimageview;        private int perpro;//Incremental Progress Public imagedownloadtask (context context, ImageView ImageView, Numberprogressbar bar) {        This.mcontext = context;        This.netimageview = ImageView;        This.mbar = bar;    Mbar.incrementprogressby (Perpro);        } @Override protected void OnPreExecute () {//Super.onpreexecute ();    Mbar.setvisibility (view.visible); } @Override protected String Doinbackground (String ... params) {int totallength;//total length URL imageUrl =        null;//the URL of the picture int length =-1;        InputStream inputstream = null;            try {imageUrl = new URL (params[0]);            HttpURLConnection connection = (httpurlconnection) imageurl.openconnection (); Connection.setDoinput (TRUE);            Connection.connect ();            InputStream = Connection.getinputstream ();            Totallength = Connection.getcontentlength ();                if (inputstream!=null) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();                byte[] buffer = new byte[1024];                int count = 0;                    while (length = inputstream.read (buffer))! =-1) {baos.write (buffer, 0, length);                    Count + = length;                This notification upxxx update Progress publishprogress ((int) ((Count/(float) totallength) * 100));  } byte[] Data=baos.tobytearray ();//declare byte array downloadimg=bitmapfactory.decodebytearray (data, 0, Data.                length);            return "OK";        }} catch (Malformedurlexception e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); }finally {try {InpuTstream.close ();            } catch (IOException e) {e.printstacktrace ();    }} return null;          } @Override protected void Onprogressupdate (Integer ... progress) {super.onprogressupdate (progress[0]);          Mbar.setprogress (Progress[0]);    LOG.E ("Akira", progress[0]+ "...");         } @Override protected void OnPostExecute (String result) {//Super.onpostexecute (s);         Mbar.setvisibility (View.gone);         Netimageview.setvisibility (view.visible);         Netimageview.setimagebitmap (DOWNLOADIMG);    Toast.maketext (Mcontext, "Loading complete", Toast.length_long). Show (); }}
Can you run and run?



What, you didn't look clear? It's okay onemoretime!


OK Three questions okay, let's do it next time. Dynamically set progress style and write your own ProgressBar

You guys, next time, bye!

Learning andriod Development Asynchronous loading pictures (ii)---use other progress bars

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.