Android默认优先使用WPS打开PDF文档

使用第三方App打开PDF文档,当选择使用WPS时,出现提示获取文档类型,一直打不开的情况。

解决办法,首先检测是否安装了WPS软件。如果安装了,则用WPS打开,否则,使用默认工具打开。

具体实现如下:

1、工具类SystemUtil

public class SystemUtil {

    public static boolean isInstall(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

}

2、下载文档类

public class DownloadUtils {

    private static ProgressDialog mDialog = null;

    /**
     * 显示下载进度条
     *
     * @param aty
     */
    public static void showProgressDialog(Activity aty) {
        if (mDialog == null) {
            mDialog = new ProgressDialog(aty);
            mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
            mDialog.setMessage(aty.getResources().getString(R.string.msg_downloading));
            mDialog.setIndeterminate(false);//设置进度条是否为不明确
            mDialog.setCancelable(true);//设置进度条是否可以按退回键取消
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    mDialog = null;
                }
            });
            mDialog.show();
        }
    }

    /**
     * 关闭下载进度条
     */
    public static void closeProgressDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    /**
     * 获取打开文档意图
     *
     * @param file
     * @return
     */
    public static Intent getFileIntent(Activity activity, File file) {
        Uri uri = Uri.fromFile(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            uri = FileProvider.getUriForFile(activity, "com.invt.fileprovider", file);
        }
        String type = getMIMEType(file);
        //优先使用WPS打开
        //检测是否安装了wps软件,没有安装选择默认打开
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        if (SystemUtil.isInstall(activity, "cn.wps.moffice_eng")) {
            intent.setClassName("cn.wps.moffice_eng",
                    "cn.wps.moffice.documentmanager.PreStartActivity2");
            intent.setData(uri);
        } else {
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(uri, type);
        }
        return intent;
    }

    /**
     * 下载文件到sdcard
     *
     * @param fileName
     * @param input
     */
    public static void writeToSDCard(String fileName, InputStream input) {
        // 判断是否挂载了SD卡
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            String directory = getDownloadPath();
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(directory, fileName);
            if (file.exists()) {
                file.delete();
            }
            try {
                FileOutputStream fos = new FileOutputStream(file);
                byte[] b = new byte[2048];
                int j = 0;
                while ((j = input.read(b)) != -1) {
                    fos.write(b, 0, j);
                }
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取下载路径
     *
     * @return
     */
    public static String getDownloadPath() {
        String compName = AppString.getCompanyName();
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + compName + "/Doc/";
    }

    /**
     * 获取文档类型,并打开
     *
     * @param f
     * @return
     */
    private static String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        /* 依扩展名的类型决定MimeType */
        if (end.equals("pdf")) {
            type = "application/pdf";
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("docx") || end.equals("doc")) {
            type = "application/vnd.ms-word";
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = "application/vnd.ms-excel";
        } else {
            //如果无法直接打开,就跳出软件列表给用户选择
            type = "*/*";
        }
        return type;
    }

}

3、使用

        DownloaderTask task = new DownloaderTask();
        task.execute(mDownloadUrl);
/**
     * 任务类
     */
    private class DownloaderTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String url = params[0];
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            try {
                fileName = URLDecoder.decode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            MyLogger.i("download", "fileName=" + fileName);
            try {
                URL resUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) resUrl.openConnection();
                conn.connect();
                InputStream input = conn.getInputStream();
                DownloadUtils.writeToSDCard(fileName, input);
                input.close();
                return fileName;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            DownloadUtils.closeProgressDialog();
            if (result == null) {
                ToastUtils.showShortToast(StartActivity.this, R.string.msg_downloaderror);
                return;
            }
            ToastUtils.showShortToast(StartActivity.this, R.string.msg_downloadsuccess);
            String dir = DownloadUtils.getDownloadPath();
            File file = new File(dir, result);
            Intent intent = DownloadUtils.getFileIntent(StartActivity.this, file);
            //自动打开
            startActivity(intent);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DownloadUtils.showProgressDialog(StartActivity.this);
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

    }

核心代码:

/**
     * 获取打开文档意图
     *
     * @param file
     * @return
     */
    public static Intent getFileIntent(Activity activity, File file) {
        Uri uri = Uri.fromFile(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            uri = FileProvider.getUriForFile(activity, "com.invt.fileprovider", file);
        }
        String type = getMIMEType(file);
        //优先使用WPS打开
        //检测是否安装了wps软件,没有安装选择默认打开
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        if (SystemUtil.isInstall(activity, "cn.wps.moffice_eng")) {
            intent.setClassName("cn.wps.moffice_eng",
                    "cn.wps.moffice.documentmanager.PreStartActivity2");
            intent.setData(uri);
        } else {
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(uri, type);
        }
        return intent;
    }

完!!!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值