1. Project Overview
Displaying online Office documents (such as Word, Excel, PPT) on mobile is a common requirement. Users can preview in the app by clicking on the link, without downloading apps or files to the local area. There are two main ideas for implementing this function:
WebView + Online Documentation Service: Embed document URLs into preview pages using Microsoft Office Online or Google Docs Viewer;
Third-party SDK (such as Tencent TBS/WPS): Integrated browser kernel or document SDK, supports local loading of remote documents and rendering and displaying.
This article focuses on the implementation methods of the two solutions and gives complete examples.
2. Related technical knowledge
Load online preview
Office Online URL template:
/op/?src=<URL_ENCODED_DOC_URL>
Google Docs Viewer:
/gview?embedded=true&url=<URL_ENCODED_DOC_URL>
WebView configuration: enable JavaScript, support scaling, adjust cache policies, etc.
2. Tencent TBS SDK (X5 core)
TbsReaderView provided by TBS can load formats such as doc/docx/xls/ppt/pdf.
The kernel needs to be preloaded when the App is initialized and TbsReaderView is added to the layout.
3. File access and permissions
Online preview does not require read and write permissions;
If you download it locally and open it with the SDK, you need to apply for storage permissions (Android 6.0+ runtime permissions).
4. Performance and compatibility
WebView schemes rely on external networks and services;
The SDK solution has a large package but supports offline and can customize the UI.
Ideas for realization
3.1 Solution 1: WebView + Office Online
Place a WebView in the layout.
Get the remote URL of the document in Activity, encode the URL and splice it to the Office Online viewing address.
Configure WebView: Enable JavaScript, DOM storage, and zoom control.
Call (previewUrl) to preview online.
3.2 Solution 2: TBS SDK offline preview
Introduce TBS SDK dependencies in the project.
Initialize X5 at Application startup: Call QbSdk.initX5Environment(...).
Add TbsReaderView to the layout.
Download or cache the document locally in the Activity and call (bundle, null) to load the preview.
Remember to destroy the TbsReaderView in onDestroy().
4. Integrate code
4.1 Java code ()
package ; import ; import ; import ; import .*; import ; import .*; import .*; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; public class MainActivity extends AppCompatActivity { private static final int REQ_STORAGE = 1001; private WebView webView; private TbsReaderView tbsView; private FrameLayout container; private String remoteDocUrl = "/"; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); webView = findViewById(.web_view); tbsView = findViewById(.tbs_view); container = findViewById(.tbs_container); findViewById(.btn_web_preview).setOnClickListener(v -> previewWithWeb()); findViewById(.btn_tbs_preview).setOnClickListener(v -> previewWithTbs()); } /** Solution 1: WebView + Office Online */ private void previewWithWeb() { (); (); WebSettings ws = (); (true); (true); (false); (true); String urlEncoded = (remoteDocUrl); String previewUrl = "/op/?src=" + urlEncoded; (previewUrl); } /** Solution 2: TBS SDK preview, storage permissions are required */ private void previewWithTbs() { (); (); if ((this, .WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { (this, new String[]{.WRITE_EXTERNAL_STORAGE}, REQ_STORAGE); } else { downloadAndOpenWithTbs(remoteDocUrl); } } @Override public void onRequestPermissionsResult(int req, @NonNull String[] perms, @NonNull int[] grantResults) { if (req == REQ_STORAGE && >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { downloadAndOpenWithTbs(remoteDocUrl); } else { (this, "Storage permission denied", Toast.LENGTH_SHORT).show(); } } /** After downloading it locally, open it with TbsReaderView */ private void downloadAndOpenWithTbs(String urlStr) { new Thread(() -> { try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) (); (); InputStream is = (); File file = new File(getExternalFilesDir(null), ""); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[4096]; int len; while ((len = (buf))>0) (buf,0,len); (); (); runOnUiThread(() -> openFileInTbs(())); } catch (Exception e) { (); runOnUiThread(() -> (this, "Download failed", Toast.LENGTH_SHORT).show()); } }).start(); } private void openFileInTbs(String filePath) { Bundle params = new Bundle(); (TbsReaderView.KEY_FILE_PATH, filePath); (TbsReaderView.KEY_TEMP_PATH, getExternalFilesDir(null).getPath()); boolean ok = (getFileType(filePath), false); if (ok) { (params); } else { (this, "TBS kernel is not loaded or not supported", Toast.LENGTH_SHORT).show(); } } private String getFileType(String path) { if (path == null || !(".")) return ""; return (('.') + 1); } @Override protected void onDestroy() { (); (); } }
4.2 XML layout and Manifest
<!-- —— statement INTERNET With read and write permissions,And register TbsReaderView Permissions --> <manifest xmlns:andro package=""> <uses-permission android:name=""/> <uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:label="OfficePreview" android:icon="@mipmap/ic_launcher" android:theme="@style/"> <activity android:name=".MainActivity"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> </activity> </application> </manifest> <!-- activity_main.xml —— Also included WebView and TbsReaderView --> <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:andro android:layout_width="match_parent" android:layout_height="match_parent"> <!-- WebView Method preview --> <WebView android: android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"/> <!-- TBS SDK Method preview --> <FrameLayout android: android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"> < android: android:layout_width="match_parent" android:layout_height="match_parent"/> </FrameLayout> <!-- Bottom button --> <LinearLayout android:layout_gravity="bottom|center_horizontal" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp"> <Button android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Web Preview"/> <Button android: android:layout_marginStart="16dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TBS Preview"/> </LinearLayout> </FrameLayout>
5. Code interpretation
plan
URL encode the document URL and splice it to the Office Online viewing address;
Enable JavaScript, scaling support, and DOM storage in WebView;
Just loadUrl() directly, no additional download is required.
SDK Solution
QbSdk.initX5Environment() needs to be called in advance at Application or at any time (omitted);
After downloading the document to the App's private storage, detect kernel support through ();
Call openFile() to load local documents, supporting doc, xls, ppt, pdf and other formats;
Call () in onDestroy() to free the resource.
3. Permissions and Lifecycle
Only after applying for write storage permission during runtime can it be saved to the local area;
Clean animations and TBS resources in onPause()/onDestroy() to avoid memory leaks.
6. Project Summary
WebView + Office Online: Simple implementation without the need to integrate third-party SDKs, and rely on external services;
TBS SDK: supports offline preview and more formats, but the package is large and the kernel needs to be initialized;
This example combines the two solutions into one, select and switch as needed.
7. Practical suggestions and future prospects
UI optimization: add loading progress bar and error page prompts;
Caching strategy: cache downloaded files and read them directly next time;
More formats: combine open-source rendering libraries (such as Apache POI + PDF conversion) to achieve more customization;
Compose era: In Jetpack Compose, you can also use AndroidView to embed WebView or TBS directly.
This is the end of this article about the detailed explanation of the example of Android previewing the office document online. For more information about Android online previewing the office content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!