我有一个类似这个https://drive.google.com/uc?id=0Bw6vr2LNxB3iUFJrTk5oZDljaTA&export=download
的可下载链接,只能在浏览器上使用。
如果我使用移动浏览器打开链接
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
然后它会自动下载文件。
是否可以使用webview而不是默认浏览器下载文件?
我试过这样的事情
public class showDownload extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_download);
Bundle extras = getIntent().getExtras();
if (extras.getString("url") != null) {
//DO SOMETHING
String url=extras.getString("url");
Toast.makeText(getApplicationContext(), "__", Toast.LENGTH_SHORT).show();
webView = (WebView) findViewById(R.id.webView1);
webView.loadUrl(url);
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(
Uri.parse(url));
Toast.makeText(getApplicationContext(), " Yesssss", Toast.LENGTH_SHORT).show();
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
}
}
}
我累了但很难得到任何解决方案? 任何人都可以帮我解决这个问题吗?
答案 0 :(得分:0)
如果您想要一个应用内下载管理器,请参阅此帖子。 为您提供有关各种下载选项的非常详细的信息。 https://stackoverflow.com/a/3028660
答案 1 :(得分:0)
我无法验证它是什么类型的下载链接,但如果您想使用webview下载文件,我们有两个选项 -
DownloadManager
this link DownloadListener
this link 我会检查他们两个并会回到你身边,直到那时你可以先从DownloadListener
开始,因为我之前使用它并且效果很好。
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
答案 2 :(得分:0)
点击你的按钮
String URL = "https://drive.google.com/uc?id=0Bw6vr2LNxB3iUFJrTk5oZDljaTA&export=download";
//check if your device is marshmallow that need runtime permission
return(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1);
String[] perms = {"android.permission.WRITE_EXTERNAL_STORAGE"};
int permsRequestCode = 200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(perms, permsRequestCode);
}
并调用onRequestPermissionsResult
方法
@Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){
switch(permsRequestCode){
case 200:
boolean writeAccepted = grantResults[0]== PackageManager.PERMISSION_GRANTED;
//if user click allow, it will start downloading the file from URL
if (writeAccepted) {
new DownloadTask(MainActivity.this, URL);
} else {
Toast.makeText(MainActivity.this, "you have no permission!", Toast.LENGTH_LONG).show();
}
break;
}
}
现在创建一个名为DownloadTask.java
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = "yourfilename_" + uploadDate() + rand() + ".pdf"; //Create file name by picking download file name from URL
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private String uploadDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
String formattedDate = df.format(c.getTime());
return formattedDate;
}
private String rand() {
Random random = new Random();
return String.format("%09d", random.nextInt(10000000));
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please wait...");
progressDialog.show();
}
@Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
Toast.makeText(context, "Download successful!", Toast.LENGTH_SHORT).show();
//this is to view the downloaded file
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + "yourfoldername" + "/" + downloadFileName);
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
context.startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(context, "no apps can read the file", Toast.LENGTH_SHORT).show();
}
} else {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Download failed. Please try again!", Toast.LENGTH_SHORT).show();
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
//Change button text if exception occurs
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(
Environment.getExternalStorageDirectory() + "/"
+ "yourfoldername");
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
}