1. 程式人生 > >跳轉到wps檢視檔案

跳轉到wps檢視檔案

  最近我的專案用到了需要從伺服器下載一些附件,然後支援本地去檢視這些檔案,最後確定的實現辦法是跳轉到wps app進行瀏覽。之前我讓另一個同事將這個功能寫成了一個小demo ,然後我想起來了就拿著他的Demo看了一遍然後就修改程式碼自己做成一個工具類整合到自己的app裡面了。

1、需要依賴jar包 和 拷貝一個so檔案:

  jar包 和so 檔案我會壓縮,然後免費放到csdn 的下載裡面,後面會加上連線。將兩者新增到專案裡面完畢之後如我下面截圖所示:

就是我紅色標記的兩個框,至於jar 包的名字是我隨便取的。

2、工具類程式碼:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import 你的包名.app.Visor;
import 你的包名.RestCreator;
import 你的包名.InstallUtil;
import 你的包名.VisorLogger;
import 你的包名.ToastUtil;
import 你的包名.CommonDialog;

/**
 * @author ChenYe
 *         created by on 2018/10/12 0012. 10:37
 *         我從PC端了解到,他們支援上傳的附件型別有:
 *         pdf/rar/zip/dwg/jpg/png/doc/docx/xls/slsx/ppt/pptx/wps/et/dps/ceb 等型別檔案
 *         目前不支援以上的檔案有 :  rar、dwg、slsx 、et 、dps 、ceb
 *         <p>
 *         後期如果要延伸檢視其它型別的,自己可以去:https://blog.csdn.net/sinat_30474567/article/details/53411146   裡面自己看
 **/

public class BrowseFileUtil {

    private static final String ALLOW_PDF = "pdf";
    private static final String ALLOW_PNG = "png";
    private static final String ALLOW_JPEG = "jpeg";
    private static final String ALLOW_JPG = "jpg";
    private static final String ALLOW_DOC = "doc";
    private static final String ALLOW_DOCS = "docs";
    private static final String ALLOW_DOCX = "docx";
    private static final String ALLOW_XLS = "xls";
    private static final String ALLOW_XLSX = "xlsx";
    private static final String ALLOW_PPT = "ppt";
    private static final String ALLOW_PPTX = "pptx";
    private static final String ALLOW_DWG = "dwg";
    private static final String ALLOW_ZIP = "zip";
    private static final String ALLOW_TXT = "txt";
    private static final String ALLOW_WPS = "wps";

    /**
     * 檔案以doc、docs 結尾的
     */
    public static final String TYPE_WORD = "application/msword";
    /**
     * 檔案以 .txt 結尾的
     */
    public static final String TYPE_TXT = "text/plain";

    /**
     * 檔案以 .xlsx 、xls 結尾的
     */
    public static final String TYPE_EXCEL = "application/vnd.ms-excel";

    /**
     * 檔案以 .pptx 、.ppt 結尾的
     */
    public static final String TYPE_PPT = "application/vnd.ms-powerpoint";

    /**
     * 檔案以 .pdf 結尾的
     */
    public static final String TYPE_PDF = "application/pdf";

    /**
     * 檔案以 .jpg 、.png 結尾
     */
    public static final String TYPE_PIC = "image/jpeg";

    /**
     * CAD 檔案,wps不支援
     */
    private static final String TYPE_CAD = "CAD";

    /**
     * zip 檔案
     */
    private static final String TYPE_ZIP = "application/x-zip-compressed";

    private static final String TYPE_WPS = "application/vnd.ms-works";

    private static final String WPS_PACKAGE_NAME = "cn.wps.moffice_eng";
    private static final String CAD_PACKAGE_NAME = "com.gstarmc.android_80";
    private static final String PROVIDER = "你的包名.fileprovider";
    private static final String INTENT_ACTION = "android.intent.action.VIEW";
    private static final String INTENT_CATEGORY = "android.intent.category.DEFAULT";
    private static final String WPS_ADDRESS = "0811837d75804af2b362d443f87eb4c4FriOct1214:44:46CST2018.apk";
    private static final String CAD_ADDRESS = "3ab3bc939d7e4a4e9ffb2fecade682eaFriOct2615:13:26CST2018.apk";
    private static final String TAG = "BrowseFileUtil";

