如何防止Android应用程序在外部应用程序中打开文件?

时间:2017-10-02 10:19:58

标签: android google-docs

我有一个原生的Android应用程序。我在文本区域中显示了Word文件的链接。当我点按它时,我的应用会切换到Google文档并显示无法打开文档的消息。我想切换此行为,只允许用户下载文件而无需切换到外部应用程序。怎么做?

3 个答案:

答案 0 :(得分:0)

使用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");

我希望这可以帮到你: - )

答案 1 :(得分:0)

Download Manager是一个处理长时间运行的HTTP下载的系统服务。它负责在后台下载,在任何故障后重试下载等。建议使用DownloadManager进行任何长时间运行的HTTP下载。

 public static void downloadFile(Context context, String url, String title, String description)    {

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    if(title != null)
        request.setTitle(title);
    if(description != null)
        request.setDescription(description);
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title);

    // get download service and enqueue file
    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}

您可以在Util类中使用上述方法,并且可以通过传递Context从需要进行下载的任何活动中调用它。标题和描述也可以传递给方法,以获得更多自定义通知。

你可以做类似的事情 -

viewThatHoldsTheLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //call download File
            downloadFile(mContext, theWordDocUrl, "Abc Document", "Here is your abc document");
        }
    });

答案 2 :(得分:0)

非常感谢你的建议。他们给了我一个线索,在我的应用程序中查看。事实证明,我下载文件的目录是用户无法访问的。我不得不将其更改为Downloads目录,突然一切都开始工作了。