Voglio analizzare una pagina web e visualizzare uno stato di progressdialog orizzontale e incrementarlo byte a byte, è possibile?Android: AsyncTask, come è possibile aggiornare ProgressDialog incrementare
6
A
risposta
20
provare qualcosa di simile,
Crea una ProgressDialog.
ProgressDialog mProgressDialog = new ProgressDialog(Your_Activity.this);
mProgressDialog.setMessage("Here you can set a message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
MyAsyncTask obj = new MyAsyncTask();
obj.execute("url");
tua Classe AsyncTask.
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int length = connection.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file_name.txt");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/length));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
@Override
public void onProgressUpdate(String... args){
mProgressDialog.setProgress(args[0]);
}
}
}
si deve dare a questi permesso di nel file AndroidManifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+0
In alcuni URL si ottiene sempre -1, quindi utilizzare questo codice HttpURLConnection connection = (HttpURLConnection) url.openConnection(); \t \t connection.setRequestMethod ("HEAD"); \t \t connection.connect(); \t \t int length = connection.getContentLength(); –
Sì, è possibile http://goo.gl/eeiu5 – Matthieu
C'è un exemple per favore? – MimmoG
Segnala questo link di esempio: https://sites.google.com/site/androidhowto/how-to-1/create-a-custom-progress-bar-using-asynctask – Uttam