我有一个原生安卓应用。我在文本区域中显示指向 Word 文件的链接。当我点击它时,我的应用程序会切换到 Google 文档并显示无法打开该文档的消息。我想切换此行为,只允许用户下载文件而无需切换到外部应用程序。怎么做?
最佳答案
使用 AsynTask
从网络下载文件,如下所示:
private class DownloadFile extends AsyncTask<String, Void, Void> {
String fileName="";
@Override
protected Void doInBackground(String... strings) {
String fileUrl; // -> http://maven.apache.org/maven-1.x/maven.pdf
fileUrl = strings[0];
// -> maven.pdf
fileName = strings[1];
String extStorageDirectory = Environment.getExternalStorageDirectory().toString()+ "/Android/data/com.mymdsmanager";
File dir = new File(extStorageDirectory);
if(!dir.exists())
dir.mkdirs();
File pdfFile = new File(dir, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!fileName.equals(""))
openMail(fileName); // here i want to open file in mail you can write your own code as per your requirements
}
}
public void openMail(String tableName){
String[] mailto = {MyApplication.getEmailId()};
String path = Environment.getExternalStorageDirectory().toString()+ "/Android/data/com.mymdsmanager";
File pdfFile = new File(path , tableName);
Log.d("File", "openMail: " + pdfFile.getAbsolutePath());
Uri uri = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, mailto);
intent.putExtra(Intent.EXTRA_SUBJECT, "MDS Manager Data - "+tableName);
intent.putExtra(Intent.EXTRA_TEXT, "Here is the MDS Manager data export that you requested.");
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
FileDownloader.java
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后像下面这样调用DownloadFile()
方法:
new DownloadFile().execute(link, table_name+".pdf");
希望这对您有所帮助:-)
关于android - 如何防止 Android 应用程序在外部应用程序中打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46523674/