├── .gitignore
├── .idea
├── codeStyles
│ └── Project.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── markdown-navigator
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── LICENSE
├── Readme.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── assets
│ ├── test.html
│ └── test
│ │ ├── TestDoc.doc
│ │ ├── TestExcel.xls
│ │ ├── TestPDF.pdf
│ │ └── TestPPT.ppt
│ ├── java
│ └── com
│ │ └── hanlyjiang
│ │ └── library
│ │ └── fileviewer
│ │ └── demo
│ │ ├── FileViewApplication.java
│ │ ├── FileViewDemoMainActivity.java
│ │ └── utils
│ │ ├── FileUtils.java
│ │ └── RunnableUtils.java
│ └── res
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable
│ └── ic_launcher_background.xml
│ ├── layout
│ └── activity_main.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── doc
├── fileviewer-demo-screenshots.gif
└── 无法加载x5内核的解决方案.doc
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── lib_fileviewer
├── .gitignore
├── build.gradle
├── libs
│ ├── lib_mupdf_1.11.1.jar
│ └── tbs_sdk_thirdapp_v4.3.0.265_44165_sharewithdownloadwithfile_withoutGame_obfs_20220303_184913.jar
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── artifex
│ │ └── mupdf
│ │ └── fitz
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ ├── artifex
│ │ │ └── mupdf
│ │ │ │ └── viewer
│ │ │ │ ├── CancellableAsyncTask.java
│ │ │ │ ├── CancellableTaskDefinition.java
│ │ │ │ ├── DocumentActivity.java
│ │ │ │ ├── MuPDFCancellableTaskDefinition.java
│ │ │ │ ├── MuPDFCore.java
│ │ │ │ ├── OutlineActivity.java
│ │ │ │ ├── PageAdapter.java
│ │ │ │ ├── PageView.java
│ │ │ │ ├── ReaderView.java
│ │ │ │ ├── SearchTask.java
│ │ │ │ ├── SearchTaskResult.java
│ │ │ │ └── Stepper.java
│ │ │ └── hanlyjiang
│ │ │ └── library
│ │ │ ├── fileviewer
│ │ │ ├── FileViewer.java
│ │ │ ├── tbs
│ │ │ │ └── TBSFileViewActivity.java
│ │ │ └── wps
│ │ │ │ ├── WPSModel.java
│ │ │ │ ├── WPSOpRecv.java
│ │ │ │ └── WPSOpenUtils.java
│ │ │ └── utils
│ │ │ ├── AndroidUtils.java
│ │ │ ├── FileViewerUtils.java
│ │ │ └── IntentUtils.java
│ ├── jniLibs
│ │ ├── arm64-v8a
│ │ │ └── libmupdf_java.so
│ │ ├── armeabi-v7a
│ │ │ └── libmupdf_java.so
│ │ └── armeabi
│ │ │ ├── liblbs.so
│ │ │ └── libmupdf_java.so
│ └── res
│ │ ├── drawable-xxhdpi
│ │ └── ic_go_back.png
│ │ ├── drawable
│ │ ├── button.xml
│ │ ├── common_divider_shape.xml
│ │ ├── ic_chevron_left_white_24dp.xml
│ │ ├── ic_chevron_right_white_24dp.xml
│ │ ├── ic_close_white_24dp.xml
│ │ ├── ic_link_white_24dp.xml
│ │ ├── ic_search_white_24dp.xml
│ │ ├── ic_toc_white_24dp.xml
│ │ ├── page_indicator.xml
│ │ ├── seek_line.xml
│ │ └── seek_thumb.xml
│ │ ├── layout
│ │ ├── activity_tbs_file_view_layout.xml
│ │ └── document_activity.xml
│ │ └── values
│ │ ├── colors.xml
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── artifex
│ └── mupdf
│ └── fitz
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | /local.properties
3 | /.idea/workspace.xml
4 | /.idea/libraries
5 | #/.idea/misc.xml
6 | #/.idea/modules.xml
7 | .DS_Store
8 | /build
9 | /captures
10 |
11 |
12 | # Built application files
13 | *.apk
14 | *.ap_
15 |
16 | # Files for the ART/Dalvik VM
17 | *.dex
18 |
19 | # Java class files
20 | *.class
21 |
22 | # Generated files
23 | bin/
24 | gen/
25 | out/
26 |
27 | # Gradle files
28 | .gradle/
29 | build/
30 |
31 | # Local configuration file (sdk path, etc)
32 | local.properties
33 |
34 | # Proguard folder generated by Eclipse
35 | proguard/
36 |
37 | # Log Files
38 | *.log
39 |
40 | # Android Studio Navigation editor temp files
41 | .navigation/
42 |
43 | # Android Studio captures folder
44 | captures/
45 |
46 | # Intellij
47 | *.iml
48 | .idea/workspace.xml
49 | .idea/tasks.xml
50 | .idea/gradle.xml
51 | .idea/dictionaries
52 | .idea/libraries
53 |
54 | # Keystore files
55 | *.jks
56 |
57 | # External native build folder generated in Android Studio 2.2 and later
58 | .externalNativeBuild
59 |
60 | # Google Services (e.g. APIs or Firebase)
61 | google-services.json
62 |
63 | # Freeline
64 | freeline.py
65 | freeline/
66 | freeline_project_description.json
67 |
68 |
69 | # Built application files
70 | *.apk
71 | *.ap_
72 |
73 | # Files for the ART/Dalvik VM
74 | *.dex
75 |
76 | # Java class files
77 | *.class
78 |
79 | # Generated files
80 | bin/
81 | gen/
82 | out/
83 |
84 | # Gradle files
85 | .gradle/
86 | build/
87 |
88 | # Local configuration file (sdk path, etc)
89 | local.properties
90 |
91 | # Proguard folder generated by Eclipse
92 | proguard/
93 |
94 | # Log Files
95 | *.log
96 |
97 | # Android Studio Navigation editor temp files
98 | .navigation/
99 |
100 | # Android Studio captures folder
101 | captures/
102 |
103 | # IntelliJ
104 | *.iml
105 | .idea/workspace.xml
106 | .idea/tasks.xml
107 | .idea/gradle.xml
108 | .idea/assetWizardSettings.xml
109 | .idea/dictionaries
110 | .idea/libraries
111 | .idea/caches
112 |
113 | # Keystore files
114 | # Uncomment the following line if you do not want to check your keystore files in.
115 | #*.jks
116 |
117 | # External native build folder generated in Android Studio 2.2 and later
118 | .externalNativeBuild
119 |
120 | # Google Services (e.g. APIs or Firebase)
121 | google-services.json
122 |
123 | # Freeline
124 | freeline.py
125 | freeline/
126 | freeline_project_description.json
127 |
128 | # fastlane
129 | fastlane/report.xml
130 | fastlane/Preview.html
131 | fastlane/screenshots
132 | fastlane/test_output
133 | fastlane/readme.md
134 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | xmlns:android
14 |
15 | ^$
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | xmlns:.*
25 |
26 | ^$
27 |
28 |
29 | BY_NAME
30 |
31 |
32 |
33 |
34 |
35 |
36 | .*:id
37 |
38 | http://schemas.android.com/apk/res/android
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | .*:name
48 |
49 | http://schemas.android.com/apk/res/android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | name
59 |
60 | ^$
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | style
70 |
71 | ^$
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | .*
81 |
82 | ^$
83 |
84 |
85 | BY_NAME
86 |
87 |
88 |
89 |
90 |
91 |
92 | .*
93 |
94 | http://schemas.android.com/apk/res/android
95 |
96 |
97 | ANDROID_ATTRIBUTE_ORDER
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | .*
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/.idea/markdown-navigator/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 蒋航
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 |
2 | ## 在 Android 上查看word,excel,powerpoint,pdf
3 |
4 | 示例app效果:
5 |
6 | 
7 |
8 | ## 如何使用?
9 | 参考: [示例](app)
10 | * 复制`lib_fileviewer`模块,加入到project
11 | * App中build.gradle中加入以下配置:
12 | ```groovy
13 | ndk {
14 | // 此处必须设置为 armeabi ,TBS 文件浏览不支持其他类型
15 | abiFilters "armeabi"
16 | }
17 | ```
18 | * TBS初始化(在Application中):
19 | ```java
20 | QbSdk.initX5Environment(getApplicationContext(), new QbSdk.PreInitCallback() {
21 | @Override
22 | public void onCoreInitFinished() {
23 | Log.d(TAG, "onCoreInitFinished");
24 | }
25 |
26 | @Override
27 | public void onViewInitFinished(boolean initResult) {
28 | Log.e(TAG, "onViewInitFinished" + initResult);
29 | }
30 | });
31 | ```
32 |
33 | * **查看文件统一入口:**
34 | ```
35 | Uri uri = Uri.fromFile(new File(filePath));
36 | FileViewer.viewFile(context,uri)
37 | ```
38 | * **直接使用mupdf查看:**
39 | ```java
40 | FileViewer.viewPDFWithMuPDFByPath(Context context, String filePath)
41 | ```
42 | 或:
43 | ```java
44 | FileViewer.startMuPDFActivityByUri(Context context, Uri documentUri)
45 | ```
46 |
47 | * **直接使用TBS查看word文档:**
48 | ```
49 | TBSFileViewActivity.viewFile(context, filePath);
50 | ```
51 |
52 | ## 注意事项
53 | 1. office文件无法查看(TBS初始化失败),可以查看这个文档:[无法加载x5内核的解决方案.doc](doc/无法加载x5内核的解决方案.doc)
54 |
55 |
56 | ## 使用到的库:
57 | ### PDF查看: mupdf
58 |
59 | 版本: v1.11.1
60 |
61 |
62 | > 介绍:
63 | > MuPDF is an open source software framework for viewing and converting PDF, XPS, and E-book documents. There are viewers for various platforms, several command line tools, and a software library for building tools and applications.
64 |
65 | 项目地址:
66 | https://mupdf.com/docs/
67 |
68 | Android 文档:
69 | https://mupdf.com/docs/android-sdk.html
70 |
71 | ### word等文件查看 : TBS(腾讯浏览服务)
72 | > **简介:**
73 | > web内核
74 |
75 |
76 | [官方页面](http://x5.tencent.com/)
77 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 30
5 | defaultConfig {
6 | applicationId "com.hanlyjiang.github.fileviewer.demo"
7 | minSdkVersion 19
8 | targetSdkVersion 22
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
12 | ndk {
13 | abiFilters "armeabi", "armeabi-v7a"
14 | }
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | targetCompatibility 1.8
25 | sourceCompatibility 1.8
26 | }
27 | }
28 |
29 | dependencies {
30 | implementation fileTree(dir: 'libs', include: ['*.jar'])
31 | implementation 'androidx.appcompat:appcompat:1.0.0'
32 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
33 | testImplementation 'junit:junit:4.12'
34 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
35 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
36 | // https://github.com/googlesamples/easypermissions
37 | implementation 'pub.devrel:easypermissions:1.1.0'
38 | implementation project(':lib_fileviewer')
39 | }
40 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
22 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
35 |
36 |
37 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/assets/test/TestDoc.doc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/assets/test/TestDoc.doc
--------------------------------------------------------------------------------
/app/src/main/assets/test/TestExcel.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/assets/test/TestExcel.xls
--------------------------------------------------------------------------------
/app/src/main/assets/test/TestPDF.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/assets/test/TestPDF.pdf
--------------------------------------------------------------------------------
/app/src/main/assets/test/TestPPT.ppt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/assets/test/TestPPT.ppt
--------------------------------------------------------------------------------
/app/src/main/java/com/hanlyjiang/library/fileviewer/demo/FileViewApplication.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.demo;
2 |
3 | import android.app.Application;
4 | import android.util.Log;
5 |
6 | import com.hanlyjiang.library.fileviewer.demo.utils.FileUtils;
7 | import com.tencent.smtt.sdk.QbSdk;
8 |
9 | import java.io.File;
10 | import java.io.IOException;
11 |
12 |
13 | /**
14 | * 测试Application,用于初始化X5内核
15 | *
16 | * @author hanlyjiang
17 | */
18 | public class FileViewApplication extends Application {
19 |
20 | public static String FILE_DIR = "/sdcard/Downloads/test/";
21 | public static final String TAG = "TBSInit";
22 |
23 | @Override
24 | public void onCreate() {
25 | super.onCreate();
26 | initX5Web();
27 | FILE_DIR = new File(getFilesDir(), "test").getAbsolutePath() + File.separator;
28 | try {
29 | FileUtils.copyAssetsDir(this, "test", FILE_DIR);
30 | } catch (IOException e) {
31 | e.printStackTrace();
32 | }
33 | }
34 |
35 | private void initX5Web() {
36 | Log.i(TAG, "QbSdk.initX5Environment");
37 | QbSdk.initX5Environment(getApplicationContext(), new QbSdk.PreInitCallback() {
38 | @Override
39 | public void onCoreInitFinished() {
40 | Log.d(TAG, "onCoreInitFinished");
41 | }
42 |
43 | @Override
44 | public void onViewInitFinished(boolean initResult) {
45 | Log.e(TAG, "onViewInitFinished:" + initResult);
46 | }
47 | });
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hanlyjiang/library/fileviewer/demo/FileViewDemoMainActivity.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.demo;
2 |
3 | import android.Manifest;
4 | import android.graphics.PixelFormat;
5 | import android.net.Uri;
6 | import android.os.Bundle;
7 | import androidx.annotation.NonNull;
8 | import androidx.appcompat.app.AppCompatActivity;
9 | import android.util.Log;
10 | import android.widget.Toast;
11 |
12 | import com.hanlyjiang.library.fileviewer.FileViewer;
13 | import com.hanlyjiang.library.fileviewer.tbs.TBSFileViewActivity;
14 | import com.tencent.smtt.sdk.WebView;
15 |
16 | import java.io.File;
17 |
18 | import pub.devrel.easypermissions.AfterPermissionGranted;
19 | import pub.devrel.easypermissions.EasyPermissions;
20 | import pub.devrel.easypermissions.PermissionRequest;
21 |
22 | import static com.hanlyjiang.library.fileviewer.demo.FileViewApplication.FILE_DIR;
23 |
24 |
25 | public class FileViewDemoMainActivity extends AppCompatActivity {
26 |
27 | private static final int RC_WRITE_STOREGE = 1;
28 | private static final String TAG = "TBSInit";
29 | protected WebView tbsWebView;
30 |
31 | @Override
32 | protected void onCreate(Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 | getWindow().setFormat(PixelFormat.TRANSLUCENT);
35 | super.setContentView(R.layout.activity_main);
36 | initView();
37 | initWebView();
38 | requestPermissions();
39 | }
40 |
41 | private void requestPermissions() {
42 | String[] perms = new String[]{
43 | Manifest.permission.WRITE_EXTERNAL_STORAGE,
44 | Manifest.permission.READ_EXTERNAL_STORAGE,
45 | Manifest.permission.READ_PHONE_STATE
46 | };
47 | if (!EasyPermissions.hasPermissions(this, perms)) {
48 | EasyPermissions.requestPermissions(
49 | new PermissionRequest.Builder(this, RC_WRITE_STOREGE, perms)
50 | .setRationale("请求权限")
51 | .setPositiveButtonText("确认")
52 | .setNegativeButtonText("取消")
53 | .build());
54 | }
55 | }
56 |
57 |
58 | private void initWebView() {
59 | tbsWebView = (WebView) findViewById(R.id.tbs_webView);
60 | tbsWebView.loadUrl("file:///android_asset/test.html");
61 | tbsWebView.setDrawingCacheEnabled(true);
62 | }
63 |
64 |
65 | private void initView() {
66 | findViewById(R.id.btn_open_pdf_with_mupdf).setOnClickListener(view -> {
67 | String fileName = getFilePath("TestPDF.pdf");
68 | startMuPDFActivityWithExampleFile(fileName);
69 | });
70 | findViewById(R.id.btn_open_pdf_with_tbs).setOnClickListener((view) -> {
71 | openFileWithTbs(getFilePath("TestPDF.pdf"));
72 | });
73 | findViewById(R.id.btn_open_doc_with_tbs).setOnClickListener(view -> openFileWithTbs(getFilePath("TestDoc.doc")));
74 | findViewById(R.id.btn_open_ppt_with_tbs).setOnClickListener(view -> openFileWithTbs(getFilePath("TestPPT.ppt")));
75 | findViewById(R.id.btn_open_excel_with_tbs).setOnClickListener(view -> openFileWithTbs(getFilePath("TestExcel.xls")));
76 | }
77 |
78 | @NonNull
79 | private String getFilePath(String fileName) {
80 | return new File(FILE_DIR + fileName).getAbsolutePath();
81 | }
82 |
83 | private void openFileWithTbs(String filePath) {
84 | Log.d(TAG, "Open File: " + filePath);
85 | TBSFileViewActivity.viewFile(this, filePath);
86 | }
87 |
88 | public void startMuPDFActivityWithExampleFile(String fileName) {
89 | File file = new File(fileName);
90 | if (!file.isFile()) {
91 | Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
92 | return;
93 | }
94 | Uri uri = Uri.fromFile(file);
95 | FileViewer.startMuPDFActivityByUri(this, uri);
96 | }
97 |
98 |
99 | @Override
100 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
101 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
102 | // Forward results to EasyPermissions
103 | EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
104 | }
105 |
106 | @AfterPermissionGranted(RC_WRITE_STOREGE)
107 | private void methodRequiresTwoPermission() {
108 | String[] perms = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION};
109 | if (EasyPermissions.hasPermissions(this, perms)) {
110 | // Already have permission, do the thing
111 | // ...
112 | } else {
113 | // Do not have permissions, request them now
114 | EasyPermissions.requestPermissions(this, "请求权限",
115 | RC_WRITE_STOREGE, perms);
116 | }
117 | }
118 |
119 | }
120 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hanlyjiang/library/fileviewer/demo/utils/FileUtils.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.demo.utils;
2 |
3 | import android.content.Context;
4 |
5 | import java.io.File;
6 | import java.io.FileOutputStream;
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 |
10 |
11 | public class FileUtils {
12 |
13 | /**
14 | * 拷贝Asset文件夹到sd卡
15 | *
16 | * @param context
17 | * @param fromDir 如果拷贝assets ,则传入 ""
18 | * @param destDir 目的地
19 | * @throws IOException
20 | */
21 | public static void copyAssetsDir(Context context, String fromDir, String destDir) throws IOException {
22 | String[] files = context.getAssets().list(fromDir);
23 | for (String f : files) {
24 | copyFile(context.getAssets().open(fromDir + File.separator + f), destDir + File.separator + f);
25 | }
26 | }
27 |
28 | public static void copyFile(InputStream in, String newPath) {
29 | new File(newPath).getParentFile().mkdirs();
30 | try (
31 | InputStream inStream = in;
32 | FileOutputStream fs = new FileOutputStream(newPath)
33 | ) {
34 | int byteread;
35 | byte[] buffer = new byte[4096];
36 | while ((byteread = inStream.read(buffer)) != -1) {
37 | fs.write(buffer, 0, byteread);
38 | fs.flush();
39 | }
40 | } catch (Exception e) {
41 | e.printStackTrace();
42 | }
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hanlyjiang/library/fileviewer/demo/utils/RunnableUtils.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.demo.utils;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 |
7 | import java.util.concurrent.Callable;
8 | import java.util.concurrent.ExecutorService;
9 | import java.util.concurrent.Future;
10 | import java.util.concurrent.LinkedBlockingDeque;
11 | import java.util.concurrent.ThreadPoolExecutor;
12 | import java.util.concurrent.TimeUnit;
13 |
14 |
15 | /**
16 | * 替代之前封装在MapActivity中的 任务执行函数
17 | *
18 | * Created by hanlyjiang on 2016/12/5.
19 | */
20 | public class RunnableUtils {
21 |
22 | private static final ExecutorService EXECUTOR = getExecutorService();
23 |
24 | private static ExecutorService getExecutorService() {
25 | if (EXECUTOR == null) {
26 | return new ThreadPoolExecutor(2, 2, 60,
27 | TimeUnit.SECONDS, new LinkedBlockingDeque<>(), r -> new Thread(r, "RunnableUtils"));
28 | }
29 | return EXECUTOR;
30 | }
31 |
32 | private static UiHandler sUiHandler = new UiHandler(Looper.getMainLooper());
33 |
34 | /**
35 | * 在UI线程中执行一个Runnable
36 | *
37 | * @param task 要执行的任务
38 | */
39 | public static void postUi(Runnable task) {
40 | postUiWork(task);
41 | }
42 |
43 | /**
44 | * 在UI线程中执行一个Runnable
45 | *
46 | * @param task 要执行的任务
47 | * @param delay 延迟(MILLISECONDS) 1000ms = 1s
48 | */
49 | public static void postUi(Runnable task, int delay) {
50 | postUiWork(task, delay);
51 | }
52 |
53 | /**
54 | * 在后台 线程中执行一个 Callable
55 | *
56 | * @param callableTask 要执行的任务
57 | * @return Future 对象
58 | */
59 | public static Future executeOnWorkThread(Callable callableTask) {
60 | return EXECUTOR.submit(callableTask);
61 | }
62 |
63 | /**
64 | * 在IO 线程中执行一个Runnable
65 | *
66 | * @param task 要执行的任务
67 | */
68 | public static void executeOnWorkThread(Runnable task) {
69 | EXECUTOR.execute(task);
70 | }
71 |
72 |
73 | private static void postUiWork(Runnable runnable, int delay) {
74 | Message msg = sUiHandler.obtainMessage();
75 | msg.obj = runnable;
76 | msg.arg1 = delay;
77 | if (sUiHandler == null) {
78 | sUiHandler = new UiHandler(Looper.getMainLooper());
79 | }
80 | sUiHandler.sendMessage(msg);
81 | }
82 |
83 | private static void postUiWork(Runnable runnable) {
84 | if (sUiHandler == null) {
85 | sUiHandler = new UiHandler(Looper.getMainLooper());
86 | }
87 | sUiHandler.post(runnable);
88 | }
89 |
90 | private static class UiHandler extends Handler {
91 |
92 | UiHandler(Looper looper) {
93 | super(looper);
94 | }
95 |
96 | @Override
97 | public void handleMessage(Message msg) {
98 | super.handleMessage(msg);
99 | if (msg.obj != null) {
100 | if (msg.arg1 > 0) {
101 | postDelayed((Runnable) msg.obj, msg.arg1);
102 | } else {
103 | post((Runnable) msg.obj);
104 | }
105 | }
106 | }
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
18 |
19 |
24 |
25 |
30 |
31 |
36 |
37 |
42 |
43 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 文件浏览Demo
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 |
5 | repositories {
6 | google()
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:7.0.0'
11 |
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | google()
21 | jcenter()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 | ext{
29 | compileSdkVersion =30
30 | buildToolsVersion="30.0.3"
31 | minSdkVersion=15
32 | targetSdkVersion=26
33 | }
--------------------------------------------------------------------------------
/doc/fileviewer-demo-screenshots.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/doc/fileviewer-demo-screenshots.gif
--------------------------------------------------------------------------------
/doc/无法加载x5内核的解决方案.doc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/doc/无法加载x5内核的解决方案.doc
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | android.enableJetifier=true
10 | android.useAndroidX=true
11 | org.gradle.jvmargs=-Xmx1536m
12 | # When configured, Gradle will run in incubating parallel mode.
13 | # This option should only be used with decoupled projects. More details, visit
14 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
15 | # org.gradle.parallel=true
16 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon May 24 10:19:12 CST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/lib_fileviewer/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/lib_fileviewer/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 |
7 | defaultConfig {
8 | minSdkVersion rootProject.ext.minSdkVersion
9 | targetSdkVersion rootProject.ext.targetSdkVersion
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
14 | }
15 |
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 |
23 | }
24 |
25 | dependencies {
26 | // implementation fileTree(include: ['*.jar'], dir: 'libs')
27 | implementation 'androidx.appcompat:appcompat:1.0.0'
28 | testImplementation 'junit:junit:4.13.2'
29 | androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
30 | exclude group: 'com.android.support', module: 'support-annotations'
31 | })
32 | api files("libs/tbs_sdk_thirdapp_v4.3.0.265_44165_sharewithdownloadwithfile_withoutGame_obfs_20220303_184913.jar")
33 | api files("libs/lib_mupdf_1.11.1.jar")
34 | // api 'com.tencent.tbs.tbssdk:sdk:43903'
35 | }
36 |
--------------------------------------------------------------------------------
/lib_fileviewer/libs/lib_mupdf_1.11.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/lib_fileviewer/libs/lib_mupdf_1.11.1.jar
--------------------------------------------------------------------------------
/lib_fileviewer/libs/tbs_sdk_thirdapp_v4.3.0.265_44165_sharewithdownloadwithfile_withoutGame_obfs_20220303_184913.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/lib_fileviewer/libs/tbs_sdk_thirdapp_v4.3.0.265_44165_sharewithdownloadwithfile_withoutGame_obfs_20220303_184913.jar
--------------------------------------------------------------------------------
/lib_fileviewer/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/androidTest/java/com/artifex/mupdf/fitz/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.fitz;
2 |
3 | import android.content.Context;
4 | import androidx.test.platform.app.InstrumentationRegistry;
5 | import androidx.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.assertEquals;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getInstrumentation().getContext();
23 |
24 | assertEquals("com.artifex.mupdf.fitz.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/CancellableAsyncTask.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.os.AsyncTask;
4 |
5 | import java.util.concurrent.CancellationException;
6 | import java.util.concurrent.ExecutionException;
7 |
8 | // Ideally this would be a subclass of AsyncTask, however the cancel() method is final, and cannot
9 | // be overridden. I felt that having two different, but similar cancel methods was a bad idea.
10 | public class CancellableAsyncTask {
11 | private final AsyncTask asyncTask;
12 | private final CancellableTaskDefinition ourTask;
13 |
14 | public CancellableAsyncTask(final CancellableTaskDefinition task) {
15 | if (task == null)
16 | throw new IllegalArgumentException();
17 |
18 | this.ourTask = task;
19 | asyncTask = new AsyncTask() {
20 | @Override
21 | protected Result doInBackground(Params... params) {
22 | return task.doInBackground(params);
23 | }
24 |
25 | @Override
26 | protected void onPreExecute() {
27 | CancellableAsyncTask.this.onPreExecute();
28 | }
29 |
30 | @Override
31 | protected void onPostExecute(Result result) {
32 | CancellableAsyncTask.this.onPostExecute(result);
33 | task.doCleanup();
34 | }
35 |
36 | @Override
37 | protected void onCancelled(Result result) {
38 | task.doCleanup();
39 | }
40 | };
41 | }
42 |
43 | public void onPreExecute() {
44 |
45 | }
46 |
47 | public void onPostExecute(Result result) {
48 |
49 | }
50 |
51 | public void cancel() {
52 | this.asyncTask.cancel(true);
53 | ourTask.doCancel();
54 |
55 | try {
56 | this.asyncTask.get();
57 | } catch (InterruptedException e) {
58 | } catch (ExecutionException e) {
59 | } catch (CancellationException e) {
60 | }
61 | }
62 |
63 | public void execute(Params... params) {
64 | asyncTask.execute(params);
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/CancellableTaskDefinition.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | public interface CancellableTaskDefinition {
4 | public Result doInBackground(Params... params);
5 |
6 | public void doCancel();
7 |
8 | public void doCleanup();
9 | }
10 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/DocumentActivity.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.content.DialogInterface.OnCancelListener;
8 | import android.content.Intent;
9 | import android.content.SharedPreferences;
10 | import android.content.res.Resources;
11 | import android.graphics.Color;
12 | import android.net.Uri;
13 | import android.os.Bundle;
14 | import android.os.Handler;
15 | import android.text.Editable;
16 | import android.text.TextUtils;
17 | import android.text.TextWatcher;
18 | import android.text.method.PasswordTransformationMethod;
19 | import android.view.KeyEvent;
20 | import android.view.Menu;
21 | import android.view.View;
22 | import android.view.Window;
23 | import android.view.WindowManager;
24 | import android.view.animation.Animation;
25 | import android.view.animation.TranslateAnimation;
26 | import android.view.inputmethod.EditorInfo;
27 | import android.view.inputmethod.InputMethodManager;
28 | import android.widget.EditText;
29 | import android.widget.ImageButton;
30 | import android.widget.RelativeLayout;
31 | import android.widget.SeekBar;
32 | import android.widget.TextView;
33 | import android.widget.ViewAnimator;
34 |
35 | import com.artifex.mupdf.R;
36 |
37 | import java.io.ByteArrayOutputStream;
38 | import java.io.IOException;
39 | import java.io.InputStream;
40 | import java.util.ArrayList;
41 | import java.util.Locale;
42 |
43 | public class DocumentActivity extends Activity {
44 | private final int OUTLINE_REQUEST = 0;
45 |
46 | ;
47 | private final Handler mHandler = new Handler();
48 | private MuPDFCore core;
49 | private String mFileName;
50 | private ReaderView mDocView;
51 | private View mButtonsView;
52 | private boolean mButtonsVisible;
53 | private EditText mPasswordView;
54 | private TextView mFilenameView;
55 | private SeekBar mPageSlider;
56 | private int mPageSliderRes;
57 | private TextView mPageNumberView;
58 | private ImageButton mSearchButton;
59 | private ImageButton mOutlineButton;
60 | private ViewAnimator mTopBarSwitcher;
61 | private ImageButton mLinkButton;
62 | private TopBarMode mTopBarMode = TopBarMode.Main;
63 | private ImageButton mSearchBack;
64 | private ImageButton mSearchFwd;
65 | private ImageButton mSearchClose;
66 | private EditText mSearchText;
67 | private SearchTask mSearchTask;
68 | private AlertDialog.Builder mAlertBuilder;
69 | private boolean mLinkHighlight = false;
70 | private boolean mAlertsActive = false;
71 | private AlertDialog mAlertDialog;
72 | private ArrayList mFlatOutline;
73 |
74 | private MuPDFCore openFile(String path) {
75 | int lastSlashPos = path.lastIndexOf('/');
76 | mFileName = new String(lastSlashPos == -1
77 | ? path
78 | : path.substring(lastSlashPos + 1));
79 | System.out.println("Trying to open " + path);
80 | try {
81 | core = new MuPDFCore(path);
82 | } catch (Exception e) {
83 | System.out.println(e);
84 | return null;
85 | } catch (OutOfMemoryError e) {
86 | // out of memory is not an Exception, so we catch it separately.
87 | System.out.println(e);
88 | return null;
89 | }
90 | return core;
91 | }
92 |
93 | private MuPDFCore openBuffer(byte buffer[], String magic) {
94 | System.out.println("Trying to open byte buffer");
95 | try {
96 | core = new MuPDFCore(buffer, magic);
97 | } catch (Exception e) {
98 | System.out.println(e);
99 | return null;
100 | }
101 | return core;
102 | }
103 |
104 | /**
105 | * Called when the activity is first created.
106 | */
107 | @Override
108 | public void onCreate(final Bundle savedInstanceState) {
109 | super.onCreate(savedInstanceState);
110 |
111 | requestWindowFeature(Window.FEATURE_NO_TITLE);
112 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
113 |
114 | mAlertBuilder = new AlertDialog.Builder(this);
115 |
116 | if (core == null) {
117 | if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
118 | mFileName = savedInstanceState.getString("FileName");
119 | }
120 | }
121 | if (core == null) {
122 | Intent intent = getIntent();
123 | byte buffer[] = null;
124 |
125 | if (Intent.ACTION_VIEW.equals(intent.getAction())) {
126 | Uri uri = intent.getData();
127 | System.out.println("URI to open is: " + uri);
128 | if (uri.getScheme().equals("file")) {
129 | String path = uri.getPath();
130 | core = openFile(path);
131 | } else {
132 | try {
133 | InputStream is = getContentResolver().openInputStream(uri);
134 | int len;
135 | ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();
136 | byte[] data = new byte[16384];
137 | while ((len = is.read(data, 0, data.length)) != -1) {
138 | bufferStream.write(data, 0, len);
139 | }
140 | bufferStream.flush();
141 | buffer = bufferStream.toByteArray();
142 | is.close();
143 | } catch (IOException e) {
144 | String reason = e.toString();
145 | Resources res = getResources();
146 | AlertDialog alert = mAlertBuilder.create();
147 | setTitle(String.format(Locale.ROOT, res.getString(R.string.cannot_open_document_Reason), reason));
148 | alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dismiss),
149 | new DialogInterface.OnClickListener() {
150 |
151 | @Override
152 | public void onClick(DialogInterface dialog, int which) {
153 | finish();
154 | }
155 | });
156 | alert.show();
157 | return;
158 | }
159 | core = openBuffer(buffer, intent.getType());
160 | }
161 | SearchTaskResult.set(null);
162 | }
163 | if (core != null && core.needsPassword()) {
164 | requestPassword(savedInstanceState);
165 | return;
166 | }
167 | if (core != null && core.countPages() == 0) {
168 | core = null;
169 | }
170 | }
171 | if (core == null) {
172 | AlertDialog alert = mAlertBuilder.create();
173 | alert.setTitle(R.string.cannot_open_document);
174 | alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dismiss),
175 | new DialogInterface.OnClickListener() {
176 | @Override
177 | public void onClick(DialogInterface dialog, int which) {
178 | finish();
179 | }
180 | });
181 | alert.setOnCancelListener(new OnCancelListener() {
182 | @Override
183 | public void onCancel(DialogInterface dialog) {
184 | finish();
185 | }
186 | });
187 | alert.show();
188 | return;
189 | }
190 |
191 | createUI(savedInstanceState);
192 | }
193 |
194 | public void requestPassword(final Bundle savedInstanceState) {
195 | mPasswordView = new EditText(this);
196 | mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
197 | mPasswordView.setTransformationMethod(new PasswordTransformationMethod());
198 |
199 | AlertDialog alert = mAlertBuilder.create();
200 | alert.setTitle("Enter password");
201 | alert.setView(mPasswordView);
202 | alert.setButton(AlertDialog.BUTTON_POSITIVE, "确定",
203 | new DialogInterface.OnClickListener() {
204 |
205 | @Override
206 | public void onClick(DialogInterface dialog, int which) {
207 | if (core.authenticatePassword(mPasswordView.getText().toString())) {
208 | createUI(savedInstanceState);
209 | } else {
210 | requestPassword(savedInstanceState);
211 | }
212 | }
213 | });
214 | alert.setButton(AlertDialog.BUTTON_NEGATIVE, "取消",
215 | new DialogInterface.OnClickListener() {
216 | @Override
217 | public void onClick(DialogInterface dialog, int which) {
218 | finish();
219 | }
220 | });
221 | alert.show();
222 | }
223 |
224 | public void createUI(Bundle savedInstanceState) {
225 | if (core == null) {
226 | return;
227 | }
228 |
229 | // Now create the UI.
230 | // First create the document view
231 | mDocView = new ReaderView(this) {
232 | @Override
233 | protected void onMoveToChild(int i) {
234 | if (core == null) {
235 | return;
236 | }
237 |
238 | mPageNumberView.setText(String.format(Locale.ROOT, "%d / %d", i + 1, core.countPages()));
239 | mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes);
240 | mPageSlider.setProgress(i * mPageSliderRes);
241 | super.onMoveToChild(i);
242 | }
243 |
244 | @Override
245 | protected void onTapMainDocArea() {
246 | if (!mButtonsVisible) {
247 | showButtons();
248 | } else {
249 | if (mTopBarMode == TopBarMode.Main) {
250 | hideButtons();
251 | }
252 | }
253 | }
254 |
255 | @Override
256 | protected void onDocMotion() {
257 | hideButtons();
258 | }
259 | };
260 | mDocView.setAdapter(new PageAdapter(this, core));
261 |
262 | mSearchTask = new SearchTask(this, core) {
263 | @Override
264 | protected void onTextFound(SearchTaskResult result) {
265 | SearchTaskResult.set(result);
266 | // Ask the ReaderView to move to the resulting page
267 | mDocView.setDisplayedViewIndex(result.pageNumber);
268 | // Make the ReaderView act on the change to SearchTaskResult
269 | // via overridden onChildSetup method.
270 | mDocView.resetupChildren();
271 | }
272 | };
273 |
274 | // Make the buttons overlay, and store all its
275 | // controls in variables
276 | makeButtonsView();
277 |
278 | // Set up the page slider
279 | int smax = Math.max(core.countPages() - 1, 1);
280 | mPageSliderRes = ((10 + smax - 1) / smax) * 2;
281 |
282 | // Set the file-name text
283 | String docTitle = core.getTitle();
284 | if (!TextUtils.isEmpty(docTitle)) {
285 | mFilenameView.setText(docTitle);
286 | } else {
287 | mFilenameView.setText(mFileName);
288 | }
289 |
290 | // Activate the seekbar
291 | mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
292 | @Override
293 | public void onStopTrackingTouch(SeekBar seekBar) {
294 | mDocView.pushHistory();
295 | mDocView.setDisplayedViewIndex((seekBar.getProgress() + mPageSliderRes / 2) / mPageSliderRes);
296 | }
297 |
298 | @Override
299 | public void onStartTrackingTouch(SeekBar seekBar) {
300 | }
301 |
302 | @Override
303 | public void onProgressChanged(SeekBar seekBar, int progress,
304 | boolean fromUser) {
305 | updatePageNumView((progress + mPageSliderRes / 2) / mPageSliderRes);
306 | }
307 | });
308 |
309 | // Activate the search-preparing button
310 | mSearchButton.setOnClickListener(new View.OnClickListener() {
311 | @Override
312 | public void onClick(View v) {
313 | searchModeOn();
314 | }
315 | });
316 |
317 | mSearchClose.setOnClickListener(new View.OnClickListener() {
318 | @Override
319 | public void onClick(View v) {
320 | searchModeOff();
321 | }
322 | });
323 |
324 | // Search invoking buttons are disabled while there is no text specified
325 | mSearchBack.setEnabled(false);
326 | mSearchFwd.setEnabled(false);
327 | mSearchBack.setColorFilter(Color.argb(255, 128, 128, 128));
328 | mSearchFwd.setColorFilter(Color.argb(255, 128, 128, 128));
329 |
330 | // React to interaction with the text widget
331 | mSearchText.addTextChangedListener(new TextWatcher() {
332 |
333 | @Override
334 | public void afterTextChanged(Editable s) {
335 | boolean haveText = s.toString().length() > 0;
336 | setButtonEnabled(mSearchBack, haveText);
337 | setButtonEnabled(mSearchFwd, haveText);
338 |
339 | // Remove any previous search results
340 | if (SearchTaskResult.get() != null && !mSearchText.getText().toString().equals(SearchTaskResult.get().txt)) {
341 | SearchTaskResult.set(null);
342 | mDocView.resetupChildren();
343 | }
344 | }
345 |
346 | @Override
347 | public void beforeTextChanged(CharSequence s, int start, int count,
348 | int after) {
349 | }
350 |
351 | @Override
352 | public void onTextChanged(CharSequence s, int start, int before,
353 | int count) {
354 | }
355 | });
356 |
357 | //React to Done button on keyboard
358 | mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
359 | @Override
360 | public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
361 | if (actionId == EditorInfo.IME_ACTION_DONE) {
362 | search(1);
363 | }
364 | return false;
365 | }
366 | });
367 |
368 | mSearchText.setOnKeyListener(new View.OnKeyListener() {
369 | @Override
370 | public boolean onKey(View v, int keyCode, KeyEvent event) {
371 | if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
372 | search(1);
373 | }
374 | return false;
375 | }
376 | });
377 |
378 | // Activate search invoking buttons
379 | mSearchBack.setOnClickListener(new View.OnClickListener() {
380 | @Override
381 | public void onClick(View v) {
382 | search(-1);
383 | }
384 | });
385 | mSearchFwd.setOnClickListener(new View.OnClickListener() {
386 |
387 | @Override
388 | public void onClick(View v) {
389 | search(1);
390 | }
391 | });
392 |
393 | mLinkButton.setOnClickListener(new View.OnClickListener() {
394 | @Override
395 | public void onClick(View v) {
396 | setLinkHighlight(!mLinkHighlight);
397 | }
398 | });
399 |
400 | if (core.hasOutline()) {
401 | mOutlineButton.setOnClickListener(new View.OnClickListener() {
402 | @Override
403 | public void onClick(View v) {
404 | if (mFlatOutline == null) {
405 | mFlatOutline = core.getOutline();
406 | }
407 | if (mFlatOutline != null) {
408 | Intent intent = new Intent(DocumentActivity.this, OutlineActivity.class);
409 | Bundle bundle = new Bundle();
410 | bundle.putInt("POSITION", mDocView.getDisplayedViewIndex());
411 | bundle.putSerializable("OUTLINE", mFlatOutline);
412 | intent.putExtras(bundle);
413 | startActivityForResult(intent, OUTLINE_REQUEST);
414 | }
415 | }
416 | });
417 | } else {
418 | mOutlineButton.setVisibility(View.GONE);
419 | }
420 |
421 | // Reenstate last state if it was recorded
422 | SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
423 | mDocView.setDisplayedViewIndex(prefs.getInt("page" + mFileName, 0));
424 |
425 | if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false)) {
426 | showButtons();
427 | }
428 |
429 |
430 | if (savedInstanceState != null && savedInstanceState.getBoolean("SearchMode", false)) {
431 | searchModeOn();
432 | }
433 |
434 | // Stick the document view and the buttons overlay into a parent view
435 | RelativeLayout layout = new RelativeLayout(this);
436 | layout.setBackgroundColor(Color.DKGRAY);
437 | layout.addView(mDocView);
438 | layout.addView(mButtonsView);
439 | setContentView(layout);
440 | }
441 |
442 | @Override
443 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
444 | switch (requestCode) {
445 | case OUTLINE_REQUEST:
446 | if (resultCode >= RESULT_FIRST_USER) {
447 | mDocView.pushHistory();
448 | mDocView.setDisplayedViewIndex(resultCode - RESULT_FIRST_USER);
449 | }
450 | break;
451 | }
452 | super.onActivityResult(requestCode, resultCode, data);
453 | }
454 |
455 | @Override
456 | protected void onSaveInstanceState(Bundle outState) {
457 | super.onSaveInstanceState(outState);
458 |
459 | if (mFileName != null && mDocView != null) {
460 | outState.putString("FileName", mFileName);
461 |
462 | // Store current page in the prefs against the file name,
463 | // so that we can pick it up each time the file is loaded
464 | // Other info is needed only for screen-orientation change,
465 | // so it can go in the bundle
466 | SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
467 | SharedPreferences.Editor edit = prefs.edit();
468 | edit.putInt("page" + mFileName, mDocView.getDisplayedViewIndex());
469 | edit.apply();
470 | }
471 |
472 | if (!mButtonsVisible) {
473 | outState.putBoolean("ButtonsHidden", true);
474 | }
475 |
476 | if (mTopBarMode == TopBarMode.Search) {
477 | outState.putBoolean("SearchMode", true);
478 | }
479 | }
480 |
481 | @Override
482 | protected void onPause() {
483 | super.onPause();
484 |
485 | if (mSearchTask != null) {
486 | mSearchTask.stop();
487 | }
488 |
489 | if (mFileName != null && mDocView != null) {
490 | SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
491 | SharedPreferences.Editor edit = prefs.edit();
492 | edit.putInt("page" + mFileName, mDocView.getDisplayedViewIndex());
493 | edit.apply();
494 | }
495 | }
496 |
497 | @Override
498 | public void onDestroy() {
499 | if (mDocView != null) {
500 | mDocView.applyToChildren(new ReaderView.ViewMapper() {
501 | @Override
502 | void applyToView(View view) {
503 | ((PageView) view).releaseBitmaps();
504 | }
505 | });
506 | }
507 | if (core != null) {
508 | core.onDestroy();
509 | }
510 | core = null;
511 | super.onDestroy();
512 | }
513 |
514 | private void setButtonEnabled(ImageButton button, boolean enabled) {
515 | button.setEnabled(enabled);
516 | button.setColorFilter(enabled ? Color.argb(255, 255, 255, 255) : Color.argb(255, 128, 128, 128));
517 | }
518 |
519 | private void setLinkHighlight(boolean highlight) {
520 | mLinkHighlight = highlight;
521 | // LINK_COLOR tint
522 | mLinkButton.setColorFilter(highlight ? Color.argb(0xFF, 0x00, 0x66, 0xCC) : Color.argb(0xFF, 255, 255, 255));
523 | // Inform pages of the change.
524 | mDocView.setLinksEnabled(highlight);
525 | }
526 |
527 | private void showButtons() {
528 | if (core == null) {
529 | return;
530 | }
531 | if (!mButtonsVisible) {
532 | mButtonsVisible = true;
533 | // Update page number text and slider
534 | int index = mDocView.getDisplayedViewIndex();
535 | updatePageNumView(index);
536 | mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes);
537 | mPageSlider.setProgress(index * mPageSliderRes);
538 | if (mTopBarMode == TopBarMode.Search) {
539 | mSearchText.requestFocus();
540 | showKeyboard();
541 | }
542 |
543 | Animation anim = new TranslateAnimation(0, 0, -mTopBarSwitcher.getHeight(), 0);
544 | anim.setDuration(200);
545 | anim.setAnimationListener(new Animation.AnimationListener() {
546 | @Override
547 | public void onAnimationStart(Animation animation) {
548 | mTopBarSwitcher.setVisibility(View.VISIBLE);
549 | }
550 |
551 | @Override
552 | public void onAnimationRepeat(Animation animation) {
553 | }
554 |
555 | @Override
556 | public void onAnimationEnd(Animation animation) {
557 | }
558 | });
559 | mTopBarSwitcher.startAnimation(anim);
560 |
561 | anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0);
562 | anim.setDuration(200);
563 | anim.setAnimationListener(new Animation.AnimationListener() {
564 | @Override
565 | public void onAnimationStart(Animation animation) {
566 | mPageSlider.setVisibility(View.VISIBLE);
567 | }
568 |
569 | @Override
570 | public void onAnimationRepeat(Animation animation) {
571 | }
572 |
573 | @Override
574 | public void onAnimationEnd(Animation animation) {
575 | mPageNumberView.setVisibility(View.VISIBLE);
576 | }
577 | });
578 | mPageSlider.startAnimation(anim);
579 | }
580 | }
581 |
582 | private void hideButtons() {
583 | if (mButtonsVisible) {
584 | mButtonsVisible = false;
585 | hideKeyboard();
586 |
587 | Animation anim = new TranslateAnimation(0, 0, 0, -mTopBarSwitcher.getHeight());
588 | anim.setDuration(200);
589 | anim.setAnimationListener(new Animation.AnimationListener() {
590 |
591 | @Override
592 | public void onAnimationStart(Animation animation) {
593 | }
594 |
595 | @Override
596 | public void onAnimationRepeat(Animation animation) {
597 | }
598 |
599 | @Override
600 | public void onAnimationEnd(Animation animation) {
601 | mTopBarSwitcher.setVisibility(View.INVISIBLE);
602 | }
603 | });
604 | mTopBarSwitcher.startAnimation(anim);
605 |
606 | anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight());
607 | anim.setDuration(200);
608 | anim.setAnimationListener(new Animation.AnimationListener() {
609 | @Override
610 | public void onAnimationStart(Animation animation) {
611 | mPageNumberView.setVisibility(View.INVISIBLE);
612 | }
613 |
614 | @Override
615 | public void onAnimationRepeat(Animation animation) {
616 | }
617 |
618 | @Override
619 | public void onAnimationEnd(Animation animation) {
620 | mPageSlider.setVisibility(View.INVISIBLE);
621 | }
622 | });
623 | mPageSlider.startAnimation(anim);
624 | }
625 | }
626 |
627 | private void searchModeOn() {
628 | if (mTopBarMode != TopBarMode.Search) {
629 | mTopBarMode = TopBarMode.Search;
630 | //Focus on EditTextWidget
631 | mSearchText.requestFocus();
632 | showKeyboard();
633 | mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
634 | }
635 | }
636 |
637 | private void searchModeOff() {
638 | if (mTopBarMode == TopBarMode.Search) {
639 | mTopBarMode = TopBarMode.Main;
640 | hideKeyboard();
641 | mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
642 | SearchTaskResult.set(null);
643 | // Make the ReaderView act on the change to mSearchTaskResult
644 | // via overridden onChildSetup method.
645 | mDocView.resetupChildren();
646 | }
647 | }
648 |
649 | private void updatePageNumView(int index) {
650 | if (core == null) {
651 | return;
652 | }
653 | mPageNumberView.setText(String.format(Locale.ROOT, "%d / %d", index + 1, core.countPages()));
654 | }
655 |
656 | private void makeButtonsView() {
657 | mButtonsView = getLayoutInflater().inflate(R.layout.document_activity, null);
658 | mFilenameView = (TextView) mButtonsView.findViewById(R.id.docNameText);
659 | mPageSlider = (SeekBar) mButtonsView.findViewById(R.id.pageSlider);
660 | mPageNumberView = (TextView) mButtonsView.findViewById(R.id.pageNumber);
661 | mSearchButton = (ImageButton) mButtonsView.findViewById(R.id.searchButton);
662 | mOutlineButton = (ImageButton) mButtonsView.findViewById(R.id.outlineButton);
663 | mTopBarSwitcher = (ViewAnimator) mButtonsView.findViewById(R.id.switcher);
664 | mSearchBack = (ImageButton) mButtonsView.findViewById(R.id.searchBack);
665 | mSearchFwd = (ImageButton) mButtonsView.findViewById(R.id.searchForward);
666 | mSearchClose = (ImageButton) mButtonsView.findViewById(R.id.searchClose);
667 | mSearchText = (EditText) mButtonsView.findViewById(R.id.searchText);
668 | mButtonsView.findViewById(R.id.ib_go_back).setOnClickListener(new View.OnClickListener() {
669 | @Override
670 | public void onClick(View v) {
671 | finish();
672 | }
673 | });
674 | mLinkButton = (ImageButton) mButtonsView.findViewById(R.id.linkButton);
675 | mLinkButton.setVisibility(View.GONE);
676 | mTopBarSwitcher.setVisibility(View.INVISIBLE);
677 | mPageNumberView.setVisibility(View.INVISIBLE);
678 |
679 | mPageSlider.setVisibility(View.INVISIBLE);
680 | }
681 |
682 | private void showKeyboard() {
683 | InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
684 | if (imm != null) {
685 | imm.showSoftInput(mSearchText, 0);
686 | }
687 | }
688 |
689 | private void hideKeyboard() {
690 | InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
691 | if (imm != null) {
692 | imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
693 | }
694 | }
695 |
696 | private void search(int direction) {
697 | hideKeyboard();
698 | int displayPage = mDocView.getDisplayedViewIndex();
699 | SearchTaskResult r = SearchTaskResult.get();
700 | int searchPage = r != null ? r.pageNumber : -1;
701 | mSearchTask.go(mSearchText.getText().toString(), direction, displayPage, searchPage);
702 | }
703 |
704 | @Override
705 | public boolean onSearchRequested() {
706 | if (mButtonsVisible && mTopBarMode == TopBarMode.Search) {
707 | hideButtons();
708 | } else {
709 | showButtons();
710 | searchModeOn();
711 | }
712 | return super.onSearchRequested();
713 | }
714 |
715 | @Override
716 | public boolean onPrepareOptionsMenu(Menu menu) {
717 | if (mButtonsVisible && mTopBarMode != TopBarMode.Search) {
718 | hideButtons();
719 | } else {
720 | showButtons();
721 | searchModeOff();
722 | }
723 | return super.onPrepareOptionsMenu(menu);
724 | }
725 |
726 | @Override
727 | protected void onStart() {
728 | super.onStart();
729 | }
730 |
731 | @Override
732 | protected void onStop() {
733 | super.onStop();
734 | }
735 |
736 | @Override
737 | public void onBackPressed() {
738 | if (!mDocView.popHistory()) {
739 | super.onBackPressed();
740 | }
741 | }
742 |
743 | /* The core rendering instance */
744 | enum TopBarMode {
745 | Main, Search, More
746 | }
747 |
748 |
749 | }
750 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/MuPDFCancellableTaskDefinition.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import com.artifex.mupdf.fitz.Cookie;
4 |
5 | public abstract class MuPDFCancellableTaskDefinition implements CancellableTaskDefinition {
6 | private Cookie cookie;
7 |
8 | public MuPDFCancellableTaskDefinition() {
9 | this.cookie = new Cookie();
10 | }
11 |
12 | @Override
13 | public void doCancel() {
14 | if (cookie == null)
15 | return;
16 |
17 | cookie.abort();
18 | }
19 |
20 | @Override
21 | public void doCleanup() {
22 | if (cookie == null)
23 | return;
24 |
25 | cookie.destroy();
26 | cookie = null;
27 | }
28 |
29 | @Override
30 | public final Result doInBackground(Params... params) {
31 | return doInBackground(cookie, params);
32 | }
33 |
34 | public abstract Result doInBackground(Cookie cookie, Params... params);
35 | }
36 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/MuPDFCore.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.PointF;
5 | import android.graphics.RectF;
6 |
7 | import com.artifex.mupdf.fitz.Cookie;
8 | import com.artifex.mupdf.fitz.DisplayList;
9 | import com.artifex.mupdf.fitz.Document;
10 | import com.artifex.mupdf.fitz.Link;
11 | import com.artifex.mupdf.fitz.Matrix;
12 | import com.artifex.mupdf.fitz.Outline;
13 | import com.artifex.mupdf.fitz.Page;
14 | import com.artifex.mupdf.fitz.Rect;
15 | import com.artifex.mupdf.fitz.RectI;
16 | import com.artifex.mupdf.fitz.android.AndroidDrawDevice;
17 |
18 | import java.util.ArrayList;
19 |
20 | public class MuPDFCore {
21 | private int resolution;
22 | private Document doc;
23 | private Outline[] outline;
24 | private int pageCount = -1;
25 | private int currentPage;
26 | private Page page;
27 | private float pageWidth;
28 | private float pageHeight;
29 | private DisplayList displayList;
30 |
31 | public MuPDFCore(String filename) {
32 | doc = Document.openDocument(filename);
33 | pageCount = doc.countPages();
34 | resolution = 160;
35 | currentPage = -1;
36 | }
37 |
38 | public MuPDFCore(byte buffer[], String magic) {
39 | doc = Document.openDocument(buffer, magic);
40 | pageCount = doc.countPages();
41 | resolution = 160;
42 | currentPage = -1;
43 | }
44 |
45 | public String getTitle() {
46 | return doc.getMetaData(Document.META_INFO_TITLE);
47 | }
48 |
49 | public int countPages() {
50 | return pageCount;
51 | }
52 |
53 | private synchronized void gotoPage(int pageNum) {
54 | /* TODO: page cache */
55 | if (pageNum > pageCount - 1)
56 | pageNum = pageCount - 1;
57 | else if (pageNum < 0)
58 | pageNum = 0;
59 | if (pageNum != currentPage) {
60 | currentPage = pageNum;
61 | if (page != null)
62 | page.destroy();
63 | page = null;
64 | if (displayList != null)
65 | displayList.destroy();
66 | displayList = null;
67 | page = doc.loadPage(pageNum);
68 | Rect b = page.getBounds();
69 | pageWidth = b.x1 - b.x0;
70 | pageHeight = b.y1 - b.y0;
71 | }
72 | }
73 |
74 | public synchronized PointF getPageSize(int pageNum) {
75 | gotoPage(pageNum);
76 | return new PointF(pageWidth, pageHeight);
77 | }
78 |
79 | public synchronized void onDestroy() {
80 | if (displayList != null)
81 | displayList.destroy();
82 | displayList = null;
83 | if (page != null)
84 | page.destroy();
85 | page = null;
86 | if (doc != null)
87 | doc.destroy();
88 | doc = null;
89 | }
90 |
91 | public synchronized void drawPage(Bitmap bm, int pageNum,
92 | int pageW, int pageH,
93 | int patchX, int patchY,
94 | int patchW, int patchH,
95 | Cookie cookie) {
96 | // if bitmap is recycle,just return , because some async task will drawpage after bitmap
97 | if (bm != null && bm.isRecycled()) {
98 | return;
99 | }
100 | gotoPage(pageNum);
101 |
102 | if (displayList == null)
103 | displayList = page.toDisplayList(false);
104 |
105 | float zoom = resolution / 72;
106 | Matrix ctm = new Matrix(zoom, zoom);
107 | RectI bbox = new RectI(page.getBounds().transform(ctm));
108 | float xscale = (float) pageW / (float) (bbox.x1 - bbox.x0);
109 | float yscale = (float) pageH / (float) (bbox.y1 - bbox.y0);
110 | ctm.scale(xscale, yscale);
111 | if (bm != null && bm.isRecycled()) {
112 | return;
113 | }
114 | AndroidDrawDevice dev = new AndroidDrawDevice(bm, patchX, patchY);
115 | displayList.run(dev, ctm, cookie);
116 | dev.destroy();
117 | }
118 |
119 | public synchronized void updatePage(Bitmap bm, int pageNum,
120 | int pageW, int pageH,
121 | int patchX, int patchY,
122 | int patchW, int patchH,
123 | Cookie cookie) {
124 | drawPage(bm, pageNum, pageW, pageH, patchX, patchY, patchW, patchH, cookie);
125 | }
126 |
127 | public synchronized Link[] getPageLinks(int pageNum) {
128 | gotoPage(pageNum);
129 | return page.getLinks();
130 | }
131 |
132 | public synchronized RectF[] searchPage(int pageNum, String text) {
133 | gotoPage(pageNum);
134 | Rect[] rs = page.search(text);
135 | RectF[] rfs = new RectF[rs.length];
136 | for (int i = 0; i < rs.length; ++i)
137 | rfs[i] = new RectF(rs[i].x0, rs[i].y0, rs[i].x1, rs[i].y1);
138 | return rfs;
139 | }
140 |
141 | public synchronized boolean hasOutline() {
142 | if (outline == null)
143 | outline = doc.loadOutline();
144 | return outline != null;
145 | }
146 |
147 | private void flattenOutlineNodes(ArrayList result, Outline list[], String indent) {
148 | for (Outline node : list) {
149 | if (node.title != null)
150 | result.add(new OutlineActivity.Item(indent + node.title, node.page));
151 | if (node.down != null)
152 | flattenOutlineNodes(result, node.down, indent + " ");
153 | }
154 | }
155 |
156 | public synchronized ArrayList getOutline() {
157 | ArrayList result = new ArrayList();
158 | flattenOutlineNodes(result, outline, "");
159 | return result;
160 | }
161 |
162 | public synchronized boolean needsPassword() {
163 | return doc.needsPassword();
164 | }
165 |
166 | public synchronized boolean authenticatePassword(String password) {
167 | return doc.authenticatePassword(password);
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/OutlineActivity.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.app.ListActivity;
4 | import android.os.Bundle;
5 | import android.view.View;
6 | import android.view.Window;
7 | import android.view.WindowManager;
8 | import android.widget.ArrayAdapter;
9 | import android.widget.ListView;
10 |
11 | import java.io.Serializable;
12 | import java.util.ArrayList;
13 |
14 | public class OutlineActivity extends ListActivity {
15 | protected ArrayAdapter- adapter;
16 |
17 | public void onCreate(Bundle savedInstanceState) {
18 | super.onCreate(savedInstanceState);
19 | requestWindowFeature(Window.FEATURE_NO_TITLE);
20 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
21 |
22 | adapter = new ArrayAdapter
- (this, android.R.layout.simple_list_item_1);
23 | setListAdapter(adapter);
24 |
25 | Bundle bundle = getIntent().getExtras();
26 | int currentPage = bundle.getInt("POSITION");
27 | ArrayList
- outline = (ArrayList
- ) bundle.getSerializable("OUTLINE");
28 | int found = -1;
29 | for (int i = 0; i < outline.size(); ++i) {
30 | Item item = outline.get(i);
31 | if (found < 0 && item.page >= currentPage)
32 | found = i;
33 | adapter.add(item);
34 | }
35 | if (found >= 0)
36 | setSelection(found);
37 | }
38 |
39 | protected void onListItemClick(ListView l, View v, int position, long id) {
40 | Item item = adapter.getItem(position);
41 | setResult(RESULT_FIRST_USER + item.page);
42 | finish();
43 | }
44 |
45 | public static class Item implements Serializable {
46 | public String title;
47 | public int page;
48 |
49 | public Item(String title, int page) {
50 | this.title = title;
51 | this.page = page;
52 | }
53 |
54 | public String toString() {
55 | return title;
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/PageAdapter.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.graphics.Point;
6 | import android.graphics.PointF;
7 | import android.os.AsyncTask;
8 | import android.util.SparseArray;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.widget.BaseAdapter;
12 |
13 | public class PageAdapter extends BaseAdapter {
14 | private final Context mContext;
15 | private final MuPDFCore mCore;
16 | private final SparseArray mPageSizes = new SparseArray();
17 | private Bitmap mSharedHqBm;
18 |
19 | public PageAdapter(Context c, MuPDFCore core) {
20 | mContext = c;
21 | mCore = core;
22 | }
23 |
24 | public int getCount() {
25 | return mCore.countPages();
26 | }
27 |
28 | public Object getItem(int position) {
29 | return null;
30 | }
31 |
32 | public long getItemId(int position) {
33 | return 0;
34 | }
35 |
36 | public void releaseBitmaps() {
37 | // recycle and release the shared bitmap.
38 | if (mSharedHqBm != null)
39 | mSharedHqBm.recycle();
40 | mSharedHqBm = null;
41 | }
42 |
43 | public View getView(final int position, View convertView, ViewGroup parent) {
44 | final PageView pageView;
45 | if (convertView == null) {
46 | if (mSharedHqBm == null || mSharedHqBm.getWidth() != parent.getWidth() || mSharedHqBm.getHeight() != parent.getHeight())
47 | mSharedHqBm = Bitmap.createBitmap(parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
48 |
49 | pageView = new PageView(mContext, mCore, new Point(parent.getWidth(), parent.getHeight()), mSharedHqBm);
50 | } else {
51 | pageView = (PageView) convertView;
52 | }
53 |
54 | PointF pageSize = mPageSizes.get(position);
55 | if (pageSize != null) {
56 | // We already know the page size. Set it up
57 | // immediately
58 | pageView.setPage(position, pageSize);
59 | } else {
60 | // Page size as yet unknown. Blank it for now, and
61 | // start a background task to find the size
62 | pageView.blank(position);
63 | AsyncTask sizingTask = new AsyncTask() {
64 | @Override
65 | protected PointF doInBackground(Void... arg0) {
66 | return mCore.getPageSize(position);
67 | }
68 |
69 | @Override
70 | protected void onPostExecute(PointF result) {
71 | super.onPostExecute(result);
72 | // We now know the page size
73 | mPageSizes.put(position, result);
74 | // Check that this view hasn't been reused for
75 | // another page since we started
76 | if (pageView.getPage() == position)
77 | pageView.setPage(position, result);
78 | }
79 | };
80 |
81 | sizingTask.execute((Void) null);
82 | }
83 | return pageView;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/PageView.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.graphics.Bitmap.Config;
6 | import android.graphics.Canvas;
7 | import android.graphics.Color;
8 | import android.graphics.Matrix;
9 | import android.graphics.Paint;
10 | import android.graphics.Point;
11 | import android.graphics.PointF;
12 | import android.graphics.Rect;
13 | import android.graphics.RectF;
14 | import android.os.AsyncTask;
15 | import android.os.Build;
16 | import android.os.Handler;
17 | import android.view.View;
18 | import android.view.ViewGroup;
19 | import android.widget.ImageView;
20 | import android.widget.ProgressBar;
21 |
22 | import com.artifex.mupdf.fitz.Cookie;
23 | import com.artifex.mupdf.fitz.Link;
24 |
25 | // Make our ImageViews opaque to optimize redraw
26 | class OpaqueImageView extends ImageView {
27 |
28 | public OpaqueImageView(Context context) {
29 | super(context);
30 | }
31 |
32 | @Override
33 | public boolean isOpaque() {
34 | return true;
35 | }
36 | }
37 |
38 | public class PageView extends ViewGroup {
39 | private static final int HIGHLIGHT_COLOR = 0x80cc6600;
40 | private static final int LINK_COLOR = 0x800066cc;
41 | private static final int BOX_COLOR = 0xFF4444FF;
42 | private static final int BACKGROUND_COLOR = 0xFFFFFFFF;
43 | private static final int PROGRESS_DIALOG_DELAY = 200;
44 | protected final Context mContext;
45 | private final MuPDFCore mCore;
46 | private final Handler mHandler = new Handler();
47 | protected int mPageNumber;
48 | protected Point mSize; // Size of page at minimum zoom
49 | protected float mSourceScale;
50 | protected Link mLinks[];
51 | private Point mParentSize;
52 | private ImageView mEntire; // Image rendered at minimum zoom
53 | private Bitmap mEntireBm;
54 | private Matrix mEntireMat;
55 | private AsyncTask mGetLinkInfo;
56 | private CancellableAsyncTask mDrawEntire;
57 | private Point mPatchViewSize; // View size on the basis of which the patch was created
58 | private Rect mPatchArea;
59 | private ImageView mPatch;
60 | private Bitmap mPatchBm;
61 | private CancellableAsyncTask mDrawPatch;
62 | private RectF mSearchBoxes[];
63 | private View mSearchView;
64 | private boolean mIsBlank;
65 | private boolean mHighlightLinks;
66 | private ProgressBar mBusyIndicator;
67 |
68 | public PageView(Context c, MuPDFCore core, Point parentSize, Bitmap sharedHqBm) {
69 | super(c);
70 | mContext = c;
71 | mCore = core;
72 | mParentSize = parentSize;
73 | setBackgroundColor(BACKGROUND_COLOR);
74 | mEntireBm = Bitmap.createBitmap(parentSize.x, parentSize.y, Config.ARGB_8888);
75 | mPatchBm = sharedHqBm;
76 | mEntireMat = new Matrix();
77 | }
78 |
79 | private void reinit() {
80 | // Cancel pending render task
81 | if (mDrawEntire != null) {
82 | mDrawEntire.cancel();
83 | mDrawEntire = null;
84 | }
85 |
86 | if (mDrawPatch != null) {
87 | mDrawPatch.cancel();
88 | mDrawPatch = null;
89 | }
90 |
91 | if (mGetLinkInfo != null) {
92 | mGetLinkInfo.cancel(true);
93 | mGetLinkInfo = null;
94 | }
95 |
96 | mIsBlank = true;
97 | mPageNumber = 0;
98 |
99 | if (mSize == null)
100 | mSize = mParentSize;
101 |
102 | if (mEntire != null) {
103 | mEntire.setImageBitmap(null);
104 | mEntire.invalidate();
105 | }
106 |
107 | if (mPatch != null) {
108 | mPatch.setImageBitmap(null);
109 | mPatch.invalidate();
110 | }
111 |
112 | mPatchViewSize = null;
113 | mPatchArea = null;
114 |
115 | mSearchBoxes = null;
116 | mLinks = null;
117 | }
118 |
119 | public void releaseResources() {
120 | reinit();
121 |
122 | if (mBusyIndicator != null) {
123 | removeView(mBusyIndicator);
124 | mBusyIndicator = null;
125 | }
126 | }
127 |
128 | public void releaseBitmaps() {
129 | reinit();
130 |
131 | // recycle bitmaps before releasing them.
132 |
133 | if (mEntireBm != null)
134 | mEntireBm.recycle();
135 | mEntireBm = null;
136 |
137 | if (mPatchBm != null)
138 | mPatchBm.recycle();
139 | mPatchBm = null;
140 | }
141 |
142 | public void blank(int page) {
143 | reinit();
144 | mPageNumber = page;
145 |
146 | if (mBusyIndicator == null) {
147 | mBusyIndicator = new ProgressBar(mContext);
148 | mBusyIndicator.setIndeterminate(true);
149 | addView(mBusyIndicator);
150 | }
151 |
152 | setBackgroundColor(BACKGROUND_COLOR);
153 | }
154 |
155 | public void setPage(int page, PointF size) {
156 | // Cancel pending render task
157 | if (mDrawEntire != null) {
158 | mDrawEntire.cancel();
159 | mDrawEntire = null;
160 | }
161 |
162 | mIsBlank = false;
163 | // Highlights may be missing because mIsBlank was true on last draw
164 | if (mSearchView != null)
165 | mSearchView.invalidate();
166 |
167 | mPageNumber = page;
168 | if (mEntire == null) {
169 | mEntire = new OpaqueImageView(mContext);
170 | mEntire.setScaleType(ImageView.ScaleType.MATRIX);
171 | addView(mEntire);
172 | }
173 |
174 | // Calculate scaled size that fits within the screen limits
175 | // This is the size at minimum zoom
176 | mSourceScale = Math.min(mParentSize.x / size.x, mParentSize.y / size.y);
177 | Point newSize = new Point((int) (size.x * mSourceScale), (int) (size.y * mSourceScale));
178 | mSize = newSize;
179 |
180 | mEntire.setImageBitmap(null);
181 | mEntire.invalidate();
182 |
183 | // Get the link info in the background
184 | mGetLinkInfo = new AsyncTask() {
185 | protected Link[] doInBackground(Void... v) {
186 | return getLinkInfo();
187 | }
188 |
189 | protected void onPostExecute(Link[] v) {
190 | mLinks = v;
191 | if (mSearchView != null)
192 | mSearchView.invalidate();
193 | }
194 | };
195 |
196 | mGetLinkInfo.execute();
197 |
198 | // Render the page in the background
199 | mDrawEntire = new CancellableAsyncTask(getDrawPageTask(mEntireBm, mSize.x, mSize.y, 0, 0, mSize.x, mSize.y)) {
200 |
201 | @Override
202 | public void onPreExecute() {
203 | setBackgroundColor(BACKGROUND_COLOR);
204 | mEntire.setImageBitmap(null);
205 | mEntire.invalidate();
206 |
207 | if (mBusyIndicator == null) {
208 | mBusyIndicator = new ProgressBar(mContext);
209 | mBusyIndicator.setIndeterminate(true);
210 | addView(mBusyIndicator);
211 | mBusyIndicator.setVisibility(INVISIBLE);
212 | mHandler.postDelayed(new Runnable() {
213 | public void run() {
214 | if (mBusyIndicator != null)
215 | mBusyIndicator.setVisibility(VISIBLE);
216 | }
217 | }, PROGRESS_DIALOG_DELAY);
218 | }
219 | }
220 |
221 | @Override
222 | public void onPostExecute(Void result) {
223 | removeView(mBusyIndicator);
224 | mBusyIndicator = null;
225 | mEntire.setImageBitmap(mEntireBm);
226 | mEntire.invalidate();
227 | setBackgroundColor(Color.TRANSPARENT);
228 |
229 | }
230 | };
231 |
232 | mDrawEntire.execute();
233 |
234 | if (mSearchView == null) {
235 | mSearchView = new View(mContext) {
236 | @Override
237 | protected void onDraw(final Canvas canvas) {
238 | super.onDraw(canvas);
239 | // Work out current total scale factor
240 | // from source to view
241 | final float scale = mSourceScale * (float) getWidth() / (float) mSize.x;
242 | final Paint paint = new Paint();
243 |
244 | if (!mIsBlank && mSearchBoxes != null) {
245 | paint.setColor(HIGHLIGHT_COLOR);
246 | for (RectF rect : mSearchBoxes)
247 | canvas.drawRect(rect.left * scale, rect.top * scale,
248 | rect.right * scale, rect.bottom * scale,
249 | paint);
250 | }
251 |
252 | if (!mIsBlank && mLinks != null && mHighlightLinks) {
253 | paint.setColor(LINK_COLOR);
254 | for (Link link : mLinks)
255 | canvas.drawRect(link.bounds.x0 * scale, link.bounds.y0 * scale,
256 | link.bounds.x1 * scale, link.bounds.y1 * scale,
257 | paint);
258 | }
259 | }
260 | };
261 |
262 | addView(mSearchView);
263 | }
264 | requestLayout();
265 | }
266 |
267 | public void setSearchBoxes(RectF searchBoxes[]) {
268 | mSearchBoxes = searchBoxes;
269 | if (mSearchView != null)
270 | mSearchView.invalidate();
271 | }
272 |
273 | public void setLinkHighlighting(boolean f) {
274 | mHighlightLinks = f;
275 | if (mSearchView != null)
276 | mSearchView.invalidate();
277 | }
278 |
279 | @Override
280 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
281 | int x, y;
282 | switch (MeasureSpec.getMode(widthMeasureSpec)) {
283 | case MeasureSpec.UNSPECIFIED:
284 | x = mSize.x;
285 | break;
286 | default:
287 | x = MeasureSpec.getSize(widthMeasureSpec);
288 | }
289 | switch (MeasureSpec.getMode(heightMeasureSpec)) {
290 | case MeasureSpec.UNSPECIFIED:
291 | y = mSize.y;
292 | break;
293 | default:
294 | y = MeasureSpec.getSize(heightMeasureSpec);
295 | }
296 |
297 | setMeasuredDimension(x, y);
298 |
299 | if (mBusyIndicator != null) {
300 | int limit = Math.min(mParentSize.x, mParentSize.y) / 2;
301 | mBusyIndicator.measure(MeasureSpec.AT_MOST | limit, MeasureSpec.AT_MOST | limit);
302 | }
303 | }
304 |
305 | @Override
306 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
307 | int w = right - left;
308 | int h = bottom - top;
309 |
310 | if (mEntire != null) {
311 | if (mEntire.getWidth() != w || mEntire.getHeight() != h) {
312 | mEntireMat.setScale(w / (float) mSize.x, h / (float) mSize.y);
313 | mEntire.setImageMatrix(mEntireMat);
314 | mEntire.invalidate();
315 | }
316 | mEntire.layout(0, 0, w, h);
317 | }
318 |
319 | if (mSearchView != null) {
320 | mSearchView.layout(0, 0, w, h);
321 | }
322 |
323 | if (mPatchViewSize != null) {
324 | if (mPatchViewSize.x != w || mPatchViewSize.y != h) {
325 | // Zoomed since patch was created
326 | mPatchViewSize = null;
327 | mPatchArea = null;
328 | if (mPatch != null) {
329 | mPatch.setImageBitmap(null);
330 | mPatch.invalidate();
331 | }
332 | } else {
333 | mPatch.layout(mPatchArea.left, mPatchArea.top, mPatchArea.right, mPatchArea.bottom);
334 | }
335 | }
336 |
337 | if (mBusyIndicator != null) {
338 | int bw = mBusyIndicator.getMeasuredWidth();
339 | int bh = mBusyIndicator.getMeasuredHeight();
340 |
341 | mBusyIndicator.layout((w - bw) / 2, (h - bh) / 2, (w + bw) / 2, (h + bh) / 2);
342 | }
343 | }
344 |
345 | public void updateHq(boolean update) {
346 | Rect viewArea = new Rect(getLeft(), getTop(), getRight(), getBottom());
347 | if (viewArea.width() == mSize.x || viewArea.height() == mSize.y) {
348 | // If the viewArea's size matches the unzoomed size, there is no need for an hq patch
349 | if (mPatch != null) {
350 | mPatch.setImageBitmap(null);
351 | mPatch.invalidate();
352 | }
353 | } else {
354 | final Point patchViewSize = new Point(viewArea.width(), viewArea.height());
355 | final Rect patchArea = new Rect(0, 0, mParentSize.x, mParentSize.y);
356 |
357 | // Intersect and test that there is an intersection
358 | if (!patchArea.intersect(viewArea))
359 | return;
360 |
361 | // Offset patch area to be relative to the view top left
362 | patchArea.offset(-viewArea.left, -viewArea.top);
363 |
364 | boolean area_unchanged = patchArea.equals(mPatchArea) && patchViewSize.equals(mPatchViewSize);
365 |
366 | // If being asked for the same area as last time and not because of an update then nothing to do
367 | if (area_unchanged && !update)
368 | return;
369 |
370 | boolean completeRedraw = !(area_unchanged && update);
371 |
372 | // Stop the drawing of previous patch if still going
373 | if (mDrawPatch != null) {
374 | mDrawPatch.cancel();
375 | mDrawPatch = null;
376 | }
377 |
378 | // Create and add the image view if not already done
379 | if (mPatch == null) {
380 | mPatch = new OpaqueImageView(mContext);
381 | mPatch.setScaleType(ImageView.ScaleType.MATRIX);
382 | addView(mPatch);
383 | mSearchView.bringToFront();
384 | }
385 |
386 | CancellableTaskDefinition task;
387 |
388 | if (completeRedraw)
389 | task = getDrawPageTask(mPatchBm, patchViewSize.x, patchViewSize.y,
390 | patchArea.left, patchArea.top,
391 | patchArea.width(), patchArea.height());
392 | else
393 | task = getUpdatePageTask(mPatchBm, patchViewSize.x, patchViewSize.y,
394 | patchArea.left, patchArea.top,
395 | patchArea.width(), patchArea.height());
396 |
397 | mDrawPatch = new CancellableAsyncTask(task) {
398 |
399 | public void onPostExecute(Void result) {
400 | mPatchViewSize = patchViewSize;
401 | mPatchArea = patchArea;
402 | mPatch.setImageBitmap(mPatchBm);
403 | mPatch.invalidate();
404 | //requestLayout();
405 | // Calling requestLayout here doesn't lead to a later call to layout. No idea
406 | // why, but apparently others have run into the problem.
407 | mPatch.layout(mPatchArea.left, mPatchArea.top, mPatchArea.right, mPatchArea.bottom);
408 | }
409 | };
410 |
411 | mDrawPatch.execute();
412 | }
413 | }
414 |
415 | public void update() {
416 | // Cancel pending render task
417 | if (mDrawEntire != null) {
418 | mDrawEntire.cancel();
419 | mDrawEntire = null;
420 | }
421 |
422 | if (mDrawPatch != null) {
423 | mDrawPatch.cancel();
424 | mDrawPatch = null;
425 | }
426 |
427 | // Render the page in the background
428 | mDrawEntire = new CancellableAsyncTask(getUpdatePageTask(mEntireBm, mSize.x, mSize.y, 0, 0, mSize.x, mSize.y)) {
429 |
430 | public void onPostExecute(Void result) {
431 | mEntire.setImageBitmap(mEntireBm);
432 | mEntire.invalidate();
433 | }
434 | };
435 |
436 | mDrawEntire.execute();
437 |
438 | updateHq(true);
439 | }
440 |
441 | public void removeHq() {
442 | // Stop the drawing of the patch if still going
443 | if (mDrawPatch != null) {
444 | mDrawPatch.cancel();
445 | mDrawPatch = null;
446 | }
447 |
448 | // And get rid of it
449 | mPatchViewSize = null;
450 | mPatchArea = null;
451 | if (mPatch != null) {
452 | mPatch.setImageBitmap(null);
453 | mPatch.invalidate();
454 | }
455 | }
456 |
457 | public int getPage() {
458 | return mPageNumber;
459 | }
460 |
461 | @Override
462 | public boolean isOpaque() {
463 | return true;
464 | }
465 |
466 | public Link hitLink(float x, float y) {
467 | // Since link highlighting was implemented, the super class
468 | // PageView has had sufficient information to be able to
469 | // perform this method directly. Making that change would
470 | // make MuPDFCore.hitLinkPage superfluous.
471 | float scale = mSourceScale * (float) getWidth() / (float) mSize.x;
472 | float docRelX = (x - getLeft()) / scale;
473 | float docRelY = (y - getTop()) / scale;
474 |
475 | if (mLinks != null)
476 | for (Link l : mLinks)
477 | if (l.bounds.contains(docRelX, docRelY))
478 | return l;
479 | return null;
480 | }
481 |
482 | protected CancellableTaskDefinition getDrawPageTask(final Bitmap bm, final int sizeX, final int sizeY,
483 | final int patchX, final int patchY, final int patchWidth, final int patchHeight) {
484 | return new MuPDFCancellableTaskDefinition() {
485 | @Override
486 | public Void doInBackground(Cookie cookie, Void... params) {
487 | // Workaround bug in Android Honeycomb 3.x, where the bitmap generation count
488 | // is not incremented when drawing.
489 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB &&
490 | Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH)
491 | bm.eraseColor(0);
492 | mCore.drawPage(bm, mPageNumber, sizeX, sizeY, patchX, patchY, patchWidth, patchHeight, cookie);
493 | return null;
494 | }
495 | };
496 |
497 | }
498 |
499 | protected CancellableTaskDefinition getUpdatePageTask(final Bitmap bm, final int sizeX, final int sizeY,
500 | final int patchX, final int patchY, final int patchWidth, final int patchHeight) {
501 | return new MuPDFCancellableTaskDefinition() {
502 | @Override
503 | public Void doInBackground(Cookie cookie, Void... params) {
504 | // Workaround bug in Android Honeycomb 3.x, where the bitmap generation count
505 | // is not incremented when drawing.
506 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB &&
507 | Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH)
508 | bm.eraseColor(0);
509 | mCore.updatePage(bm, mPageNumber, sizeX, sizeY, patchX, patchY, patchWidth, patchHeight, cookie);
510 | return null;
511 | }
512 | };
513 | }
514 |
515 | protected Link[] getLinkInfo() {
516 | return mCore.getPageLinks(mPageNumber);
517 | }
518 | }
519 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/SearchTask.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.app.AlertDialog;
4 | import android.app.ProgressDialog;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.graphics.RectF;
8 | import android.os.AsyncTask;
9 | import android.os.Handler;
10 |
11 | import com.artifex.mupdf.R;
12 |
13 | class ProgressDialogX extends ProgressDialog {
14 | private boolean mCancelled = false;
15 |
16 | public ProgressDialogX(Context context) {
17 | super(context);
18 | }
19 |
20 | public boolean isCancelled() {
21 | return mCancelled;
22 | }
23 |
24 | @Override
25 | public void cancel() {
26 | mCancelled = true;
27 | super.cancel();
28 | }
29 | }
30 |
31 | public abstract class SearchTask {
32 | private static final int SEARCH_PROGRESS_DELAY = 200;
33 | private final Context mContext;
34 | private final MuPDFCore mCore;
35 | private final Handler mHandler;
36 | private final AlertDialog.Builder mAlertBuilder;
37 | private AsyncTask mSearchTask;
38 |
39 | public SearchTask(Context context, MuPDFCore core) {
40 | mContext = context;
41 | mCore = core;
42 | mHandler = new Handler();
43 | mAlertBuilder = new AlertDialog.Builder(context);
44 | }
45 |
46 | protected abstract void onTextFound(SearchTaskResult result);
47 |
48 | public void stop() {
49 | if (mSearchTask != null) {
50 | mSearchTask.cancel(true);
51 | mSearchTask = null;
52 | }
53 | }
54 |
55 | public void go(final String text, int direction, int displayPage, int searchPage) {
56 | if (mCore == null)
57 | return;
58 | stop();
59 |
60 | final int increment = direction;
61 | final int startIndex = searchPage == -1 ? displayPage : searchPage + increment;
62 |
63 | final ProgressDialogX progressDialog = new ProgressDialogX(mContext);
64 | progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
65 | progressDialog.setTitle(mContext.getString(R.string.searching_));
66 | progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
67 | public void onCancel(DialogInterface dialog) {
68 | stop();
69 | }
70 | });
71 | progressDialog.setMax(mCore.countPages());
72 |
73 | mSearchTask = new AsyncTask() {
74 | @Override
75 | protected SearchTaskResult doInBackground(Void... params) {
76 | int index = startIndex;
77 |
78 | while (0 <= index && index < mCore.countPages() && !isCancelled()) {
79 | publishProgress(index);
80 | RectF searchHits[] = mCore.searchPage(index, text);
81 |
82 | if (searchHits != null && searchHits.length > 0)
83 | return new SearchTaskResult(text, index, searchHits);
84 |
85 | index += increment;
86 | }
87 | return null;
88 | }
89 |
90 | @Override
91 | protected void onPostExecute(SearchTaskResult result) {
92 | progressDialog.cancel();
93 | if (result != null) {
94 | onTextFound(result);
95 | } else {
96 | mAlertBuilder.setTitle(SearchTaskResult.get() == null ? R.string.text_not_found : R.string.no_further_occurrences_found);
97 | AlertDialog alert = mAlertBuilder.create();
98 | alert.setButton(AlertDialog.BUTTON_POSITIVE, mContext.getString(R.string.dismiss),
99 | (DialogInterface.OnClickListener) null);
100 | alert.show();
101 | }
102 | }
103 |
104 | @Override
105 | protected void onCancelled() {
106 | progressDialog.cancel();
107 | }
108 |
109 | @Override
110 | protected void onProgressUpdate(Integer... values) {
111 | progressDialog.setProgress(values[0].intValue());
112 | }
113 |
114 | @Override
115 | protected void onPreExecute() {
116 | super.onPreExecute();
117 | mHandler.postDelayed(new Runnable() {
118 | public void run() {
119 | if (!progressDialog.isCancelled()) {
120 | progressDialog.show();
121 | progressDialog.setProgress(startIndex);
122 | }
123 | }
124 | }, SEARCH_PROGRESS_DELAY);
125 | }
126 | };
127 |
128 | mSearchTask.execute();
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/SearchTaskResult.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.graphics.RectF;
4 |
5 | public class SearchTaskResult {
6 | static private SearchTaskResult singleton;
7 | public final String txt;
8 | public final int pageNumber;
9 | public final RectF searchBoxes[];
10 |
11 | SearchTaskResult(String _txt, int _pageNumber, RectF _searchBoxes[]) {
12 | txt = _txt;
13 | pageNumber = _pageNumber;
14 | searchBoxes = _searchBoxes;
15 | }
16 |
17 | static public SearchTaskResult get() {
18 | return singleton;
19 | }
20 |
21 | static public void set(SearchTaskResult r) {
22 | singleton = r;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/artifex/mupdf/viewer/Stepper.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.viewer;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.os.Build;
5 | import android.view.View;
6 |
7 | public class Stepper {
8 | protected final View mPoster;
9 | protected final Runnable mTask;
10 | protected boolean mPending;
11 |
12 | public Stepper(View v, Runnable r) {
13 | mPoster = v;
14 | mTask = r;
15 | mPending = false;
16 | }
17 |
18 | @SuppressLint("NewApi")
19 | public void prod() {
20 | if (!mPending) {
21 | mPending = true;
22 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
23 | mPoster.postOnAnimation(new Runnable() {
24 | @Override
25 | public void run() {
26 | mPending = false;
27 | mTask.run();
28 | }
29 | });
30 | } else {
31 | mPoster.post(new Runnable() {
32 | @Override
33 | public void run() {
34 | mPending = false;
35 | mTask.run();
36 | }
37 | });
38 |
39 | }
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/FileViewer.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.net.Uri;
6 | import android.text.TextUtils;
7 | import android.util.Log;
8 |
9 | import com.artifex.mupdf.viewer.DocumentActivity;
10 | import com.hanlyjiang.library.fileviewer.tbs.TBSFileViewActivity;
11 | import com.hanlyjiang.library.utils.FileViewerUtils;
12 |
13 | import java.io.File;
14 |
15 |
16 | /**
17 | * 文件查看入口
18 | *
19 | * @author hanlyjiang on 2017/12/13-16:59.
20 | * @version 1.0
21 | */
22 |
23 | public class FileViewer {
24 |
25 | private static final String DOT = ".";
26 | private static final String FORMAT_UNKNOWN = "unknown";
27 | private static final String FORMAT_PDF = "pdf";
28 | private static final String TAG = "FileViewUtils";
29 | private static final String[] FORMAT_TBS = new String[]{
30 | "doc", "docx",
31 | "ppt", "pptx",
32 | "xls", "xlsx",
33 | "txt",
34 | "pdf",
35 | "epub",
36 | };
37 | private static final String[] FORMAT_IMAGE = new String[]{
38 | "png", "jpg",
39 | "jpeg", "gif",
40 | "bmp",
41 | };
42 |
43 | /**
44 | * 默认的文件查看入口,仅支持下载过的文件
45 | *
46 | * @param context
47 | * @param filePath
48 | */
49 | public static OpenResult viewFile(Context context, String filePath) {
50 | if (context == null) {
51 | log("Context 为null ViewFile! 直接返回");
52 | return OpenResult.failed("Context 为 null");
53 | }
54 |
55 | if (TextUtils.isEmpty(filePath)) {
56 | return OpenResult.failed("FilePath:" + filePath + " is Empty!");
57 | }
58 |
59 | File file = new File(filePath);
60 | if (!file.isFile()) {
61 | return OpenResult.failed("文件不存在 " + filePath + " 不存在");
62 | }
63 |
64 | String format = parseFormat(filePath);
65 | if (FORMAT_UNKNOWN.equals(format)) {
66 | return OpenResult.failed("不支持的文件格式:" + format);
67 | }
68 |
69 | if (isPDF(format)) {
70 | viewPDFWithMuPDFByPath(context, filePath);
71 | log("PDF 格式文件,使用muPDF浏览");
72 | return OpenResult.success();
73 | }
74 |
75 | if (isTBSSupportFile(format)) {
76 | TBSFileViewActivity.viewFile(context, filePath);
77 | log(format + " : TBS默认支持文件类型,使用TBS浏览");
78 | return OpenResult.success();
79 | }
80 |
81 | FileViewerUtils.viewFile4_4(context, filePath);
82 | return OpenResult.success();
83 | }
84 |
85 | private static void log(String msg) {
86 | Log.e(TAG, msg);
87 | }
88 |
89 | public static void viewPDFWithMuPDFByPath(Context context, String filePath) {
90 | Uri uri = Uri.fromFile(new File(filePath));
91 | startMuPDFActivityByUri(context, uri);
92 | }
93 |
94 | public static void startMuPDFActivityByUri(Context context, Uri documentUri) {
95 | Intent intent = new Intent(context, DocumentActivity.class);
96 | intent.setAction(Intent.ACTION_VIEW);
97 | intent.setData(documentUri);
98 | context.startActivity(intent);
99 | }
100 |
101 | /**
102 | * 判断是否为图片文件
103 | *
104 | * @param format 文件后缀
105 | * @return 图片文件 - true
106 | */
107 | private static boolean isImageFile(String format) {
108 | for (String imageFormat : FORMAT_IMAGE) {
109 | if (imageFormat.equalsIgnoreCase(format)) {
110 | return true;
111 | }
112 | }
113 | return false;
114 | }
115 |
116 | /**
117 | * 判断是否是 TBS 文件浏览服务支持的文件格式
118 | *
119 | * @param format
120 | * @return
121 | */
122 | private static boolean isTBSSupportFile(String format) {
123 | for (String tbsFormat : FORMAT_TBS) {
124 | if (tbsFormat.equalsIgnoreCase(format)) {
125 | return true;
126 | }
127 | }
128 | return false;
129 | }
130 |
131 | private static boolean isPDF(String format) {
132 | if (FORMAT_PDF.equalsIgnoreCase(format)) {
133 | return true;
134 | }
135 | return false;
136 | }
137 |
138 | /**
139 | * 解析文件后缀名,不带 "."
140 | *
141 | * @param fileName 文件名(可以为全路径)
142 | * @return 文件后缀名,不带 "."
143 | */
144 | private static String parseFormat(String fileName) {
145 | if (!fileName.contains(DOT)) {
146 | return FORMAT_UNKNOWN;
147 | }
148 | return fileName.substring(fileName.lastIndexOf(".") + 1);
149 | }
150 |
151 | public static class OpenResult {
152 | boolean isSuccess = true;
153 | String failedResult = "";
154 |
155 | OpenResult(boolean isSuccess, String failedResult) {
156 | this.isSuccess = isSuccess;
157 | this.failedResult = failedResult;
158 | }
159 |
160 | static OpenResult success() {
161 | return new OpenResult(true, "");
162 | }
163 |
164 | static OpenResult failed(String result) {
165 | return new OpenResult(false, result);
166 | }
167 |
168 | public boolean isSuccess() {
169 | return isSuccess;
170 | }
171 |
172 | public String getFailedResult() {
173 | return failedResult;
174 | }
175 | }
176 |
177 | }
178 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/tbs/TBSFileViewActivity.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.tbs;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.os.Environment;
7 | import androidx.appcompat.app.AppCompatActivity;
8 | import android.text.TextUtils;
9 | import android.util.Log;
10 | import android.view.MenuItem;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 | import android.widget.FrameLayout;
14 | import android.widget.Toast;
15 |
16 | import com.artifex.mupdf.R;
17 | import com.hanlyjiang.library.utils.FileViewerUtils;
18 | import com.tencent.smtt.sdk.TbsReaderView;
19 |
20 | import java.io.File;
21 |
22 | /**
23 | * 此 Activity 使用 TBS (腾讯浏览服务)查看文件
24 | *
默认支持常见文件类型
25 | *
默认支持类型:
26 | * doc
27 | * docx
28 | * ppt
29 | * pptx
30 | * xls
31 | * xlsx
32 | * txt
33 | * pdf
34 | * epub
35 | *
36 | * intent参数: filePath - 文件路径
37 | *
38 | * @author hanlyjiang
39 | */
40 | public class TBSFileViewActivity extends AppCompatActivity implements TbsReaderView.ReaderCallback {
41 | public static final String FILE_PATH = "filePath";
42 |
43 | private static final String TAG = "TBSFileViewActivity";
44 |
45 | private TbsReaderView mTbsReaderView;
46 | private FrameLayout rootViewParent;
47 |
48 | private ViewGroup errorHandleLayout;
49 | private String filePath;
50 |
51 | public static void viewFile(Context context, String localPath) {
52 | Intent intent = new Intent(context, TBSFileViewActivity.class);
53 | intent.putExtra(FILE_PATH, localPath);
54 | context.startActivity(intent);
55 | }
56 |
57 | public static String getFileName(String filePath) {
58 | if (filePath == null) {
59 | return "";
60 | }
61 | int lastSlashIndex = filePath.lastIndexOf("/") + 1;
62 | if (lastSlashIndex == -1) {
63 | return filePath;
64 | }
65 | int lastDotFromSlashIndex = filePath.indexOf(".", lastSlashIndex);
66 | if (lastDotFromSlashIndex == -1) {
67 | return filePath.substring(lastSlashIndex);
68 | }
69 | return filePath.substring(lastSlashIndex, lastDotFromSlashIndex);
70 | }
71 |
72 | @Override
73 | protected void onCreate(Bundle savedInstanceState) {
74 | super.onCreate(savedInstanceState);
75 | setContentView(R.layout.activity_tbs_file_view_layout);
76 | rootViewParent = (FrameLayout) findViewById(R.id.fl_rootview);
77 | errorHandleLayout = (ViewGroup) findViewById(R.id.ll_error_handle);
78 | initErrorHandleLayout(errorHandleLayout);
79 |
80 | filePath = handleIntent();
81 | if (TextUtils.isEmpty(filePath) || !new File(filePath).isFile()) {
82 | Toast.makeText(this, getString(R.string.file_not_exist), Toast.LENGTH_SHORT).show();
83 | finish();
84 | }
85 |
86 | getSupportActionBar().setTitle(getString(R.string.view_file) + getFileName(filePath));
87 | getSupportActionBar().setDisplayHomeAsUpEnabled(true);
88 |
89 | mTbsReaderView = new TbsReaderView(this, this);
90 | FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
91 | FrameLayout.LayoutParams.MATCH_PARENT,
92 | FrameLayout.LayoutParams.MATCH_PARENT
93 | );
94 | mTbsReaderView.setLayoutParams(layoutParams);
95 | rootViewParent.addView(mTbsReaderView);
96 | displayFile(filePath);
97 | }
98 |
99 | private void initErrorHandleLayout(ViewGroup errorHandleLayout) {
100 | findViewById(R.id.btn_retry_with_tbs).setOnClickListener(new View.OnClickListener() {
101 | @Override
102 | public void onClick(View v) {
103 | displayFile(filePath);
104 | }
105 | });
106 | findViewById(R.id.btn_view_with_other_app).setOnClickListener(new View.OnClickListener() {
107 | @Override
108 | public void onClick(View v) {
109 | FileViewerUtils.viewFile4_4(v.getContext(), filePath);
110 | }
111 | });
112 | }
113 |
114 | private String handleIntent() {
115 | if (getIntent() != null) {
116 | return getIntent().getStringExtra(FILE_PATH);
117 | }
118 | return null;
119 | }
120 |
121 | @Override
122 | public boolean onOptionsItemSelected(MenuItem item) {
123 | switch (item.getItemId()) {
124 | case android.R.id.home:
125 | finish();
126 | return true;
127 | default:
128 | return super.onOptionsItemSelected(item);
129 | }
130 | }
131 |
132 | @Override
133 | public void onCallBackAction(Integer integer, Object long1, Object long2) {
134 | Log.d(TAG, "onCallBackAction " + integer + "," + long1 + "," + long2);
135 | }
136 |
137 | private void displayFile(String fileAbsPath) {
138 | Bundle bundle = new Bundle();
139 | bundle.putString("filePath", fileAbsPath);
140 | bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
141 | // preOpen 需要文件后缀名 用以判断是否支持
142 | boolean result = mTbsReaderView.preOpen(parseFormat(fileAbsPath), true);
143 | if (result) {
144 | mTbsReaderView.openFile(bundle);
145 | mTbsReaderView.setVisibility(View.VISIBLE);
146 | errorHandleLayout.setVisibility(View.GONE);
147 | } else {
148 | mTbsReaderView.setVisibility(View.GONE);
149 | errorHandleLayout.setVisibility(View.VISIBLE);
150 | }
151 | }
152 |
153 |
154 | private String parseFormat(String fileName) {
155 | return fileName.substring(fileName.lastIndexOf(".") + 1);
156 | }
157 |
158 | @Override
159 | protected void onDestroy() {
160 | super.onDestroy();
161 | mTbsReaderView.onStop();
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSModel.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.wps;
2 |
3 | /**
4 | * @author hanlyjiang on 2018/3/22-12:04.
5 | * @version 1.0
6 | */
7 |
8 | class WPSModel {
9 | public static final String OPEN_MODE = "OpenMode";// 打开文件的模式。
10 | public static final String SEND_SAVE_BROAD = "SendSaveBroad";// 文件保存时是否发送广播。
11 | public static final String SEND_CLOSE_BROAD = "SendCloseBroad";// 文件关闭时是否发送广播
12 | public static final String THIRD_PACKAGE = "ThirdPackage";// 第三方的包名,关闭的广播会包含该项。
13 | public static final String CLEAR_BUFFER = "ClearBuffer";// 关闭文件时是否请空临时文件。
14 | public static final String CLEAR_TRACE = "ClearTrace";// 关闭文件时是否删除使用记录。
15 | public static final String CLEAR_FILE = "ClearFile";// 关闭文件时是否删除打开的文件。
16 | public static final String VIEW_PROGRESS = "ViewProgress";// 文件上次查看的进度。
17 | public static final String AUTO_JUMP = "AutoJump";// 是否自动跳转到上次查看的进度。
18 | public static final String SAVE_PATH = "SavePath";// 文件保存路径。
19 | public static final String VIEW_SCALE = "ViewScale";// 文件上次查看的视图的缩放。
20 | public static final String VIEW_SCALE_X = "ViewScrollX";// 文件上次查看的视图的X坐标。
21 | public static final String VIEW_SCALE_Y = "ViewScrollY";// 文件上次查看的视图的Y坐标。
22 | public static final String USER_NAME = "UserName";// 批注的作者。
23 | public static final String HOMEKEY_DOWN = "HomeKeyDown";// 监听home键并发广播
24 | public static final String BACKKEY_DOWN = "BackKeyDown";// 监听back键并发广播
25 | public static final String ENTER_REVISE_MODE = "EnterReviseMode";// 以修订模式打开文档
26 | public static final String CACHE_FILE_INVISIBLE = "CacheFileInvisible";// Wps生成的缓存文件外部是否可见
27 |
28 | public class OpenMode {
29 | public static final String NORMAL = "Normal";// 只读模式
30 | public static final String READ_ONLY = "ReadOnly";// 正常模式
31 | public static final String READ_MODE = "ReadMode";// 打开直接进入阅读器模式
32 | // 仅Word、TXT文档支持
33 | public static final String SAVE_ONLY = "SaveOnly";// 保存模式(打开文件,另存,关闭)
34 | // 仅Word、TXT文档支持
35 | }
36 |
37 | public class ClassName {
38 | public static final String NORMAL = "cn.wps.moffice.documentmanager.PreStartActivity2";// 普通版
39 | public static final String ENGLISH = "cn.wps.moffice.documentmanager.PreStartActivity2";// 英文版
40 | public static final String ENTERPRISE = "cn.wps.moffice.documentmanager.PreStartActivity2";// 企业版
41 | }
42 |
43 | public class PackageName {
44 | public static final String NORMAL = "cn.wps.moffice_eng";// 普通版
45 | public static final String ENGLISH = "cn.wps.moffice_eng";// 英文版
46 | }
47 |
48 | public class Reciver {
49 | public static final String ACTION_BACK = "com.kingsoft.writer.back.key.down";// 返回键广播
50 | public static final String ACTION_HOME = "com.kingsoft.writer.home.key.down";// Home键广播
51 | public static final String ACTION_SAVE = "cn.wps.moffice.file.save";// 保存广播
52 | public static final String ACTION_CLOSE = "cn.wps.moffice.file.close";// 关闭文件广播
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSOpRecv.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.wps;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.util.Log;
7 |
8 |
9 | /**
10 | * @author hanlyjiang on 2018/3/22-12:09.
11 | * @version 1.0
12 | */
13 |
14 | public abstract class WPSOpRecv extends BroadcastReceiver {
15 |
16 | private static final String TAG = "WPSOpRecv";
17 |
18 | /**
19 | * 检测到WPS关闭文件时要启动的Activity
20 | *
21 | * @return
22 | */
23 | protected abstract Class backActivityClass();
24 |
25 | protected abstract void onReceiveWPSSave(Context context, Intent intent);
26 |
27 | void onReceiveWPSClose(Context context, Intent intent) {
28 | Intent newintent = new Intent(context, backActivityClass());
29 | newintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
30 | | Intent.FLAG_ACTIVITY_NEW_TASK);
31 | context.startActivity(newintent);
32 | }
33 |
34 | protected abstract void onReceiveWPSBack(Context context, Intent intent);
35 |
36 | @Override
37 | public void onReceive(Context context, Intent intent) {
38 | String stringExtra = intent.getStringExtra(WPSModel.THIRD_PACKAGE);
39 | boolean isWPSBackToMe = context.getPackageName().contains(stringExtra);
40 | switch (intent.getAction()) {
41 | case WPSModel.Reciver.ACTION_BACK://返回键广播
42 | Log.d(TAG, WPSModel.Reciver.ACTION_BACK);
43 | if (isWPSBackToMe) {
44 | onReceiveWPSBack(context, intent);
45 | }
46 | break;
47 | case WPSModel.Reciver.ACTION_CLOSE://关闭文件时候的广播
48 | Log.d(TAG, WPSModel.Reciver.ACTION_CLOSE + "/" + isWPSBackToMe);
49 | if (isWPSBackToMe) {
50 | onReceiveWPSClose(context, intent);
51 | }
52 | break;
53 | case WPSModel.Reciver.ACTION_HOME://home键广播
54 | Log.d(TAG, WPSModel.Reciver.ACTION_HOME);
55 | break;
56 | case WPSModel.Reciver.ACTION_SAVE://保存广播
57 | Log.d(TAG, WPSModel.Reciver.ACTION_SAVE);
58 | if (isWPSBackToMe) {
59 | onReceiveWPSSave(context, intent);
60 | }
61 | break;
62 | default:
63 | break;
64 | }
65 |
66 | }
67 |
68 | /*
69 | 需要注册如下 BroadcastReceiver
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | */
81 | }
82 |
83 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/fileviewer/wps/WPSOpenUtils.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.fileviewer.wps;
2 |
3 | import android.content.ActivityNotFoundException;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.content.pm.PackageManager;
7 | import android.content.pm.ResolveInfo;
8 | import android.net.Uri;
9 | import android.os.Bundle;
10 | import androidx.annotation.NonNull;
11 | import androidx.fragment.app.Fragment;
12 | import android.util.Log;
13 |
14 | import com.hanlyjiang.library.utils.AndroidUtils;
15 | import com.hanlyjiang.library.utils.FileViewerUtils;
16 |
17 | import java.io.File;
18 | import java.util.List;
19 |
20 |
21 | /**
22 | * WPS打开文件工具
23 | *
24 | * @author hanlyjiang on 2018/3/22-13:49.
25 | * @version 1.0
26 | */
27 |
28 | public class WPSOpenUtils {
29 |
30 |
31 | /**
32 | * 用WPS 打开应用,注意此种方法无法获取
33 | *
34 | * @param filePath 设置好数据了类型的intent
35 | * @param context Context 对象
36 | * @return
37 | */
38 | public static boolean viewOrEditFileWithWPS(@NonNull Context context, String filePath, boolean readOnly) {
39 | return viewOrEditFileWithWPS(new ContextStartWrapper(context), filePath, readOnly, 0);
40 | }
41 |
42 | /**
43 | * 用WPS 打开文档
44 | *
45 | * @param fragment
46 | * @param filePath 设置好数据了类型的intent
47 | * @param readOnly true - 以只读模式打开文档通过StartActivity启动); false - 以编辑模式打开文档(通过StartActivityForResult启动)
48 | * @param requestCode 指定通过StartActivityForResult启动时的requestCode
49 | * @return
50 | */
51 | public static boolean viewOrEditFileWithWPS(@NonNull Fragment fragment, String filePath, boolean readOnly, int requestCode) {
52 | return viewOrEditFileWithWPS(new FragmentStartWrapper(fragment), filePath, readOnly, requestCode);
53 | }
54 |
55 | /**
56 | * 用WPS 打开应用
57 | *
58 | * @param filePath 设置好数据了类型的intent
59 | * @param wrapper ActivityStarterWrapper 对象
60 | * @return
61 | */
62 | protected static boolean viewOrEditFileWithWPS(@NonNull ActivityStarterWrapper wrapper, String filePath, boolean readOnly, int requestCode) {
63 | Intent intent = new Intent();
64 | File file = new File(filePath);
65 | if (!file.isFile()) {
66 | AndroidUtils.showToast(wrapper.getContext(), "文件不存在");
67 | return false;
68 | }
69 | intent.setDataAndType(Uri.fromFile(file), FileViewerUtils.getMimeType(file));
70 | return doRealWPSViewOrEdit(wrapper, intent, readOnly, requestCode);
71 | }
72 |
73 |
74 | /**
75 | * 用WPS 打开应用
76 | *
77 | * @param context Context 对象
78 | * @param intent 设置好数据了类型的intent
79 | * @return
80 | */
81 | protected static boolean doRealWPSViewOrEdit(@NonNull ActivityStarterWrapper context, @NonNull Intent intent,
82 | boolean readOnly, int requestCode) {
83 | Bundle bundle = new Bundle();
84 | bundle.putBoolean(WPSModel.SEND_CLOSE_BROAD, true); // 关闭时是否发送广播
85 | bundle.putBoolean(WPSModel.SEND_SAVE_BROAD, true); // 保存时是否发送广播
86 | bundle.putString(WPSModel.THIRD_PACKAGE, context.getPackageName()); // 第三方应用的包名,用于对改应用合法性的验证
87 | if (readOnly) {
88 | bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.READ_ONLY); // 打开模式
89 | } else {
90 | bundle.putString(WPSModel.OPEN_MODE, WPSModel.OpenMode.NORMAL); // 打开模式
91 | bundle.putBoolean(WPSModel.ENTER_REVISE_MODE, true); // 修订模式
92 | }
93 | bundle.putBoolean(WPSModel.CLEAR_TRACE, true);// 清除打开记录
94 | // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
95 | // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
96 | intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
97 | intent.setAction(Intent.ACTION_VIEW);
98 | intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);
99 | intent.putExtras(bundle);
100 | try {
101 | if (readOnly) {
102 | context.startActivity(Intent.createChooser(intent, "请选择WPS打开文件"));
103 | } else {
104 | context.startActivityForResult(Intent.createChooser(intent, "请选择WPS打开应用"), requestCode);
105 | }
106 | } catch (ActivityNotFoundException exception) {
107 | Log.d("WPSOpenUtils", exception.getMessage());
108 | exception.printStackTrace();
109 | return false;
110 | }
111 | return true;
112 | }
113 |
114 |
115 | /**
116 | * 检测是否有安装 WPS
117 | *
118 | * @param context Context
119 | * @return
120 | */
121 | public static boolean checkWPSInstallation(Context context) {
122 | PackageManager packageManager1 = context.getPackageManager();
123 | Intent intent = new Intent();
124 | intent.setClassName(WPSModel.PackageName.NORMAL, WPSModel.ClassName.NORMAL);
125 | List resolveInfos = packageManager1.queryIntentActivities(intent, PackageManager.MATCH_ALL);
126 | if (resolveInfos == null || resolveInfos.size() == 0) {
127 | return false;
128 | }
129 | boolean found = false;
130 | for (ResolveInfo info : resolveInfos) {
131 | if (info.activityInfo.packageName.toLowerCase().equalsIgnoreCase(WPSModel.PackageName.NORMAL)
132 | || info.activityInfo.name.toLowerCase().equalsIgnoreCase(WPSModel.ClassName.NORMAL)) {
133 | found = true;
134 | break;
135 | }
136 | }
137 | return found;
138 | }
139 |
140 | abstract static class ActivityStarterWrapper {
141 |
142 | protected Context context;
143 |
144 | public ActivityStarterWrapper(Context context) {
145 | this.context = context;
146 | }
147 |
148 | abstract String getPackageName();
149 |
150 | abstract void startActivityForResult(Intent intent, int requestCode);
151 |
152 | abstract void startActivity(Intent intent);
153 |
154 | public Context getContext() {
155 | return context;
156 | }
157 | }
158 |
159 | protected static class ContextStartWrapper extends ActivityStarterWrapper {
160 |
161 | public ContextStartWrapper(Context context) {
162 | super(context);
163 | }
164 |
165 | @Override
166 | String getPackageName() {
167 | return context.getPackageName();
168 | }
169 |
170 | @Override
171 | void startActivityForResult(Intent intent, int requestCode) {
172 | context.startActivity(intent);
173 | }
174 |
175 | @Override
176 | void startActivity(Intent intent) {
177 | context.startActivity(intent);
178 | }
179 | }
180 |
181 | protected static class FragmentStartWrapper extends ActivityStarterWrapper {
182 |
183 | Fragment fragment;
184 |
185 | public FragmentStartWrapper(Fragment fragment) {
186 | super(fragment.getContext());
187 | this.fragment = fragment;
188 | }
189 |
190 | @Override
191 | String getPackageName() {
192 | return (fragment.getContext() == null) ? "" : fragment.getContext().getPackageName();
193 | }
194 |
195 | @Override
196 | void startActivityForResult(Intent intent, int requestCode) {
197 | fragment.startActivityForResult(intent, requestCode);
198 | }
199 |
200 | @Override
201 | void startActivity(Intent intent) {
202 | fragment.startActivity(intent);
203 | }
204 | }
205 | }
206 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/utils/AndroidUtils.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.utils;
2 |
3 | import android.content.Context;
4 | import android.widget.Toast;
5 |
6 |
7 | /**
8 | * Android 平台工具函数
9 | *
10 | * @author hanlyjiang
11 | * @version 1.0
12 | */
13 | public class AndroidUtils {
14 |
15 | /**
16 | * 以 Toast.LENGTH_SHORT 的时长显示toast,内容为 msg
17 | *
18 | * @param context Context
19 | * @param msg 要显示的内容
20 | */
21 | public static void showToast(Context context, String msg) {
22 | if (context == null) return;
23 | Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
24 | }
25 |
26 | /**
27 | * 以 Toast.LENGTH_SHORT 的时长显示toast,内容为 msg
28 | *
29 | * @param context Context
30 | * @param msgResId String id
31 | */
32 | public static void showToast(Context context, int msgResId) {
33 | if (context == null) return;
34 | Toast.makeText(context, context.getResources().getString(msgResId), Toast.LENGTH_SHORT).show();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/utils/FileViewerUtils.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.utils;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.net.Uri;
6 | import android.text.TextUtils;
7 | import android.webkit.MimeTypeMap;
8 |
9 | import com.artifex.mupdf.R;
10 |
11 | import java.io.File;
12 |
13 | /**
14 | * 文件查看相关工具类
15 | *
16 | * @author hanlyjiang 2017/3/13
17 | * @version 1.0
18 | */
19 | public class FileViewerUtils {
20 |
21 | public static final int FILE_EDIT = 0;
22 |
23 | /**
24 | * 查看文件
25 | *
26 | * @param filePath
27 | */
28 | public static void viewFile(Context activity, String filePath) {
29 | File viewFile = new File(filePath);
30 | Intent intent = new Intent();
31 | intent.setDataAndType(Uri.fromFile(viewFile), getMimeType(viewFile));
32 | intent.addCategory("android.intent.category.DEFAULT");
33 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
34 | activity.startActivity(intent);
35 | }
36 |
37 | /**
38 | * Android 4.4 系统上文件查看
39 | *
40 | * @param context
41 | * @param fileName
42 | */
43 | public static void viewFile4_4(Context context, String fileName) {
44 | String ext = getExtension(fileName);
45 | if (TextUtils.isEmpty(ext)) {
46 | AndroidUtils.showToast(context, context.getString(R.string.file_not_recognized));
47 | return;
48 | }
49 | Intent intent = IntentUtils.getFileViewIntent(context, fileName);
50 | if (intent != null) {
51 | Intent newIntent = Intent.createChooser(intent, context.getString(R.string.choose_one_activity_to_open));
52 | context.startActivity(newIntent);
53 | } else {
54 | FileViewerUtils.viewFile(context, fileName);
55 | }
56 | }
57 |
58 | /**
59 | * Gets the extension of a file name, like ".png" or ".jpg".
60 | *
61 | * @param fileName
62 | * @return Extension including the dot("."); "" if there is no extension;
63 | * null if fileName was null.
64 | */
65 | public static String getExtension(String fileName) {
66 | if (fileName == null) {
67 | return null;
68 | }
69 |
70 | int dot = fileName.lastIndexOf(".");
71 | if (dot >= 0) {
72 | return fileName.substring(dot);
73 | } else {
74 | // No extension.
75 | return "";
76 | }
77 | }
78 |
79 |
80 | /**
81 | * Get The MIME type for the given file.
82 | *
83 | * @param file given file
84 | * @return The MIME type for the given file.
85 | */
86 | public static String getMimeType(File file) {
87 |
88 | String extension = getExtension(file.getName());
89 |
90 | if (extension.length() > 0)
91 | return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
92 |
93 | return "application/octet-stream";
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/java/com/hanlyjiang/library/utils/IntentUtils.java:
--------------------------------------------------------------------------------
1 | package com.hanlyjiang.library.utils;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.net.Uri;
6 | import android.text.TextUtils;
7 |
8 | import com.artifex.mupdf.R;
9 |
10 | import java.io.File;
11 |
12 | /**
13 | * @author hanlyjiang on 2018/5/16-16:53.
14 | * @version 1.0
15 | */
16 |
17 | class IntentUtils {
18 |
19 | static final String IS_DOCUMENT = "isDoc";
20 |
21 | /**
22 | * 通过文件后缀名来获取对应的Intent
23 | *
24 | * @param context Context 对象
25 | * @param fileName 文件名称
26 | * @return 对应的Intent 或 null - 不支持的文件类型
27 | */
28 | public static Intent getFileViewIntent(Context context, String fileName) {
29 | String ext = FileViewerUtils.getExtension(fileName);
30 | boolean isDocument = false;
31 | if (TextUtils.isEmpty(ext)) {
32 | AndroidUtils.showToast(context, context.getString(R.string.file_not_recognized));
33 | return null;
34 | }
35 | Intent intent = null;
36 | if (".jpg".equalsIgnoreCase(ext) || ".jpeg".equalsIgnoreCase(ext) || ".png".equalsIgnoreCase(ext) || ".gif".equalsIgnoreCase(ext)) {
37 | intent = getImageFileIntent(fileName);
38 | } else if (".xls".equalsIgnoreCase(ext) || ".xlsx".equalsIgnoreCase(ext) || ".et".equalsIgnoreCase(ext) || ".ett".equalsIgnoreCase(ext)) {
39 | intent = getExcelFileIntent(fileName);
40 | isDocument = true;
41 | } else if (".doc".equalsIgnoreCase(ext) || ".docx".equalsIgnoreCase(ext) || ".wps".equalsIgnoreCase(ext) || ".wpt".equalsIgnoreCase(ext)) {
42 | intent = getWordFileIntent(fileName);
43 | isDocument = true;
44 | } else if (".ppt".equalsIgnoreCase(ext) || ".pptx".equalsIgnoreCase(ext) || ".dps".equalsIgnoreCase(ext) || ".dpt".equalsIgnoreCase(ext)) {
45 | intent = getPptFileIntent(fileName);
46 | isDocument = true;
47 | } else if (".pdf".equalsIgnoreCase(ext)) {
48 | intent = getPdfFileIntent(fileName);
49 | isDocument = true;
50 | } else if (".htm".equalsIgnoreCase(ext) || ".html".equalsIgnoreCase(ext) || ".jsp".equalsIgnoreCase(ext) || ".css".equalsIgnoreCase(ext)) {
51 | intent = getHtmlFileIntent(fileName);
52 | } else if (".txt".equalsIgnoreCase(ext) || ".text".equalsIgnoreCase(ext)) {
53 | intent = getHtmlFileIntent(fileName);
54 | } else if (".mp3".equalsIgnoreCase(ext) || ".wma".equalsIgnoreCase(ext) || ".aar".equalsIgnoreCase(ext) || ".m4a".equalsIgnoreCase(ext)) {
55 | intent = getAudioFileIntent(fileName);
56 | } else if (".mp4".equalsIgnoreCase(ext) || ".avi".equalsIgnoreCase(ext) || ".flv".equalsIgnoreCase(ext)) {
57 | intent = getVideoFileIntent(fileName);
58 | } else {
59 |
60 | }
61 | if (intent != null) {
62 | intent.putExtra(IS_DOCUMENT, isDocument);
63 | }
64 | return intent;
65 | }
66 |
67 | static Intent getExcelFileIntent(String param) {
68 | Intent intent = new Intent("android.intent.action.VIEW");
69 | intent.addCategory("android.intent.category.DEFAULT");
70 | Uri uri = Uri.fromFile(new File(param));
71 | intent.setDataAndType(uri, "application/vnd.ms-excel");
72 | return intent;
73 | }
74 |
75 | static Intent getHtmlFileIntent(String param) {
76 | Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
77 | Intent intent = new Intent("android.intent.action.VIEW");
78 | intent.setDataAndType(uri, "text/html");
79 | return intent;
80 | }
81 |
82 |
83 | static Intent getImageFileIntent(String param) {
84 | Intent intent = new Intent("android.intent.action.VIEW");
85 | intent.addCategory("android.intent.category.DEFAULT");
86 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
87 | Uri uri = Uri.fromFile(new File(param));
88 | intent.setDataAndType(uri, "image/*");
89 | return intent;
90 | }
91 |
92 |
93 | static Intent getPdfFileIntent(String param) {
94 | Intent intent = new Intent("android.intent.action.VIEW");
95 | intent.addCategory("android.intent.category.DEFAULT");
96 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
97 | Uri uri = Uri.fromFile(new File(param));
98 | intent.setDataAndType(uri, "application/pdf");
99 | return intent;
100 | }
101 |
102 |
103 | static Intent getTextFileIntent(String paramString, boolean paramBoolean) {
104 | Intent intent = new Intent("android.intent.action.VIEW");
105 | intent.addCategory("android.intent.category.DEFAULT");
106 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
107 | if (paramBoolean) {
108 | Uri uri1 = Uri.parse(paramString);
109 | intent.setDataAndType(uri1, "text/plain");
110 | }
111 | return intent;
112 | }
113 |
114 |
115 | static Intent getAudioFileIntent(String param) {
116 | Intent intent = new Intent("android.intent.action.VIEW");
117 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
118 | intent.putExtra("oneshot", 0);
119 | intent.putExtra("configchange", 0);
120 | Uri uri = Uri.fromFile(new File(param));
121 | intent.setDataAndType(uri, "audio/*");
122 | return intent;
123 | }
124 |
125 |
126 | static Intent getVideoFileIntent(String param) {
127 | Intent intent = new Intent("android.intent.action.VIEW");
128 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
129 | intent.putExtra("oneshot", 0);
130 | intent.putExtra("configchange", 0);
131 | Uri uri = Uri.fromFile(new File(param));
132 | intent.setDataAndType(uri, "video/*");
133 | return intent;
134 | }
135 |
136 | static Intent getChmFileIntent(String param) {
137 | Intent intent = new Intent("android.intent.action.VIEW");
138 | intent.addCategory("android.intent.category.DEFAULT");
139 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
140 | Uri uri = Uri.fromFile(new File(param));
141 | intent.setDataAndType(uri, "application/x-chm");
142 | return intent;
143 | }
144 |
145 | static Intent getWordFileIntent(String param) {
146 | Intent intent = new Intent("android.intent.action.VIEW");
147 | intent.addCategory("android.intent.category.DEFAULT");
148 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
149 | Uri uri = Uri.fromFile(new File(param));
150 | intent.setDataAndType(uri, "application/msword");
151 | return intent;
152 | }
153 |
154 | static Intent getPptFileIntent(String param) {
155 | Intent intent = new Intent("android.intent.action.VIEW");
156 | intent.addCategory("android.intent.category.DEFAULT");
157 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
158 | Uri uri = Uri.fromFile(new File(param));
159 | intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
160 | return intent;
161 | }
162 |
163 | static Intent getApkFileIntent(String fileName) {
164 | Intent intent = new Intent("android.intent.action.VIEW");
165 | intent.addCategory("android.intent.category.DEFAULT");
166 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
167 | Uri uri = Uri.fromFile(new File(fileName));
168 | intent.setDataAndType(uri, "application/vnd.android");
169 | return intent;
170 | }
171 | }
172 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/jniLibs/arm64-v8a/libmupdf_java.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/lib_fileviewer/src/main/jniLibs/arm64-v8a/libmupdf_java.so
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/jniLibs/armeabi-v7a/libmupdf_java.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/lib_fileviewer/src/main/jniLibs/armeabi-v7a/libmupdf_java.so
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/jniLibs/armeabi/liblbs.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/lib_fileviewer/src/main/jniLibs/armeabi/liblbs.so
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/jniLibs/armeabi/libmupdf_java.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/lib_fileviewer/src/main/jniLibs/armeabi/libmupdf_java.so
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable-xxhdpi/ic_go_back.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hanlyjiang/AndroidDocumentViewer/efc4515aa3a14cda13fb348b783788a32cd41ede/lib_fileviewer/src/main/res/drawable-xxhdpi/ic_go_back.png
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/button.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 | -
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/common_divider_shape.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/ic_chevron_left_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/ic_chevron_right_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/ic_close_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/ic_link_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/ic_search_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/ic_toc_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/page_indicator.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/seek_line.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
7 |
8 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/drawable/seek_thumb.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/layout/activity_tbs_file_view_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
15 |
16 |
21 |
22 |
28 |
29 |
39 |
40 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/layout/document_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
13 |
14 |
20 |
21 |
29 |
30 |
42 |
43 |
49 |
50 |
56 |
57 |
63 |
64 |
65 |
66 |
72 |
73 |
79 |
80 |
95 |
96 |
102 |
103 |
109 |
110 |
111 |
112 |
113 |
114 |
121 |
122 |
136 |
137 |
147 |
148 |
149 |
150 |
151 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #C0202020
4 | #C0202020
5 | #233d88
6 |
7 |
8 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | mupdf_jni
3 | Cancel
4 | Cannot open document
5 | Cannot open document: %1$s
6 | Dismiss
7 | Enter password
8 | No further occurrences found
9 | Not supported
10 | Okay
11 | Search…
12 | Searching…
13 | Text not found
14 | 查看文件:
15 | 文件不存在
16 | 无法识别文件
17 | 请选择一个应用打开
18 |
19 |
--------------------------------------------------------------------------------
/lib_fileviewer/src/test/java/com/artifex/mupdf/fitz/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.artifex.mupdf.fitz;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':lib_fileviewer'
2 |
--------------------------------------------------------------------------------