- How to open a PDF file in Android programmatically?
- Project setup
- Ways of opening PDF in Android
- Making UI for the project
- Opening a PDF file in Android using WebView
- Opening a PDF file in Android using AndroidPdfViewer library
- Assets Folder
- From Phone Storage
- PDF from Internet
- Project source code and What next?
- Scoped Storage in Android 10 & Android 11
- What was the problem with earlier storage ?
- This is how it is solved now
- What all permissions app need to access the files from scoped storage?
- Access media files from shared storage | Android Developers
- To provide a more enriched user experience, many apps allow users to contribute and access media that’s available on an…
- Access documents and other files from shared storage
- On devices that run Android 4.4 (API level 19) and higher, your app can interact with a documents provider, including…
- What does it mean for you?
- Microsoft Mobile Engineering
How to open a PDF file in Android programmatically?
Opening and viewing documents in Android applications are very interesting and a must to have in every application. You can open any application present on your mobile and you will find that every application contains documents in some or the other way. And among these documents, the most popular and widely used document format is the PDF format.
PDF or Portable Document Format is a file format that has captured all the elements of a printed document. This is the most used document format. For example, in the Paytm application, you get your monthly expenses in the form of PDF document. So, if you also want to display some kind of document in your application, then you can open this PDF format document.
So, welcome to MindOrks and in this tutorial, we will learn how to open a PDF file in Android programmatically. We will cover the below topics in this tutorial:
- Project setup
- Ways of opening PDF in Android
- Making UI and adding Activities for the project
- Opening a PDF file using WebView
- Opening a PDF file using AndoirdPdfviewer library
- Project source code and What next?
Project setup
In this tutorial, we will make a project and try various ways of opening PDF file, Here we are going to set up our project:
- Start a new Android Studio Project
- Select Empty Activity and Next
- Name: Open-PDF-File-Android-Example
- Package name: com.mindorks.example.openpdffile
- Language: Kotlin
- Finish
- Your starting project is ready now
- Under your root directory, create a package named utils .(right-click on root directory > new > package)
- In the utils package, create one object classes: FileUtils .(right-click on utils > new > Kotlin file/class > Object class)
If you are preparing for your next Android Interview, Join our Android Professional Course to learn the latest in Android and land job at top tech companies.
Ways of opening PDF in Android
If you want to display PDF in your Android application, there are various ways of doing it. Some of the ways of opening the PDF can be:
- From Assets: Let’s take an example, if you want to display some icons in your application then you will put all your icons in the drawable folder and then you will use those icons in your application. Same is with the case of PDF files also. If you have some PDF file that is constant and you want to display it in your application then you can put that PDF file in the assets folder and use that PDF in your app. One example can be the Terms and Conditions file. The terms and conditions files are rarely changed. So, you can put that document in the assets folder and use it.
- From Device: The other way of opening a PDF is to open it from the device itself. Here, you can open the PDF files present in your mobile device. This is the most used approach for opening the PDF in an Android device.
- From the Internet: Here, you can open PDF files from the internet. All you need to do is just use the URL of the PDF file and after downloading the PDF file, you can open the PDF file in your mobile application.
So, we will look upon all these ways of viewing the PDF in your Android Application. Let’s make the UI of the project.
Making UI for the project
In our example, we are going to cover four different cases:
- Opening a PDF file using WebView
- Opening a PDF file from assets using AndroidPdfViewer library
- Opening a PDF file form storage using AndroidPdfViewer library
- Opening a PDF file from the internet using AndroidPdfViewer library
So, for the first point, we will use WebViewActivity and for 2nd, 3rd, and 4th point, we will be using PdfViewActivtiy .
Create two activities named WebViewActivtiy and PdfViewActivity .(right-click on root directory > new > Activity> Empty Activity)
Now, for the above four actions, create four buttons and assign the task to open activity by those four buttons.
The code for the activity_main.xml file is:
In the MainActivity.kt file, we call the desired activity with the corresponding buttons:
We are done with the UI part. Let’s learn how to view PDF from WebView.
Opening a PDF file in Android using WebView
The very first and the easiest way of displaying the PDF file is to display it in the WebView. All you need to do is just put WebView in your layout and load the desired URL by using the webView.loadUrl() function.
So, add a WebView in the activity_web_view.xml file:
Now, open the FileUtils class of the utils package that we created at the starting of this blog and add a function named getPdfUrl that will return the URL of the PDF which we are going to view in the WebView. Here, I am using the syllabus of MindOrks Professional Course. Add below method in FileUtils class:
Now, all we need to do is open the above URL in the WebView by calling the webView.loadUrl method. Following is the code of WebViewActivity.kt file:
The last thing that you need to do is adding INTERNET permission to your application. So, add the below line in your AndroidManifest.xml file:
Now, run the application on your mobile phone and the PDF will be displayed on the screen.
Note: The opening of PDF in WebView depends on your internet speed, so wait for sometimes if your internet is slow.
Opening a PDF file in Android using AndroidPdfViewer library
There are various libraries that can be used to display PDF files in our application. In our tutorial, we will learn how to open a PDF file from Assets, Phone Storage, and from the Internet by using the AndroidPdfViewer library.
Also, we will be using PRDownloader library by MindOrks to download files from the Internet and open it by AndoridPdfViewer .
Adding dependencies and permissions
Open the app level build.gradle and add the below dependencies of AndroidPdfViewer and PRDownloader:
Since we will be reading pdf from INTERNET. Open the AndoidManifest.xml file and add the below:
The AndroiPdfViewer provides a PDFView to display PDF files in it. So, write the below code in actvity_pdf_view.xml :
We can use the AndroidPdfViewer to open the PDF from:
- Assets folder
- Phone storage
- Internet
So, we need to write the code to connect the button click of MainActivity with the above events. Create a function named checkPdfAction() and write the below code:
Call the above method from the onCreate() :
Let’s learn how to display PDF from assets, storage, and internet.
Assets Folder
Firstly, we will look upon how to view PDF, stored in the Assets Folder.
Creating an assets folder
Create an assets folder by right-clicking on main > New Folder > Assets Folder and paste the PDF document into it.
PDF file name: MindOrks_Android_Online_Professional_Course-Syllabus.pdf
Create getPdfNameFromAssets() method
Create a method named getPdfNameFromAssets in the FileUtils class. This method will return the name of the PDF file present in the assets folder:
Now, in the PdfViewActivity.kt file, create a method showPdfFromAssets which will take the file name in string format and will use the fromAssets() method of AndroidPdfViewer library to display PDF:
Call the above method from the checkPdfAction and pass the file name by calling the getPdfnameFromAssets method of FileUtils class:
Finally, run the application on your mobile device and see the output.
From Phone Storage
Now, we will look upon how to open PDF files from the Phone’s storage. So, we have to launch an intent to find the file having PDF format and the selected file will be displayed in the PDFView by calling the fromUri method.
Create a function selectPdfFromStorage() in the PdfViewActivity.kt file and add the below code:
Once, the user selects a PDF, the onActivityResult will be called:
Now, create a method named showPdfFromUri that will take a Uri and display the PDF:
Now, you can check the output by running your application on your mobile device and select the desired PDF.
PDF from Internet
Lastly, our aim is to view the PDF files from the Internet. We will first download the PDF by using the PRDownloader and then use this file to display the PDF on your PdfViewActiviy by using the same process as used for Assets and Storage but here you have to use fromFile() to add display the PDF.
So, we need to download the file first by using the PRDownloader library. Initialise it in the onCreate() method of PdfViewActivity :
Now, you need to download the file from the INTERNET by using the download() method of PRDownloader. So, create a function named downloadPdfFromInternet() in the PdfViewActivity. This function will take the URL, directory path, and file name of the file to be downloaded.
The onDownloadComplete method will be called when the file is downloaded. So, call the showPdfFromFile method and pass the downloaded file to the method:
Finally, call the downloadPdfFromInternet method from the checkPdfAction method but we need the URL, directory name and file name of the file to be downloaded. We can get the URL by calling the getPdfUrl method of FileUtils class. Now, make a function getRootDirPath method in the FileUtils class that will return the root directory:
Now, call the downloadPdfFromInternet method from checkPdfAction method of PdfViewActivity :
Finally, run the application and try to verify all the three options i.e. assets, storage and internet options to view PDF in Android Application. Try to replace the PDF link used in the above example with your own PDF URL.
There are many other methods present in the AndroidPdfViewer library. You can explore all the methods from here.
Project source code and What next?
Do share this tutorial with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website .
Источник
Scoped Storage in Android 10 & Android 11
A secure and advanced app storage system for Android.
A controversial storage access change, slated for Android 10, becomes mandatory for Android 11. This blog talks about scoped storage, How we can access it and what does it mean for our app?
Before Android 10, storage was divided into private storage and shared storage. Private storage’s(android/data/
) access and contribution was limited to owner app alone. Apart from private storage, rest of the storage was called shared storage which is where all the media and non-media files were being stored. Any app with storage permission would be able to access this part of storage.
What was the problem with earlier storage ?
Limited access: Most of the apps do not need the access of whole storage since their use case are limited to certain types of files or files they own. One such use case can be a grocery app or an e-commerce app which needs storage access only to ask user to upload their profile picture.
Security: With storage access, an app can access a document as vulnerable as your bank statement or personal files. How would you like that?
Data organisation: Data/Files related to an app was scattered at multiple places in Shared Storage. If you have to uninstall the app and you want to clear all the corresponding data, that would not come easy.
This is how it is solved now
With Android 10, Google started to restructure the storage and change the way app accesses the storage so that all the mentioned problems can be eliminated. This storage division is called scoped storage.
Idea behind scoped storage was to divide whole storage into multiple blocks. An app would be provided access to the storage blocks which has relevant data for the app. In addition, system will bind storage to owner apps so that it becomes easier for the system to locate relevant files, corresponding to an app. This would also help to remove app specific data once app is uninstalled unless user does not want to.
This is how storage is divided now:
This storage remains same as before. Its app’s own private directory (/app/data/
) where app has unlimited access to read and write.
This is further divided into Media and Download collection. Media collection stores Image, Audio and Video files. Download collection would take care of non-media files.
What all permissions app need to access the files from scoped storage?
Earlier there was one permission to read all the files and another to write. Now with scoped storage, access is allotted based upon storage type and the ownership of the content.
1. App will have unlimited access to their internal and external storage for both read & write operation.
2. App will have unrestricted access to contribute files ( Media & Non-Media) as long as the file is stored in organised collection.
3. Media collection contributed by other apps can be accessed using ‘READ_STORAGE_PERMISSION’ permission. ‘WRITE_STORAGE_PERMISSION’ permission will be deprecated from next version and if used, will work same as ‘READ_STORAGE_PERMISSION’.
4. Non Media files contributed by other apps can be accessed using Storage access framework API. No explicit permission is needed. This does not mean that App can get access to all the directories ( Root, android/Data , Download directory etc.). Once user grants access to it, it will be complete access. (Read, Modify, Delete).
This is how we can access non-media Files. Here i am trying to access PDF file.
If App wants to select a custom folder, intent ACTION_OPEN_DOCUMENT can be replaced with ACTION_OPEN_DOCUMENT_TREE. ACTION_OPEN_DOCUMENT_TREE is introduced in android 11. This access will be valid till user reboots device. If app wants to persist the access, while accessing URI using content resolver , content resolver has to call takePersistableUriPermission method.
If App wants to create a file such as an email app saving attachment, intent can be replaced with ACTION_CREATE_DOCUMENT.
Access media files from shared storage | Android Developers
To provide a more enriched user experience, many apps allow users to contribute and access media that’s available on an…
Access documents and other files from shared storage
On devices that run Android 4.4 (API level 19) and higher, your app can interact with a documents provider, including…
Note: Media location is considered sensitive data now and would not be available unless app has ACCESS_MEDIA_LOCATION permission. It’s not a run time permission and has to be included in manifest. However it would be good idea to check this if app highly depends upon metadata or is an enterprise application where admin can remove the permission. If you want exact bytes of stored media, ‘MediaStore.setRequireOriginal(photoUri)’ has to be called.
So now apps can get access to specific block of memory. But what if I am a back up app which needs to access everything?
In Android 10, users tried to access the directories using storage access framework. Storage access framework was not intended for this purpose. Also, User complained about confusing UX. For such apps, a special permission is introduced in android 11. To ask the permission, Apps have to submit a declaration form to Google play. Once user grants the permission to have a broad access then user will get an unfiltered view of MediaStore that include non-media file. However, your app will not have access to external app directories.
Unfiltered view of Mediastore…What if my app uses custom file picker which displays exact data directories?
There is nothing you can do about it. You might want to use system picker from now on.
Alright so till this point we understand the reason behind scoped storage and the permission/methods to access it. Now let’s talk about scoped storage API changes over android 10 & 11.
Scoped storage was introduced in Android 10 but there were some controversial decision which enforced google to make API changes in Android 11.
1. In Android 10 and 11, Scoped storage is default behaviour. However app can request legacy external storage in Android 10 which is not the case in 11. Additionally In Android 10, Apps which wanted broader access, tried to use Storage access framework to select the directories which was not the intended purpose of storage framework. In Android 11, special access permission is introduced. Once Google play white list the app, special permission can be asked to the user.
2. In Android 10, UI for scoped storage permission looked same as earlier android version. So it would be hard for user to know if they are giving access to scoped storage or whole storage. With Android 11, permission UI will be updated so that user can clearly differentiate between different permissions he is providing.
3. In Android 11, Media store has been updated. User can do bulk delete/edit of media files which was not the case in Android 10. Additionally, Copying and Editing of files is possible in 11 but recommended only for one-off edits and small sized files since copying files will clutter user’s disk storage.
4. Android 10 has lack of support for native libraries and file path. This is use-case for apps written in c, c++. This support has been added in Android 11, in-fact this is the only use case where developer is expected to write new code. Under the hood file path api is a proxy to media storage api. so if possible, call media store api directly.
What does it mean for you?
if your app has files stored in Shared storage or outside app directory, you need to move them to app directory if you plan to target android 10 and above. Starting with Android 10 you will lose access to it.
Scoped storage is here to solve long time privacy issue. Although there were lots of controversial decisions and negative feedback in Android 10, It is here to stay. Starting September 2020, apps must target android 10 or later so unless you are an app which does not use storage, it’s recommended to start using scoped storage.
Lastly, thank you for reading the article! Any questions and suggestions are most welcome. See you soon.
Microsoft Mobile Engineering
#Mobile development articles and news brought to you by #MobileDevs working at @Microsoft
Источник