Android - DownloadListener 或 AsyncTask
我正在尝试通过使用 webview 处理下载而不是浏览器点击 url 来从网页下载一些文件
如果我使用 DownloadListener 它可以完美地解决一个问题我看不到进度条
如果我使用 AsyncTask 我必须将 url 放入代码中要下载它,我只需单击 url 并开始下载
我的问题是如何让 AsyncTask 从网络下载任何 url,而不需要使用
downloadFile.execute("您要下载的文件的 url");
或者我如何为 DownloadListener 创建进度条
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
new Thread(myThread).start();
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setInitialScale(50);
webview.getSettings().setUseWideViewPort(true);
webview.setVerticalScrollBarEnabled(false);
webview.setHorizontalScrollBarEnabled(false);
webview.loadUrl("http://localhost/index.php");
webview.setWebViewClient(new DownloadWebViewClient());
webview.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
InputStream is;
try {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
is = con.getInputStream();
// Path and File where to download the APK
String path = Environment.getExternalStorageDirectory() + "/apdroid/";
String fileName = url.substring(url.lastIndexOf('/') + 1);
File dir = new File(path);
dir.mkdirs(); // creates the download directory if not exist
File outputFile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
// Save file from URL to download directory on external storage
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
String name = Environment.getExternalStorageDirectory() + "/apdroid/" + url.substring(url.lastIndexOf('/') + 1);
intent.setDataAndType(Uri.fromFile(new File(name)), "application/vnd.android.package-archive");
startActivity(intent);
}catch (IOException e) {
e.printStackTrace();
}
}
});
}
protected void install(String fileName) {
// TODO Auto-generated method stub
}
private Runnable myThread = new Runnable() {
@Override
public void run() {
while (myProgress < 100) {
try {
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
} catch (Throwable t) {
}
}
}
Handler myHandle = new Handler() {
@Override
public void handleMessage(Message msg) {
myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};
private class HelloWebViewClient extends WebViewClient {
@Override
public void onReceivedError(WebView view,int errorCode,String description,String failingUrl) {
try {view.stopLoading();} catch(Exception e){}
try {view.clearView();} catch(Exception e){}
view.loadUrl("file:///android_asset/wifi.html");
}
}
我只想在从页面下载任何文件时有 ProgressBar
并且我无法使用 asyncTask 因为我必须将文件放入代码不是通过点击它们
am trying to download from web page some files by clinking the url with webview handling the download not the browser
if i use DownloadListener it works perfectly with one problem i cant see the progressbar
if i use the AsyncTask i have to put the url in the code to download it i can just click the url and start downloading
my question is how can i let the AsyncTask download any url from the web without sitting the
downloadFile.execute("the url to the file you want to download");
or how i can create progressbar for DownloadListener
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
new Thread(myThread).start();
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setInitialScale(50);
webview.getSettings().setUseWideViewPort(true);
webview.setVerticalScrollBarEnabled(false);
webview.setHorizontalScrollBarEnabled(false);
webview.loadUrl("http://localhost/index.php");
webview.setWebViewClient(new DownloadWebViewClient());
webview.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
InputStream is;
try {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
is = con.getInputStream();
// Path and File where to download the APK
String path = Environment.getExternalStorageDirectory() + "/apdroid/";
String fileName = url.substring(url.lastIndexOf('/') + 1);
File dir = new File(path);
dir.mkdirs(); // creates the download directory if not exist
File outputFile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
// Save file from URL to download directory on external storage
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
String name = Environment.getExternalStorageDirectory() + "/apdroid/" + url.substring(url.lastIndexOf('/') + 1);
intent.setDataAndType(Uri.fromFile(new File(name)), "application/vnd.android.package-archive");
startActivity(intent);
}catch (IOException e) {
e.printStackTrace();
}
}
});
}
protected void install(String fileName) {
// TODO Auto-generated method stub
}
private Runnable myThread = new Runnable() {
@Override
public void run() {
while (myProgress < 100) {
try {
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
} catch (Throwable t) {
}
}
}
Handler myHandle = new Handler() {
@Override
public void handleMessage(Message msg) {
myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};
private class HelloWebViewClient extends WebViewClient {
@Override
public void onReceivedError(WebView view,int errorCode,String description,String failingUrl) {
try {view.stopLoading();} catch(Exception e){}
try {view.clearView();} catch(Exception e){}
view.loadUrl("file:///android_asset/wifi.html");
}
}
i just want to have ProgressBar when i download any file from my page
and i cant use asyncTask because i have to put the files in the code not by clicking at them
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能应该
覆盖 URL 加载
过程,并通过某种方式识别是否正在加载您想要下载其资源的任何 URL。一旦检测到这种情况,请停止加载页面并使用此 URL 启动 AsyncTask。
You should probably be
overriding the URL loading
process, and recognize by some way if any URL is being loaded whose resource you would want to download.As soon as you detect this, stop loading the page and start the AsyncTask with this URL.