我有这段代码,但在我的 Android Emulator 4.2 中出现以下错误:networkonmainthreadexception null
我是 Android 新手,这是我的第一个应用程序,我有一个网络视图,需要下载 PDF 并保存在 SD 卡中。
这是我的代码:
browser.setDownloadListener(new DownloadListener()
{
public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, long contentLength)
{
AlertDialog.Builder builder = new AlertDialog.Builder(WebViewdemoActivity.this);
builder.setTitle("Descarga");
builder.setMessage("¿Desea guardar el fichero en su tarjeta SD?");
builder.setCancelable(false).setPositiveButton("Aceptar", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
descargar(url);
}
}).setNegativeButton("Cancelar", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
builder.create().show();
}
private void descargar(final String url)
{
String resultado ="";
//se obtiene el fichero con Apache HttpClient, API recomendada por Google
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
InputStream inputStream = null;
try
{
HttpResponse httpResponse = httpClient.execute(httpGet);
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpResponse.getEntity());
inputStream = bufferedHttpEntity.getContent();
//se crea el fichero en el que se almacenará
String fileName = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/webviewdemo";
File directorio = new File(fileName);
File file = new File(directorio, url.substring(url.lastIndexOf("/")));
//asegura que el directorio exista
directorio.mkdirs();
FileOutputStream fileOutputStream = new FileOutputStream(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while (inputStream.available() > 0 && (len = inputStream.read(buffer)) != -1)
{
byteArrayOutputStream.write(buffer, 0, len);
}
fileOutputStream.write(byteArrayOutputStream.toByteArray());
fileOutputStream.flush();
resultado = "guardado en : " + file.getAbsolutePath();
}
catch (Exception ex)
{
resultado = ex.getClass().getSimpleName() + " " + ex.getMessage();
}
finally
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
}
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(WebViewdemoActivity.this);
builder.setMessage(resultado).setPositiveButton("Aceptar", null).setTitle("Descarga");
builder.show();
}
});