Learn about Android development and load images asynchronously (2) --- use other progress bars

Source: Internet
Author: User

Learn about Android development and load images asynchronously (2) --- use other progress bars

Hello, I'm akira. In the previous section, we talked about asynchronous download using AsyncTask.

It mainly involves some image updates. This time we continue to improve the previous demo.

I don't know if you have found a problem. In the previous section, we left two bugs. 1. If there is no network, the click will collapse.

Let's say the most taboo in software development is crash, which must be solved at the first level in the bug solution.

You have to do this. 2. We will find that the progress is not updated, and the picture is displayed. 3. An extension.

The new library of daimajia is also used as the newest NumberProgressBar of library talents.

1. First, let's solve the problem one by one. First, the first click will crash. Then we need to know why.

That is, why does the click crash? The Source for solving this problem should be viewed 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 if you don't have a network, you won't be able to get the stream. Because I didn't cache the image, that is to say, each click will go to get

 

Without a stream, the inputstream is null, and then a null value is loaded. Naturally, XXX is the root cause. We need to determine whether the obtained stream is null.

But is that true? Obviously, it's not best for us to find out from the source why there is no network or a listener with a network.

When it comes to the Internet, some people will naturally think of wifi. Some people will naturally take it for granted that they want to think of a class called wifiManager. I will satisfy your needs.

Will the wifiManager provide a method for determining whether there is a network?

Let's first look at the wifiManager instantiation.

 

WifiManager manager = (WifiManager) getSystemService (WIFI_SERVICE); wifiState = manager. getWifiState (); // wifi status
The first code applies to many managers, such as inputmanager actvitymanager.

 

The second sentence is whether or not many people want the desired state. Let's continue to look at it.

I also wrote down the status here.

 

Private final int WIFI_STATE_DISABLING = 0; // indicates disabled. Private final int WIFI_STATE_DISABLED = 1; // indicates unavailability. Private final int WIFI_STATE_ENABLING = 2; // indicates that the instance is being started. Private final int WIFI_STATE_ENABLED = 3; // indicates that the instance is ready. Private final int WIFI_STATE_UNKNOWN = 4; // indicates the unknown status.
What do you think of when you see this? The first thing I think of is that my own network attached vro. This Nima is a network loading process and it is still wifi.

 

We found that the most reliable startup does not seem to meet our needs. At this time, some people may begin to doubt that life has forgotten to say

If you want to monitor the status of wifi, you need to add permissions.

As follows:

 

 
     
  
 

But the fundamental problem persists.

 

So don't doubt it. Let's start from scratch.

At this time, someone mentioned ConnectivityManager connector? This is not the case.

Let's take a look.

 

ConnectivityManager cManager =  (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);NetworkInfo mInfo =  cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

Yahoo !!! Pretty good. It looks very reliable. Continue further research.

 

 

mInfo.isAvailable()

This api is to tell you whether the Network is available. The previous type has a lot of options. Here, it means that wifi is simple, so I won't go to the official website.

 

Then, what do you want to do? to judge whether the current network is available, click "nono". What should I do if the url is empty? Considering the rigor and code robustness, let's take it into consideration.

Judgment to be performed

And set whether the button is clickable.

 

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,bar0000.exe cute (url) ;}});} else {downBtn. setClickable (false); downBtn. setOnClickListener (null); Toast. makeText (MainActivity. this, no wifi, Toast. LENGTH_SHORT ). show ();}


 

Okay, the external logic is complete. 1 crash is solved.

PS: Actually, the solution here is very unprofessional. Generally, in a formal project, we will write a broadcast to accept it and check whether the Network is available.

When Broadcasting

2. For the update progress, I am very clear that if I want to update a progress, I must know

The total progress, the current progress, and the method for notifying them to click "swipe"

OK. Check the key code.

Int totalLength; // total length URL imageUrl = null; // image 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 statement notifies upXXX of the update progress publishProgress (int) (count/(float) totalLength) * 100);} byte [] data = baos. toByteArray (); // declare the byte array downloadImg = BitmapFactory. decodeByteArray (data, 0, data. length); return OK ;}}

Here, we use a stream to write and then get it from fluency when loading, and the total length has a getContentLength method.

 

The last refresh to see the publishProgress is the refresh method.

 

@Override    protected void onProgressUpdate(Integer... progress) {          super.onProgressUpdate(progress[0]);          mBar.setProgress(progress[0]);          Log.e(akira,progress[0]+...);    }

Refresh here. Note that progress is a variable array.

 

Below I printed it with log. It doesn't matter if it's not printed.

Last post method not modified

3

First, we need to find the daimajia library.

The following url

Https://github.com/daimajia/NumberProgressBar

The written information is very, very clear.

Eclipse and andriodstudio both have their own import methods.

If you find that you cannot find the style after import, You can manually copy the style in it.

The following is my layout code.

 

     
  
       
        
         
      
     
    
  
 

Here, you will find that my M namespace is not used as Mao, because I use a style to represent all the things.

 

No, you see.

 

 

Here you will find that he defines the width and height of max progress color and font color size, etc.

 

So you can use it directly.

Main Code Modification

 

Public class MainActivity extends Activity {String url; private final int WIFI_STATE_DISABLING = 0; // indicates disabled. Private final int WIFI_STATE_DISABLED = 1; // indicates unavailability. Private final int WIFI_STATE_ENABLING = 2; // indicates that the instance is being started. Private final int WIFI_STATE_ENABLED = 3; // indicates that the instance is ready. Private final int WIFI_STATE_UNKNOWN = 4; // indicates the unknown status. 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 I MageView img = (ImageView) findViewById (R. id. img); final WifiManager manager = (WifiManager) getSystemService (WIFI_SERVICE); int wifiState = manager. getWifiState (); // wifi status 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 view) {new imagedownloadtask(mainactivity.this,img,bar0000.exe cute (url) ;}});} else {downBtn. setClickable (false); downBtn. setOnClickListener (null); Toast. makeText (MainActivity. this, no wifi, Toast. LENGTH_SHORT ). show ();}}}

ImageDownXXX code modification

 

 

/*** Created by akira on 2015/1/27. */public class ImageDownloadTask extends AsyncTask
 
  
{Private Bitmap downloadImg; private NumberProgressBar mBar; private Context mContext; private ImageView netImageView; private int perPro; // incremental progress public ImageDownloadTask (Context context, ImageView imageView, NumberProgressBar) {this. mContext = context; this. netImageView = imageView; this. mBar = bar; mBar. incrementProgressBy (perPro);} @ Override protected void onPreExecute () {// super. onPreExe Cute (); mBar. setVisibility (View. VISIBLE) ;}@ Override protected String doInBackground (String... params) {int totalLength; // total length URL imageUrl = null; // image 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. ge TInputStream (); 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 statement notifies upXXX of the update progress publishProgress (int) (count/(float) totalLength) * 100);} byte [] data = baos. toByteArray (); // declare the 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, loaded, Toast. LENGTH_LONG ). show ();}}
 
Can't you run it?

 


 

Why are you not clear? Onemoretime!

Okay, three questions. Next time, let's dynamically set the progress style and write our own progressbar.

 

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.