SlideShare a Scribd company logo
1 of 28
Download to read offline
Download
and
Restrict Video
Files
in
Android App
https://www.bacancytechnology.com/
Introduction
A couple of months back, I came across a
client requirement who wanted to build a
feature to download and restrict video files
in Android App, just like YouTube, Netflix,
Amazon Prime does with us. It took me
quite a few days to figure out how to
accomplish this requirement, but I ended
up with a satisfying solution. If you are
looking for this requirement or something
similar, hook until the end
Client
Requirement
The client made it very clear how the
feature should look like. Though, it
took time for the team to comprehend
and summarize the requirements.


Here was the requirement-


The client wanted to download the
video from the URL, save it to the
application environment, and play
offline (without using the internet)
from the environment only. Moreover,
he wanted to restrict the user from
accessing the video files outside the
app environment.
Download and
Restrict Video
Files in Android
App: Our
Approach
After much research, we concluded the
three final steps for building the feature:
How to Download and Restrict Video
Files in Android App.


1. Download the video from the URL
2. Encrypt the video file
3. Decrypt the video file at the time of
playing


We will dive into each step one by one
and implement the codebase in our
repository.
Download the
Video from
the URL
For downloading the videos, we will use the
Fetch library.


Update your build.gradle file with the
following dependency.
This library will let you download the
video/pdf/image and many more files of
different formats. Here are the code snippets
for downloading the video using the Fetch
library.


First of all, you have to define the fetch configuration like below