    /**
     * 看我這個類的備註,你就可以瞭解到PC端目前允許那些型別上傳,但是這些型別不一定支援手機開啟,所以,我目前只允許
     * 幾類檔案型別通過手機端開啟
     *
     * @return type 自己根據字尾名來做判斷當前檔案是哪種型別的
     */
    private static String allowFileType(String path) {
        String hzm;
        if (null == path || path.isEmpty()) {
            ToastUtil.newInstance().showToast("本地路徑為空,無法進行瀏覽附件!");
            return "";
        } else {
            hzm = path.substring(path.lastIndexOf(".") + 1);
            if (hzm.isEmpty()) {
                ToastUtil.newInstance().showToast("識別檔案字尾名失敗,無法開啟檔案!");
                return "";
            }
        }
        switch (hzm) {
            case ALLOW_PDF:
                return TYPE_PDF;
            case ALLOW_DOC:
            case ALLOW_DOCS:
            case ALLOW_DOCX:
                return TYPE_WORD;
            case ALLOW_JPG:
            case ALLOW_PNG:
            case ALLOW_JPEG:
                return TYPE_PIC;
            case ALLOW_PPT:
            case ALLOW_PPTX:
                return TYPE_PPT;
            case ALLOW_XLS:
            case ALLOW_XLSX:
                return TYPE_EXCEL;
            case ALLOW_DWG:
                return TYPE_CAD;
            case ALLOW_ZIP:
                return TYPE_ZIP;
            case ALLOW_TXT:
                return TYPE_TXT;
            case ALLOW_WPS:
                return TYPE_WPS;
            default:
                ToastUtil.newInstance().showToast("暫時不支援該瀏覽當前型別( " + hzm + " )的檔案");
                break;
        }
        return "";
    }

    /**
     * @param path     本地要瀏覽的檔案地址
     * @param activity activity
     */
    public static void browseFile(String path, Activity activity) {
        String type = allowFileType(path);
        if (type.isEmpty()) {
            return;
        }
        PackageInfo packageInfo;
        if (type.equals(TYPE_CAD)) {
            // CAD 檔案,目前我準備用
            alertDownloadWps(activity, 1);
        } else {
            //wps 支援
            try {
                packageInfo = Visor.getApplicationContext().getPackageManager().getPackageInfo(WPS_PACKAGE_NAME, 0);
                Uri uri;
                if (packageInfo != null) {
                    Intent intent = new Intent(INTENT_ACTION);
                    intent.addCategory(INTENT_CATEGORY);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT < 24) {
                        uri = Uri.fromFile(new File(path));
                    } else {
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        uri = FileProvider.getUriForFile(activity, PROVIDER, new File(path));
                    }
                    intent.setDataAndType(uri, type);
                    activity.startActivity(intent);
                } else {
                    alertDownloadWps(activity, 0);
                }
            } catch (PackageManager.NameNotFoundException e) {
                alertDownloadWps(activity, 0);
            }
        }
    }

    private static void alertDownloadWps(Activity activity, int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setMessage(type == 0 ? "當前手機沒有安裝wps,是否去下載(支援內網下載)?" : "目前不支援dwg(CAD)檔案檢視,但是提供了去內網下載可以檢視該型別檔案的工具,是否去下載?");
        builder.setPositiveButton("確認", (dialog, which) -> downloadWps(activity, type));
        builder.setNegativeButton("取消", (dialog, which) -> ToastUtil.newInstance().showToast("已取消"));
        AlertDialog dialog = builder.show();
        Observable.just(1).delay(60, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(aLong -> {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        });
    }

    private static void downloadWps(Activity activity, int type) {
        CommonDialog dialog = new CommonDialog(activity, type == 0 ? "正在下載wps,檔案比較大,請耐心等待..." : "正在下載檢視CAD工具,檔案比較大,請耐心等待...");
        dialog.show();
        File file = FileUtil.getOutputMediaFile(9, type == 0 ? "wps.apk" : "cad.apk");
        RestCreator.getDownService().downAcc(type == 0 ? WPS_ADDRESS : CAD_ADDRESS, "0")
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .doOnNext(responseBody -> {
                    try {
                        FileUtil.writeFile(responseBody.byteStream(), file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(inputStream -> {
                    InstallUtil.installApk(activity, file);
                    if (null != dialog && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    VisorLogger.e(TAG, "快取完畢");
                }, e -> {
                    if (null != dialog && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    VisorLogger.e(TAG, e.getMessage());
                });
    }
}

3、呼叫和解釋

呼叫:

BrowseFileUtil.browseFile(entity.getAddress(), getActivity());

解釋:

(1)downWps() 方法 是用來下載wps的,但是這個下載辦法不是通用的,你可以忽視掉,只用其他地方就好。

(2)還是有很多檔案檢視不了,你自己把握。

(3)我把涉及到我的專案的包名的地方全部替換成了"你的包名.",所以你可能拷貝我的類不能直接用,要稍作修改,你自己先看一下我的程式碼再拿有用的用。