Android downloads images with progress bars and displays images

Source: Internet
Author: User

I am not busy recently and feel unfamiliar with progressBar, so I decided to write an example of downloading a file with a progress bar! The following code downloads an image and displays the image:
Layout file layout is simple:
[Html]
<? 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">
 
<Button
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: id = "@ + id/bt"
Android: text = "start downloading files"/>
 
<ProgressBar
Android: id = "@ + id/pb"
Android: layout_width = "fill_parent"
Style = "? Android: attr/progressBarStyleHorizontal"
Android: layout_height = "wrap_content"/>
<ImageView
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: id = "@ + id/img"/>
</LinearLayout>
 
A file tool class:
 
[Java]
Package com. spring. sky. download;
 
Import java. io. File;
 
Import android. content. Context;
Import android. OS. Environment;
Import android. util. Log;
/**
* File Tool
* @ Author spring sky
* Email: vipa1888@163.com
* QQ: 840950105
* Name: Shi mingzheng
*
*/
Public class FileUtil {
/**
* Verify the SDcard status
* @ Return boolean
*/
Public static boolean checkSDCard ()
{
If (android. OS. Environment. getExternalStorageState (). equals (android. OS. Environment. MEDIA_MOUNTED ))
{
Return true;
} Else {
Return false;
}
}
/**
* Save the file to the directory.
* @ Param context
* @ Return: directory to which the file is saved
*/
Public static String setMkdir (Context context)
{
String filePath;
If (checkSDCard ())
{
FilePath = Environment. getExternalStorageDirectory () + File. separator + "myfile ";
} Else {
FilePath = context. getCacheDir (). getAbsolutePath () + File. separator + "myfile ";
}
File file = new File (filePath );
If (! File. exists ())
{
Boolean B = file. mkdirs ();
Log. e ("file", "file creation does not exist" + B );
} Else {
Log. e ("file", "file exists ");
}
Return filePath;
}
}
 
 
The following is the logic processing on the interface:
 
 
[Java]
Package com. spring. sky. download;
 
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileNotFoundException;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java.net. URL;
Import java.net. URLConnection;
 
Import android. app. Activity;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. OS. Message;
Import android. util. Log;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. ImageView;
Import android. widget. ProgressBar;
Import android. widget. Toast;
/**
* File Download Interface
* @ Author spring sky
* Email: vipa1888@163.com
* QQ: 840950105
* Name: Shi mingzheng
*
*/
Public class IndexActivity extends Activity implements OnClickListener {
Private static final int DOWNLOAD_PREPARE = 0;
Private static final int DOWNLOAD_WORK = 1;
Private static final int DOWNLOAD_ OK = 2;
Private static final int DOWNLOAD_ERROR = 3;
Private static final String TAG = "IndexActivity ";
Private Button bt;
Private ProgressBar pb;
Private ImageView img;
/**
* Files to be downloaded
* Note: Use a host on the simulator that cannot resolve a domain name
*/
Private String url = "http: // 61.155.165.32/shuixiyue/pic/item/f141247490d0e96fb251b963.jpg ";
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Bt = (Button) this. findViewById (R. id. bt );
Bt. setOnClickListener (this );
Pb = (ProgressBar) this. findViewById (R. id. pb );
Pb. setVisibility (ProgressBar. INVISIBLE );
Img = (ImageView) this. findViewById (R. id. img );
}

/**
* Button click event
*/
@ Override
Public void onClick (View v ){
Switch (v. getId ()){
Case R. id. bt:
Toast. makeText (this, "start downloading files", Toast. LENGTH_SHORT). show ();
New Thread (){
@ Override
Public void run (){
DownloadFile ();
Super. run ();
}
}. Start ();
Break;
}
}
/**
* File Download
*/
Private void downloadFile ()
{
Try {
URL u = new URL (url );
URLConnection conn = u. openConnection ();
Conn. connect ();
InputStream is = conn. getInputStream ();
FileSize = conn. getContentLength ();
If (fileSize <1 | is = null)
{
SendMessage (DOWNLOAD_ERROR );
} Else {
SendMessage (DOWNLOAD_PREPARE );
FileOutputStream fos = new FileOutputStream (getPath ());
Byte [] bytes = new byte [1, 1024];
Int len =-1;
While (len = is. read (bytes ))! =-1)
{
Fos. write (bytes, 0, len );
DownloadSize + = len;
SendMessage (DOWNLOAD_WORK );
}
SendMessage (DOWNLOAD_ OK );
Is. close ();
Fos. close ();
}
} Catch (Exception e ){
SendMessage (DOWNLOAD_ERROR );
E. printStackTrace ();
}
}
/**
* Total File Size
*/
Int fileSize = 0;
/**
* Downloaded size
*/
Int downloadSize = 0;
/**
* Handler processes messages
*/
Private Handler handler = new Handler (){
 
@ Override
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case DOWNLOAD_PREPARE:
Toast. makeText (IndexActivity. this, "Download Preparation", Toast. LENGTH_SHORT). show ();
Pb. setVisibility (ProgressBar. VISIBLE );
Log. e (TAG, "Total:" + fileSize );
Pb. setMax (fileSize );
Break;
Case DOWNLOAD_WORK:
Log. e (TAG, "downloaded:" + downloadSize );
Pb. setProgress (downloadSize );
Int res = downloadSize * 100/fileSize;
Bt. setText ("downloaded:" + res + "% ");
Break;
Case DOWNLOAD_ OK:
Try {
If (getPath (). endsWith (". jpg") | getPath (). endsWith (". png ")){
FileInputStream FCM = new FileInputStream (getPath ());
Img. setImageBitmap (BitmapFactory. decodeStream (FCM ));
}
DownloadSize = 0;
FileSize = 0;
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
Toast. makeText (IndexActivity. this, "download completed", Toast. LENGTH_SHORT). show ();
Break;
Case DOWNLOAD_ERROR:
Toast. makeText (IndexActivity. this, "Download error", Toast. LENGTH_SHORT). show ();
Break;
}
Super. handleMessage (msg );
}
};
/**
* Obtain the file storage path.
* @ Return
* @ Throws IOException
*/
Private String getPath () throws IOException
{
String path = FileUtil. setMkdir (this) + File. separator + url. substring (url. lastIndexOf ("/") + 1 );
Return path;
}
/**
* Send a message to hand www.2cto.com
* @ Param what
*/
Private void sendMessage (int what)
{
Message m = new Message ();
M. what = what;
Handler. sendMessage (m );
}
}
 
The above is the complete code for downloading an object. If you need this code, you can copy it directly! If you have any questions during use, contact me!
 
From spring sky

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.