progress-bar and downloading image with percentage
Step1 .==> View => CircularProgressBar.java
package com.example.progressbarwithimagedwonload;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class CircularProgressBar extends View {
private int mDuration = 100;
private int mProgress = 30;
private Paint mPaint = new Paint();
private RectF mRectF = new RectF();
private int mBackgroundColor = Color.LTGRAY;
private int mPrimaryColor = Color.parseColor("#6DCAEC");
private float mStrokeWidth = 10F;
public interface OnProgressChangeListener {
public void onChange(int duration, int progress, float rate);
}
private OnProgressChangeListener mOnChangeListener;
public void setOnProgressChangeListener(OnProgressChangeListener l) {
mOnChangeListener = l;
}
public CircularProgressBar(Context context) {
super(context);
}
public CircularProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setMax(int max) {
if (max < 0) {
max = 0;
}
mDuration = max;
}
public int getMax() {
return mDuration;
}
public void setProgress(int progress) {
if (progress > mDuration) {
progress = mDuration;
}
mProgress = progress;
if (mOnChangeListener != null) {
mOnChangeListener
.onChange(mDuration, progress, getRateOfProgress());
}
invalidate();
}
public int getProgress() {
return mProgress;
}
public void setBackgroundColor(int color) {
mBackgroundColor = color;
}
public void setPrimaryColor(int color) {
mPrimaryColor = color;
}
public void setCircleWidth(float width) {
mStrokeWidth = width;
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
int halfWidth = getWidth() / 2;
int halfHeight = getHeight() / 2;
int radius = halfWidth < halfHeight ? halfWidth : halfHeight;
float halfStrokeWidth = mStrokeWidth / 2;
mPaint.setColor(mBackgroundColor);
mPaint.setDither(true);
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(halfWidth, halfHeight, radius - halfStrokeWidth,
mPaint);
mPaint.setColor(mPrimaryColor);
mRectF.top = halfHeight - radius + halfStrokeWidth;
mRectF.bottom = halfHeight + radius - halfStrokeWidth;
mRectF.left = halfWidth - radius + halfStrokeWidth;
mRectF.right = halfWidth + radius - halfStrokeWidth;
canvas.drawArc(mRectF, -90, getRateOfProgress() * 360, false, mPaint);
canvas.save();
}
private float getRateOfProgress() {
return (float) mProgress / mDuration;
}
}
Step 2 ==> Activity ====>MainActivity.java
package com.example.progressbarwithimagedwonload;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private int progress = 0;
ImageView image_dwonloadimage;
Button btn_download;
private static String file_url = "http://chandandroid.uphero.com/tema_upload/uploads/chandru.jpg";
private RateTextCircularProgressBar mRateTextCircularProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image_dwonloadimage = (ImageView) findViewById(R.id.image_donwload);
mRateTextCircularProgressBar = (RateTextCircularProgressBar) findViewById(R.id.rate_progress_bar);
mRateTextCircularProgressBar.setMax(100);
mRateTextCircularProgressBar.clearAnimation();
mRateTextCircularProgressBar.getCircularProgressBar()
.setCircleWidth(20);
btn_download = (Button) findViewById(R.id.btn_download);
btn_download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadFileFromURL().execute(file_url);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mRateTextCircularProgressBar.setProgress(msg.what);
if (progress >= 100) {
image_dwonloadimage.setVisibility(View.VISIBLE);
}
mHandler.sendEmptyMessageDelayed(progress++, 100);
super.handleMessage(msg);
}
};
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// /here getting file length;
int lengthoffile = connection.getContentLength();
// input stream to read file with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// write stream to write file.
String file_path = "/sdcard/CHANDRU";
File file = new File(file_path);
if (!file.exists()) {
file.mkdirs();
}
OutputStream output = new FileOutputStream(file_path
+ "/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthoffile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/CHANDRU/downloadedfile.jpg";
// setting downloaded into image view
image_dwonloadimage.setImageDrawable(Drawable
.createFromPath(imagePath));
}
protected void onProgressUpdate(String... progress) {
// / setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
mHandler.sendEmptyMessageDelayed(Integer.parseInt(progress[0]), 100);
mRateTextCircularProgressBar.setVisibility(View.VISIBLE);
}
}
}
package com.example.progressbarwithimagedwonload;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.example.progressbarwithimagedwonload.CircularProgressBar.OnProgressChangeListener;
/**
*
* @author kalidoss rajendran
*/
public class RateTextCircularProgressBar extends FrameLayout implements OnProgressChangeListener {
private CircularProgressBar mCircularProgressBar;
private TextView mRateText;
public RateTextCircularProgressBar(Context context) {
super(context);
init();
}
public RateTextCircularProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mCircularProgressBar = new CircularProgressBar(getContext());
this.addView(mCircularProgressBar);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
mCircularProgressBar.setLayoutParams(lp);
mRateText = new TextView(getContext());
this.addView(mRateText);
mRateText.setLayoutParams(lp);
mRateText.setGravity(Gravity.CENTER);
mRateText.setTextColor(Color.BLACK);
mRateText.setTextSize(20);
mCircularProgressBar.setOnProgressChangeListener(this);
}
public void setMax( int max ) {
mCircularProgressBar.setMax(max);
}
public void setProgress(int progress) {
mCircularProgressBar.setProgress(progress);
}
public CircularProgressBar getCircularProgressBar() {
return mCircularProgressBar;
}
public void setTextSize(float size) {
mRateText.setTextSize(size);
}
public void setTextColor( int color) {
mRateText.setTextColor(color);
}
@Override
public void onChange(int duration, int progress, float rate) {
mRateText.setText(String.valueOf( (int)(rate * 100 ) + "%"));
}
}
Step 4 ==> layout===> activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_image2"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Downloading Image With help of progressBar"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="50dp" >
<Button
android:id="@+id/btn_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download..." />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<com.example.progressbarwithimagedwonload.RateTextCircularProgressBar
android:id="@+id/rate_progress_bar"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="30dp"
android:layout_marginTop="20dp"
android:visibility="invisible" >
</com.example.progressbarwithimagedwonload.RateTextCircularProgressBar>
<ImageView
android:id="@+id/image_donwload"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:src="@drawable/ic_launcher"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
Step 5 : AndroidManifest.xml ===>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.progressbarwithimagedwonload"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Example Screen :-
IMG-1
IMG-3
Download Source Code :-
Download Source Code Progressbar and Download percentage Calculation.