无法在android N中通过downloadmanager onClick打开文件下载文件

时间:2018-01-02 08:42:25

标签: android android-download-manager

我正在尝试打开listview项目上的下载文件,点击android N.它在API 24下工作正常,但是API 24及更高版本,当我尝试打开它时显示“无法打开文件”。我认为文件路径可能不正确,但我已经尝试了所有我知道的工作,但它不起作用。请帮我解决这个问题。

GalleryFragment.java

            /**************** Create Custom Adapter *********/
            adapter = new ItemAdapter(getActivity(), arraylist, res);

            listView.setAdapter(adapter);


            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    clickposition = position;
                    textView = (TextView) view.findViewById(R.id.txtitem);

                    imageView = (ImageView) view.findViewById(R.id.listimage);
                    if (!temp.contains(position)) {
                        url = Uri.parse(array[position][1]);
                        listitemname = array[position][0];
                        DownloadData();
                        temp.add(position);
                        complete = false;
                    }


                    if (complete && temp.contains(position)) {

//                        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), listitemname);      //"storage/sdcard0/Android/data/triad.com.catagoriesapp/files/Download",


                        if (file.exists()) {
                            Uri uri;
                            if (Build.VERSION.SDK_INT < 24) {
                                uri = filepath[position];
                            } else {


                              String u=  (filepath[position]).getPath();
                                if (u.substring(0, 8).matches("file:///")) {
                                    u = u.substring(8);
                                }
                                if (u.substring(0, 7).matches("file://")) {
                                    u = u.substring(7);
                                }
                                   File file = new File(u);

                                uri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", file);
                            }

                            Intent mpOpenintent = new Intent(Intent.ACTION_VIEW);
                            mpOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mpOpenintent.setDataAndType(uri, "*/*");
                            try {
                                startActivity(mpOpenintent);
                            } catch (ActivityNotFoundException e) {

                            }
//                            complete = false;
                        }

                    }
                }
            });


        }
        return view;
    }


    ArrayList<Integer> temp = new ArrayList<>();

    TextView textView1;
    ImageView imageView1;
    long downloadReference;

    private long DownloadData() {

        imageView.setImageResource(R.drawable.download1);
        textView1 = textView;
        imageView1 = imageView;
        // Create request for android download manager
        downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(url);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setAllowedOverRoaming(false);
        //Setting title of request
        request.setTitle("File " + listitemname + " Downloaded");

        //Setting description of request
        request.setDescription("File " + listitemname + " download in progress.");
        request.setDestinationInExternalFilesDir(getActivity(), Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), listitemname);
//        if (PermissionCheck.readAndWriteExternalStorage(getActivity())) {
          //  request.setDestinationInExternalPublicDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), listitemname);

        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        //Enqueue download and save into referenceId
        downloadReference = downloadManager.enqueue(request);


        return downloadReference;
    }


    @Override
    public void onStop() {

        try {
            getActivity().unregisterReceiver(downloadReceiver);

        } catch (Exception e) {
        }
        super.onStop();
    }

    @Override
    public void onResume() {
        try {
            getActivity().registerReceiver(downloadReceiver,filter);

        } catch (Exception e) {
        }
        super.onResume();
    }
  //  File[] xfilepath = new File[15];
    int clickposition;
    Uri path;
    File file;
    boolean complete = false;
    DownloadManager downloadManager;
    Cursor c;
    DownloadManager.Query query;
    String apkUri;
    Uri[] filepath = new Uri[15];
    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {


            if (imageView1 == null) {
                return;
            }

            String action = intent.getAction();

            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                complete = true;
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                imageView1.setVisibility(View.GONE);
                textView1.setVisibility(View.VISIBLE);

                if (Build.VERSION.SDK_INT < 24) {
                    query = new DownloadManager.Query();
                    query.setFilterById(downloadReference);


                    c = downloadManager.query(query);

                    if (c != null && c.getCount() > 0) {
                        if (c.moveToFirst()) {

                            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                                apkUri = c.getString(1);


                                file = new File(apkUri);

                                path = Uri.fromFile(file);
                                filepath[clickposition] = path;
                                ///add
                            }


                        }
                    }
                } else {


                        //Your read write code.

                        query = new DownloadManager.Query();
                        query.setFilterById(downloadReference);
                        c = downloadManager.query(query);
                        if (c.moveToFirst()) {
                            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                                apkUri = c.getString(8);//.substring(8,c.getString(8).length());///
//
                                if (apkUri.substring(0, 8).matches("file:///")) {
                                    apkUri = apkUri.substring(8);
                                }
                                if (apkUri.substring(0, 7).matches("file://")) {
                                    apkUri = apkUri.substring(7);
                                }
                                file = new File(apkUri);
                              path = Uri.fromFile(file);
                            //    path  = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", file);

                                filepath[clickposition] = path;
                                if (!file.exists()) {
                                    return;
                                }
                              //  getActivity().unregisterReceiver(downloadReceiver);
                            }

                        }

                    }
                }
            }




    };


    public void setListData(String array[][], int listlength) {

        for (int i = 0; i < listlength; i++) {

            final ItemModel item = new ItemModel();

            /******* Firstly take data in model object ******/
            item.setName(array[i][0]);


            /******** Take Model Object in ArrayList **********/
            arraylist.add(item);


        }

    }


}

这是我的provider_paths.xml -

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/triad.com.catagoriesapp/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>

0 个答案:

没有答案