implementation
"androidx.tonyodev.fetch2:xfetch2:3.1.6"
val fetchConfiguration:
FetchConfiguration =
FetchConfiguration.Builder(this)
.setDownloadConcurrentLimit(1).en
ableLogging(true)
.enableRetryOnNetworkGain(true)
.build()
Use Fetch.getInstance to get the fetch instance
fetch =
Fetch.getInstance(fetchConfiguration)
Prepare the request as shown below
val request = videoUrl?.let {
filePath?.let {
it1 -> Request(it, it1)
}
}
After that, you need to set the priority of
the request like mentioned
request?.priority = Priority.HIGH
(It can be high, low, and normal)
Set the network type of the request
request?.networkType =
NetworkType.ALL (Global off,
unmetered, and wifi only)
Add header with the clientKey as shown
request?.addHeader("clientKey",
"*************************") (You
can find the clientKey in Fetch
dashboard)
After that you you need to put it to the
queue by using this code
request?.let {
fetch!!.enqueue(it,
Func { updatedRequest: Request? ->
},
Func { error: Error? -> })
}
Use the Fetch listeners for more operations
val fetchListener: FetchListener =
object : FetchListener {
override fun onQueued(
@NotNull download:
Download,
waitingOnNetwork: Boolean
) {
if (request?.id == download.id)
{
}
}


override fun onProgress(
@NotNull download:
Download,
etaInMilliSeconds: Long,
downloadedBytesPerSecond:
Long
) {}
override fun onCompleted(@NotNull
download: Download) {
Log.d("downloadingStatus-
>>", "onCompleted: ")
}




override fun
onPaused(@NotNull download:
Download) {
Log.d("downloadingStatus-
>>","video paused")
}


override fun
onResumed(@NotNull download:
Download) {
Log.d("downloadingStatus-
>>","video resumed")
}
override fun onStarted(
download: Download,
downloadBlocks: List,
totalBlocks: Int
) {
Log.d("downloadingStatus-
>>","video started downloading")
}


override fun
onWaitingNetwork(download:
Download) {}


override fun
onAdded(download: Download) {}
override fun
onCancelled(@NotNull download:
Download) {
Log.d("plae->>","video
cancelled")
}
override fun onRemoved(@NotNull
download: Download) {
Log.d("plae->>","video
removed")
}


override fun onDeleted(@NotNull
download: Download) {
Log.d("plae->>","video
deLeted")


}
override fun
onDownloadBlockUpdated(
download: Download,
downloadBlock:
DownloadBlock,
totalBlocks: Int
) {
Log.d("plae->>","video
download block updated")
override fun onError(
download: Download,
error: Error,
throwable: Throwable?
) {
Log.d("plae->>","video onError")
}
}


fetch!!.addListener(fetchListener)
Moving on towards the next step-
Encrypting the video file that we have just
downloaded.
Looking for skilled Android
developers to build scalable and high-
performance mobile applications?
Get in touch with Bacancy, the best
Android App Development Company,
to hire proficient android developers
without wasting a second.
Encrypt the Video File
subheading
After downloading and saving the video
into the directory, you must encrypt that
file. You can use the AES/GCM/NoPadding
algorithm. In this blog, we will implement
the AES algorithm.


First of all, you need to get the instance as
mentioned
val encipher =
Cipher.getInstance("AES")
Since we integrate the file encryption
feature, we need to define the secret key.
For generating the secret key, you can use
the below code snippet.
fun generateKey(): SecretKey? {
// Generate a 256-bit key
val outputKeyLength = 256
val secureRandom =
SecureRandom()
// Do *not* seed secureRandom!
Automatically seeded from system
entropy.
val keyGenerator =
KeyGenerator.getInstance("AES")
keyGenerator.init(outputKeyLength,
secureRandom)
return keyGenerator.generateKey()
}
Attach the secretKey with the encipher


encipher.init(Cipher.ENCRYPT_MODE,
generateKey())
At last, you need to use CipherInputStream


val cis =
CipherInputStream(fileInputStrea
m, encipher)
val buffer = ByteArray(1024) //
buffer can read file line by line to
increase speed
while (cis.read(buffer).also({
read = it }) >= 0) {
read?.let { fos.write(buffer,
0, it) }
fos.flush()
}
fos.close()
Decrypt the Video File


You won’t play the encrypted videos
directly in your app. For that, you have to
decrypt the video file. Use the below code
snippet to decrypt the encrypted video
files.
val fos =
FileOutputStream(decOutFile)
val encipher =
Cipher.getInstance("AES")


val encodedKey: ByteArray =
android.util.Base64.decode(
getFromPrefs(SECRET_KEY, "", ""),
android.util.Base64.DEFAULT
)
val originalKey: SecretKey =
SecretKeySpec(encodedKey, 0,
encodedKey.size, "AES")


encipher.init(Cipher.DECRYPT_
MODE, originalKey)


val cis =
CipherInputStream(fileInputSt
ream, encipher)


val buffer = ByteArray(1024) //
buffer can read file line by line
to increase speed
while (cis.read(buffer).also({ read =
it }) >= 0) {
read?.let { fos.write(buffer, 0, it) }
fos.flush()
}


fos.close()
So, this was about how we can build a
feature: How to Download and Restrict
Video Files in Android App. Here are a
few important notes to keep in mind.
Important notes




1. You need to use the same secret key for
encryption and decryption; if the secret
key is different, it can cause the app to
crash.


2. For privately saving the video files, you
should not use the external or public file
directories; if you use it, it can cause a
data leak.
I hope the blog has helped you
achieve your requirement: How to
Download and Restrict Video Files in
Android App. The Mobile Application
Development tutorials page is for you
if you are an Android enthusiast! Our
mobile app dev team has worked
hard to curate blogs and help you
quench your thirst for knowledge. So,
visit the page and start exploring!
Conclusion
https://www.bacancytechnology.com/
Thank You

More Related Content

Similar to Download and restrict video files in android app

Scale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App FabricScale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App FabricChris Dufour
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...Wim Selles
 
Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...
Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...
Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...Rashedul Islam
 
Getting Started With CFEngine - Updated Version
Getting Started With CFEngine - Updated VersionGetting Started With CFEngine - Updated Version
Getting Started With CFEngine - Updated VersionCFEngine
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon praguehernanibf
 
Embedded Recipes 2019 - Testing firmware the devops way
Embedded Recipes 2019 - Testing firmware the devops wayEmbedded Recipes 2019 - Testing firmware the devops way
Embedded Recipes 2019 - Testing firmware the devops wayAnne Nicolas
 
Microsoft Windows Server AppFabric
Microsoft Windows Server AppFabricMicrosoft Windows Server AppFabric
Microsoft Windows Server AppFabricMark Ginnebaugh
 
Installing WordPress on AWS
Installing WordPress on AWSInstalling WordPress on AWS
Installing WordPress on AWSManish Jain
 
Getting started with CFEngine - Webinar
Getting started with CFEngine - WebinarGetting started with CFEngine - Webinar
Getting started with CFEngine - WebinarCFEngine
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioKaty Slemon
 
Web versus Native: round 1!
Web versus Native: round 1!Web versus Native: round 1!
Web versus Native: round 1!Chris Mills
 
[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In ActionHazem Saleh
 
Docker presentasjon java bin
Docker presentasjon java binDocker presentasjon java bin
Docker presentasjon java binOlve Hansen
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Pavel Chunyayev
 
Setting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntukesavan N B
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 

Similar to Download and restrict video files in android app (20)

Scale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App FabricScale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App Fabric
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
 
Cloud Messaging Flutter
Cloud Messaging FlutterCloud Messaging Flutter
Cloud Messaging Flutter
 
Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...
Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...
Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-Te...
 
Getting Started With CFEngine - Updated Version
Getting Started With CFEngine - Updated VersionGetting Started With CFEngine - Updated Version
Getting Started With CFEngine - Updated Version
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon prague
 
Embedded Recipes 2019 - Testing firmware the devops way
Embedded Recipes 2019 - Testing firmware the devops wayEmbedded Recipes 2019 - Testing firmware the devops way
Embedded Recipes 2019 - Testing firmware the devops way
 
Microsoft Windows Server AppFabric
Microsoft Windows Server AppFabricMicrosoft Windows Server AppFabric
Microsoft Windows Server AppFabric
 
Javacro 2014 Spring Security 3 Speech
Javacro 2014 Spring Security 3 SpeechJavacro 2014 Spring Security 3 Speech
Javacro 2014 Spring Security 3 Speech
 
Installing WordPress on AWS
Installing WordPress on AWSInstalling WordPress on AWS
Installing WordPress on AWS
 
Getting started with CFEngine - Webinar
Getting started with CFEngine - WebinarGetting started with CFEngine - Webinar
Getting started with CFEngine - Webinar
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
Web versus Native: round 1!
Web versus Native: round 1!Web versus Native: round 1!
Web versus Native: round 1!
 
Power ai image-pipeline
Power ai image-pipelinePower ai image-pipeline
Power ai image-pipeline
 
[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action
 
Docker presentasjon java bin
Docker presentasjon java binDocker presentasjon java bin
Docker presentasjon java bin
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015
 
Setting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntu
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfKaty Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfKaty Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfKaty Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfKaty Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfKaty Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfKaty Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfKaty Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfKaty Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfKaty Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfKaty Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfKaty Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfKaty Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfKaty Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfKaty Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfKaty Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfKaty Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfKaty Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Download and restrict video files in android app

  • 3. A couple of months back, I came across a client requirement who wanted to build a feature to download and restrict video files in Android App, just like YouTube, Netflix, Amazon Prime does with us. It took me quite a few days to figure out how to accomplish this requirement, but I ended up with a satisfying solution. If you are looking for this requirement or something similar, hook until the end
  • 5. The client made it very clear how the feature should look like. Though, it took time for the team to comprehend and summarize the requirements. Here was the requirement- The client wanted to download the video from the URL, save it to the application environment, and play offline (without using the internet) from the environment only. Moreover, he wanted to restrict the user from accessing the video files outside the app environment.
  • 6. Download and Restrict Video Files in Android App: Our Approach
  • 7. After much research, we concluded the three final steps for building the feature: How to Download and Restrict Video Files in Android App. 1. Download the video from the URL 2. Encrypt the video file 3. Decrypt the video file at the time of playing We will dive into each step one by one and implement the codebase in our repository.
  • 8.
  • 10. For downloading the videos, we will use the Fetch library. Update your build.gradle file with the following dependency. This library will let you download the video/pdf/image and many more files of different formats. Here are the code snippets for downloading the video using the Fetch library. First of all, you have to define the fetch configuration like below implementation "androidx.tonyodev.fetch2:xfetch2:3.1.6"
  • 12. Prepare the request as shown below val request = videoUrl?.let { filePath?.let { it1 -> Request(it, it1) } } After that, you need to set the priority of the request like mentioned request?.priority = Priority.HIGH (It can be high, low, and normal) Set the network type of the request request?.networkType = NetworkType.ALL (Global off, unmetered, and wifi only)
  • 13. Add header with the clientKey as shown request?.addHeader("clientKey", "*************************") (You can find the clientKey in Fetch dashboard) After that you you need to put it to the queue by using this code request?.let { fetch!!.enqueue(it, Func { updatedRequest: Request? -> }, Func { error: Error? -> }) }
  • 14. Use the Fetch listeners for more operations val fetchListener: FetchListener = object : FetchListener { override fun onQueued( @NotNull download: Download, waitingOnNetwork: Boolean ) { if (request?.id == download.id) { } } override fun onProgress( @NotNull download: Download, etaInMilliSeconds: Long, downloadedBytesPerSecond: Long ) {}
  • 15. override fun onCompleted(@NotNull download: Download) { Log.d("downloadingStatus- >>", "onCompleted: ") } override fun onPaused(@NotNull download: Download) { Log.d("downloadingStatus- >>","video paused") } override fun onResumed(@NotNull download: Download) { Log.d("downloadingStatus- >>","video resumed") }
  • 16. override fun onStarted( download: Download, downloadBlocks: List, totalBlocks: Int ) { Log.d("downloadingStatus- >>","video started downloading") } override fun onWaitingNetwork(download: Download) {} override fun onAdded(download: Download) {} override fun onCancelled(@NotNull download: Download) { Log.d("plae->>","video cancelled") }
  • 17. override fun onRemoved(@NotNull download: Download) { Log.d("plae->>","video removed") } override fun onDeleted(@NotNull download: Download) { Log.d("plae->>","video deLeted") } override fun onDownloadBlockUpdated( download: Download, downloadBlock: DownloadBlock, totalBlocks: Int ) { Log.d("plae->>","video download block updated")
  • 18. override fun onError( download: Download, error: Error, throwable: Throwable? ) { Log.d("plae->>","video onError") } } fetch!!.addListener(fetchListener)
  • 19. Moving on towards the next step- Encrypting the video file that we have just downloaded. Looking for skilled Android developers to build scalable and high- performance mobile applications? Get in touch with Bacancy, the best Android App Development Company, to hire proficient android developers without wasting a second.
  • 20. Encrypt the Video File subheading After downloading and saving the video into the directory, you must encrypt that file. You can use the AES/GCM/NoPadding algorithm. In this blog, we will implement the AES algorithm. First of all, you need to get the instance as mentioned val encipher = Cipher.getInstance("AES")
  • 21. Since we integrate the file encryption feature, we need to define the secret key. For generating the secret key, you can use the below code snippet. fun generateKey(): SecretKey? { // Generate a 256-bit key val outputKeyLength = 256 val secureRandom = SecureRandom() // Do *not* seed secureRandom! Automatically seeded from system entropy. val keyGenerator = KeyGenerator.getInstance("AES") keyGenerator.init(outputKeyLength, secureRandom) return keyGenerator.generateKey() }
  • 22. Attach the secretKey with the encipher encipher.init(Cipher.ENCRYPT_MODE, generateKey()) At last, you need to use CipherInputStream val cis = CipherInputStream(fileInputStrea m, encipher) val buffer = ByteArray(1024) // buffer can read file line by line to increase speed while (cis.read(buffer).also({ read = it }) >= 0) { read?.let { fos.write(buffer, 0, it) } fos.flush() } fos.close()
  • 23. Decrypt the Video File You won’t play the encrypted videos directly in your app. For that, you have to decrypt the video file. Use the below code snippet to decrypt the encrypted video files. val fos = FileOutputStream(decOutFile) val encipher = Cipher.getInstance("AES") val encodedKey: ByteArray = android.util.Base64.decode( getFromPrefs(SECRET_KEY, "", ""), android.util.Base64.DEFAULT )
  • 24. val originalKey: SecretKey = SecretKeySpec(encodedKey, 0, encodedKey.size, "AES") encipher.init(Cipher.DECRYPT_ MODE, originalKey) val cis = CipherInputStream(fileInputSt ream, encipher) val buffer = ByteArray(1024) // buffer can read file line by line to increase speed
  • 25. while (cis.read(buffer).also({ read = it }) >= 0) { read?.let { fos.write(buffer, 0, it) } fos.flush() } fos.close() So, this was about how we can build a feature: How to Download and Restrict Video Files in Android App. Here are a few important notes to keep in mind.
  • 26. Important notes 1. You need to use the same secret key for encryption and decryption; if the secret key is different, it can cause the app to crash. 2. For privately saving the video files, you should not use the external or public file directories; if you use it, it can cause a data leak.
  • 27. I hope the blog has helped you achieve your requirement: How to Download and Restrict Video Files in Android App. The Mobile Application Development tutorials page is for you if you are an Android enthusiast! Our mobile app dev team has worked hard to curate blogs and help you quench your thirst for knowledge. So, visit the page and start exploring! Conclusion