开发者

Android: How to download file and show notification with progressbar?

开发者 https://www.devze.com 2023-04-12 19:38 出处:网络
I have an activity that downloads a file from the web when a button is clicked. The downloading of the file is done via an inner AsyncTask. The download works, I can even show, update, and hide a prog

I have an activity that downloads a file from the web when a button is clicked. The downloading of the file is done via an inner AsyncTask. The download works, I can even show, update, and hide a progressbar widget in the the Activitys layout.xml using the AsyncTask. I can also, show a notification from this AsyncTask. I Cannot however, update the progressbar inside the notification from the AsyncTask. I get a Force Close as soon as the first update is processed. Will supply my code if needed!

Thanks for your time

InvocationTargetException.<init>(Throwable) line: 50    
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not              available [native method] 
Method.invoke(Object, Object...) line: 507  
ZygoteInit$MethodAndArgsCaller.run() line: 845  
ZygoteInit.main(String[]) line: 603 
NativeStart.main(String[]) line: not available [native method]  

This is thrown to this line

myContentView.setProgressBar(R.id.status_progress, 100, Integer.parseInt(progress[0]), false);

Here is my code

protected String doInBackground(String... aurl) {
int count;

try {

URL url = new URL(aurl[0]);
String path = url.getPath();
String filename = new File(path).getName();
Environment.getExternalStorageDirectory();
File tm = new File("/sdcard/Transform Mii/");
tm.mkdirs();
File out = new File(tm, filename);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(out);

byte data[] = new byte[1024开发者_如何学JAVA];

long total = 0;

while ((count = input.read(data)) != -1) {
    total += count;
    publishProgress(""+(int)((total*100)/lenghtOfFile));
    output.write(data, 0, count);
}

output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;

}
protected void onProgressUpdate(String... progress) {
progressbar.setProgress(Integer.parseInt(progress[0]));
myContentView.setProgressBar(R.id.status_progress, 100, Integer.parseInt(progress[0]), false);
notificationManager.notify(NOTIF_ID, notification);
}

progressbar is the bar that is in the activity's layout.xml, this updates normally

myContentView progressbar is the bar that is inside the notification

0

精彩评论

暂无评论...
验证码 换一张
取 消