Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
What is the best way to load a notification image?
Here's my current way: As you can see the image loads synchronously and thus the notification can be delayed. This is a bad way.
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Bitmap bitmap = getBitmapFromURL("https://graph.facebook.com/YOUR_USER_ID/picture?type=large");
// CONSTRUCT THE NOTIFICATION DETAILS
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
builder.setLargeIcon(bitmap);
builder.setContentIntent(pendingIntent);
I really need an answer to continue working on my project.
You should first notify your Notification with no image or place holder, then load your bitmap with an AsyncTask, or use Picasso and Target callback.
Give to your task the builder that you used for the first notify, when bitmap is loaded, add it to the builder, and then re-notify your Notification.
If there's a risk that content had changed before complete image loading, store a variable that identify your current content to show, that you can check before renotify.
You can follow that exemple of MediaNotificationManager provide by google UniversalMusicPlayer project.
In your case :
// CONSTRUCT THE NOTIFICATION DETAILS
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
//builder.setLargeIcon(bitmap); // replace this line with place holder drawable from resources
builder.setContentIntent(pendingIntent);
manager.notify(NOTIFICATION_ID, builder.build());
currentLoadImageTask = new LoadImageTask(manager, builder);
currentLoadImageTask.execute("https://graph.facebook.com/YOUR_USER_ID/picture?type=large");
// ...
static class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
final NotificationManager manager;
final NotificationCompat.Builder builder;
public LoadImageTask(final NotificationManager manager, final NotificationCompat.Builder builder) {
this.manager = manager;
this.builder = builder;
}
#Override
protected Bitmap doInBackground(final String... strings) {
if (strings == null || strings.length == 0) {
return null;
}
try {
final URL url = new URL(strings[0]);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
final InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(final Bitmap bitmap) {
if (bitmap == null || manager == null || builder == null) {
return;
}
builder.setLargeIcon(bitmap);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
With picasso :
// CONSTRUCT THE NOTIFICATION DETAILS
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
//builder.setLargeIcon(bitmap); // replace this line with place holder drawable from resources
builder.setContentIntent(pendingIntent);
manager.notify(NOTIFICATION_ID, builder.build());
// ...
Picasso.with(context)
.load("https://graph.facebook.com/YOUR_USER_ID/picture?type=large")
.resize(250, 250)
.into(new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
builder.setLargeIcon(bitmap);
manager.notify(NOTIFICATION_ID, builder.build());
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
// Do nothing
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
// Do nothing
}
});
If not in UiThread you can create a Runnable and execute it in Looper
final Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
// Call from here
}
});
Picasso is much better simply because using cache.
And I highly recommend you to resize every bitmap you set in notification because it can easily provoc OutOfMemoryException if you dont.
Remember,if you are loading something using the web, you have to wait a bit.
There are several solutions:
Load an image from the web like in your example and show.
Show a stub image and show downloaded image later by updating the notification
Use a little that helps top cache web inches. For instance, picaso
http://square.github.io/picasso/
use Picasso lib to load image from url like
Picasso.with(this.load(imageUri).into(imageview_id);
Related
How can I show image URL from server (flask) on Android studio by okhttp. I write a method for return img(encode by base64) and send to my android studio by this code
#app.route('/', methods = ['GET', 'POST'])
def handle_request():
files_ids = list(flask.request.files)
print("\nNumber of Received Images : ", len(files_ids))
image_num = 1
n = 0
for file_id in files_ids:
print("\nSaving Image ", str(image_num), "/", len(files_ids))
if n == 0 or file_id == 'image0':
imagefile = flask.request.files[file_id]
filename = werkzeug.utils.secure_filename(imagefile.filename)
print("Image Filename : " + imagefile.filename)
timestr = time.strftime("%Y%m%d-%H%M%S")
path = r'C:\Users\Malee\Desktop\AndroidFlask-master\Part 1\FlaskServer\uploads'
imagefile.save(os.path.join(path,filename))
#os.system('python test_grader.py')
n = n+1
if n > 0 and n!=0:
if file_id != 'image0':
imagefile = flask.request.files['image'+str((len(files_ids)-1))]
filename = werkzeug.utils.secure_filename(imagefile.filename)
print("Image Filename : " + imagefile.filename)
timestr = time.strftime("%Y%m%d-%H%M%S")
path = r'C:\Users\Malee\Desktop\AndroidFlask-master\Part 1\FlaskServer\Answer'
imagefile.save(os.path.join(path,filename))
#os.system('python test_grader2.py')
break
image_num = image_num + 1
print("\n")
path = r'C:\Users\Malee\Desktop\AndroidFlask-master\Part 1\FlaskServer\download'
#return send_file(os.path.join(path,newest()), mimetype='image/gif')
path = r'C:\Users\User\Desktop\AndroidFlask-master\Part 1\FlaskServer\download'
data_uri = base64.b64encode(open('DN.jpg', 'rb').read()).decode('utf-8')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
return data_uri
And then on my android studio response by bitmap and show on ImageView by this code
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Cancel the post on failure.
call.cancel();
Log.d("FAIL", e.getMessage());
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
responseText.setText("Failed to Connect to Server. Please Try Again.");
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
ImageView responesImg = findViewById(R.id.imageView2);
/*InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);*/
ResponseBody in = response.body();
InputStream inputStream = in.byteStream();
Log.i("inputStream","inputstream value = "+inputStream);
// convert inputstram to bufferinoutstream
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bitmap=BitmapFactory.decodeStream(bufferedInputStream);
Log.i("bitmap","bitmap value = "+bitmap);
showImage(bitmap);/*
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "test.jpg" , "none");
responesImg.setImageBitmap(bitmap);*/
}
});
}
});
And when I run in my phone can be show the title but can't show img.
To load and show image from url to ImageView, you can use Glide library to do it
Add to your app gradle
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
}
Load image to view:
Glide.with(context).load(url).into(imageView);
In your Flask server you are encoding and sending the local path where the image resides on your machine to your android app. When your android app tries to decode the response, it does not know where it is.
Suggested Solution:
Save your picture to a cloud based storage.(e.g Firebase or Amazon storage, etc)
Download your image and load it to imageView. (e.g Picasso.get().load("http://link-to-your-image").into(imageView);)
Hope that help.
I'm writing Espresso tests to run on my React Native app. I'm using Espresso-Intents to simulate the user taking a picture, with the following code:
public void takePicture() {
Instrumentation.ActivityResult result = createImageCaptureActivityResultStub();
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result);
clickText("Camera");
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
System.out.println(e.toString());
return null;
}
}
private Instrumentation.ActivityResult createImageCaptureActivityResultStub() {
// Put the drawable in a bundle.
Bundle bundle = new Bundle();
bundle.putParcelable("data", getBitmapFromURL("https://vignette.wikia.nocookie.net/the-feed-your-pets-community/images/6/69/Banana.png/revision/latest?cb=20180527162222"));
// Create the Intent that will include the bundle.
Intent resultData = new Intent();
resultData.putExtras(bundle);
// Create the ActivityResult with the Intent.
return new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
}
When running, the camera intent is successfully stubbed, but the view which should display the photo is stuck in its loading state.
In debugging, I have discovered that getBitmapFromURL is not the problem, because bundle contains the correct image.
Could anyone suggest where the problem may lie, or how best to debug further?
So I basically have a List of URIs, each has a .jpeg file, and I want to show this list like a GIF file (not necessesary to make a gif, only to display).
So after a research I found the AnimationDrawble object, converted each URI into Drawable and added it as a frame to AnimationDrawable.
This is my code:
AnimationDrawable ad = new AnimationDrawable();
Drawable[] dr = new Drawable[position+1];
ProgressItem pi;
try {
for (int i = 0; i <= position; i++) {
pi = progress.get(i);
try {
dr[i] = drawableFromUrl(pi.getImage());
} catch (IOException ios) {
Toast.makeText(activity, ios.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
catch(Exception ex)
{
Toast.makeText(activity, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(activity,ProgressImage.class);
DataWraper.setItems(dr);
drawableFromUrl:
public Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
MyDownloadTask mdt = new MyDownloadTask();
try{
mdt.execute(connection);
}
catch(Exception ex)
{
Toast.makeText(activity, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
InputStream input = mdt.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
The implementation part:
Glide.with(this)
.load(ad)
.into(progressImage);
When I'm trying to Glide the AnimationDrawble into the ImageView I get the following exception:
java.lang.IllegalArgumentException: Unknown type class android.graphics.drawable.AnimationDrawable.
This made me hesistate the way I'm trying to pull this off. Should this be this complicated?
If this is the right way, what am I doing wrong? maybe there's another way of doing so? I'd love to get some details. Thanks in advance!
https://github.com/koral--/android-gif-drawable
Not sure if you're open to any 3rd party libraries, but i used this one for gifs before and it worked quite well for me
please excuse my bad English I hope my explanations are understandable.
I am working on app, wich communicate with my server. It has different tasks. One of them is to upload my pictures from my smartphone to my server. I want, that my app do this in the background, with minimized use of memory and bandwidth.
Basically it works, but when I have to many new pictures, there are to many AsyncTask at the same time and reduce memory and bandwidth perceptible.
First I use a BroadcastReceiver, which start every 30 min my picture scanner.
The Scanner frist check, if the External Storage is readable, if is WIFI on and if there is a Internet Connection.
When that is true it query a list from pictures, which are already uploaded, from the database.
Then it request all pictures from the MediaStore library, check some minimum values (size, height, width) and if the pic isn't uploaded. When everything is ok, it start an AsyncTask for resize the image and upload it:
public class Scanner {
private Context context;
private PicDAO picDAO;
private Helper helper;
public Scanner(Context context) {
this.context = context;
picDAO = new PicDAO(context);
helper = new Helper(context);
}
public void startScan(){
if(helper.isExternalStorageReadable()
&& helper.isWifiOn()
&& helper.checkInternet()){
HashMap<Integer, String> pics = picDAO.picsHashMap();
Cursor mCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,null,null,MediaStore.Images.Media.DEFAULT_SORT_ORDER);
if(mCursor != null){
mCursor.moveToFirst();
while(!mCursor.isAfterLast()) {
PicClass pic = new PicClass(
mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID)),
mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)),
mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA)),
mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media.WIDTH)),
mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media.HEIGHT)),
mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media.SIZE)),
context
);
if(pic.getSize() > 25000
&& pic.getHeight() > 200
&& pic.getWidth() > 200
&& ( pics.get(pic.getIdent()) == null || !pics.get(pic.getIdent()).equals(pic.getDisplay_name()))
){
CreateThumb createThumb = new CreateThumb(context);
createThumb.execute(new PicClass[]{pic});
}
mCursor.moveToNext();
}
mCursor.close();
}
}
}
}
The creatThumb looks resize the Image and start a upload (using the volley library):
public class CreateThumb extends AsyncTask {
private Context context;
public CreateThumb(Context context) {
this.context = context;
}
#Override
protected PicClass doInBackground(PicClass... pics) {
Helper helper = new Helper(context);
String encodedString = "";
if(helper.isWifiOn() && helper.checkInternet()){
double dWidth = 1000;
double dHeight = 1000;
if(pics[0].getWidth() < (int) dWidth && pics[0].getHeight() < (int) dHeight){
dWidth = pics[0].getWidth();
dHeight = pics[0].getHeight();
}else{
if (pics[0].getWidth() > pics[0].getHeight()){
double div = pics[0].getWidth() / dWidth;
dHeight = pics[0].getHeight() / div;
}else{
double div = pics[0].getHeight() / dHeight;
dWidth = pics[0].getWidth() / div;
}
}
int width = (int) dWidth;
int height = (int) dHeight;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(pics[0].getPath(),bmOptions);
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap,width,height,0);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] byte_arr = stream.toByteArray();
encodedString = Base64.encodeToString(byte_arr, 0);
}
pics[0].setThumb_file(encodedString);
return pics[0];
}
#Override
protected void onPostExecute(final PicClass pic) {
if(!pic.getThumb_file().equals("")){
RequestQueue queue = Volley.newRequestQueue(context);
String url ="http://example.de/upload.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
if(response.equals("OK")){
PicDAO picDAO = new PicDAO(context);
picDAO.savePic(pic);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("img",pic.getThumb_file());
params.put("filename",pic.getDisplay_name() + ".jpg");
return params;
}
};
queue.add(postRequest);
}
}
}
The script on my server:
<?php
$base = $_POST['img'];
$filename = $_POST['filename'];
$binary = base64_decode($base);
$file = fopen('uploadedimages/'.$filename, 'wb');
fwrite($file, $binary);
fclose($file);
echo "OK";
The Problem is, when I have to many new pictures, it slow down the device and the internet connection, and I get this errors:
W/art: Suspending all threads took: 278.260ms
D/Volley: [2790] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://example.de/upload.php 0x8a9f5792 NORMAL 1> [lifetime=3447], [size=2], [rc=200], [retryCount=1]
How can I optimize my code or prevent that I have to many uploads simultaneously.
EDIT
I tried to rebuild the scanner part and use only one Queue where I add the request. But it seems like it doesn't work. When there is only one picture it works, but when the script add more than on request, it get no response an on the server is just the first picture.
public class Scanner {
private Context context;
private PicDAO picDAO;
private Helper helper;
public Scanner(Context context) {
this.context = context;
picDAO = new PicDAO(context);
helper = new Helper(context);
}
public void startScan(){
if(helper.isDeviceReady()){
Cursor mCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,null,null,MediaStore.Images.Media.DEFAULT_SORT_ORDER);
if(mCursor != null){
final RequestQueue mRequestQueue = Volley.newRequestQueue(context);
mCursor.moveToFirst();
while(!mCursor.isAfterLast()) {
final PicClass pic = new PicClass(mCursor, context);
if(pic.checkSize() && !picDAO.picExist(pic)){
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(pic.getPath(),bmOptions);
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap,pic.getNewSize()[0],pic.getNewSize()[1],0);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] byte_arr = stream.toByteArray();
pic.setThumb_file(Base64.encodeToString(byte_arr, 0));
StringRequest postRequest = new StringRequest(Request.Method.POST, "http://example.de/upload.php", new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.d("DEBUG",response);
if(response.equals("OK")){
PicDAO picDAO = new PicDAO(context);
picDAO.savePic(pic);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("img",pic.getThumb_file());
params.put("filename",pic.getDisplay_name() + ".jpg");
return params;
}
};
mRequestQueue.add(postRequest);
}
mCursor.moveToNext();
}
mCursor.close();
}
}
}
}
How can I optimize my code or prevent that I have to many uploads simultaneously
I'd drop AsyncTask in favor of using IntentService, which executes one job at the time and queues all the other. Of course the whole process is not as trivial as it may look so maybe using dedicated libraries like Android Priority Job Queue would be even better.
Well, to start don't make a new request queue for every upload. THe idea of a queue is that you add a bunch of requests to it, then run the queue and let Volley slowly go through the requests a small group of them at a time. You're creating dozens of queues, and I don't even see a call to run the queue.
I'd also be using a Thread rather than an AsyncTask. AsyncTasks should be one offs. In fact by using this many tasks you're starving out all the other things that may need a task, since they share a common Thread.
I've been looking all over the place for this, and the only answer I've had was "use Pair", but I can't get this to work either.
Here's what I need to:
In Asynctask I need to update both a progress bar, and text. Because of this my Asynctask generic cannot be just Integer and not just String, but both. This is so I can have both classes within the "onProgressUpdate" method.
Can somebody give me some example or links as to how I add the strings and increase the integer in "doInBackground", and how to implement this in the "onProgressUpdate"?
Thank you very much!
Can you create your own simple class to hold the variables and then pass that?
Or, what if you pass a string that you can parse and get the values you need? If you take your first string += ":" + int, then make use of something like
String myString = passedString.substring(0, passedString.lastIndexOf(":")))
int i = Integer.parseInt(passedString.substring(passedString.lastIndexOf(":")+1));
As far as I understand your question; there are mainly two things which you want to do:
1) Handle a UI thread while in the doIneBackground().
2) Implement the onProgressUpdate().
Basically we shouldn't try to access the UI thread while a background process is running.
The reason for that is very clear... # OS level there will be so many thread will be running.And in that case It will be chaos on the screen, if we can update UI from background thread.
For the 2nd one I would like recommend you to take a look at this example:
ProgressDialog mProgressDialog;
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
In the AsynTask:
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wl.acquire();
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled())
return null;
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
}
catch (IOException ignored) { }
if (connection != null)
connection.disconnect();
}
} finally {
wl.release();
}
return null;
}}
The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate and onPreExecute run on the UI thread, so there you can change the progress bar:
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
Regards
Sathya