Setting up a Material Components theme for Android

So, you’ve migrated your Android app to AndroidX and, in the process, have also switched to using Material Components for Android as opposed to the Design Support Library. Alternatively, perhaps you’re in the fortunate situation of starting an app from scratch and get to use these new libraries right away. In either case, the core widgets you incorporate into your app now mostly fall under the com.google.android.material package and bring with them a variety of new theme/style attributes.
This article will only cover the new global theme attributes and per-widget style attributes that are introduced. Given that the Theme.MaterialComponents themes extend the pre-existing Theme.AppCompat variants, they inherit all of their attributes (think colorAccentcolorControlNormal, etc.), which will not be covered.
Let’s begin!

Initial setup 🏗️

This is as simple as adding a single Gradle dependency to your app/module build.gradle file:
implementation "com.google.android.material:material:$material_version"
Material Components for Android is under active development. The initial 1.0.0 release was mostly just a port of the existing com.android.support.design classes over to the new com.google.android.material namespace. Following this have been independent feature releases and, at the time of writing, the latest version is 1.2.0-alpha05. You can track new releases on the GitHub repository.

Choosing a Material Components theme 🤔

As with the AppCompat themes, the Material Components themes include a few base variants for you to choose from:
Material Components themes (from left to right): Theme.MaterialComponents, Theme.material components.NoActionBar, Theme.material components.Light
Material Components themes (from left to right): Theme.MaterialComponents.Light.DarkActionBar, Theme.MaterialComponents.Light.NoActionBar
The key differences in each variant are the light/dark color palettes and the inclusion/exclusion of an ActionBar in each themed Activity‘s Window. There exists DayNight variants of these for supporting automatic dark/light theming.
Note 1: If you are migrating an existing theme and don’t wish to get all of the new attributes at once, use a Theme.MaterialComponents.*.Bridge variant.
Note 2: Some secondary variants are not shown here, such as Theme.MaterialComponents.Dialog.* themes.
To start using one of these themes in your app, you’d add the following to your res/styles.xml file:
<style name="AppTheme" parent="Theme.MaterialComponents.*">
    <!-- Add attributes here --></style>
Finally, you need to reference this in your Manifest:
<manifest
    ...>
    <application
        android:theme="@style/AppTheme">
        ...
    </application>
</manifest>
Note: You can also apply an android:theme per <activity> in your Manifest.

A simple playground screen 🎡

Right, time to get down to business. In order to illustrate the effects of customizing Material Components attributes, we need visual aid. We will be using the playground screen below, which uses the Theme.MaterialComponents.Light base theme and is packed with most Material Components widgets and their variants:
Playground screen

Global theme attributes 🌍

The Material Components themes introduce new attributes that can be used to style elements on a global scale. These can be grouped into three main subsystems: colortypography and shape.

Color

Color attributes consist mainly of primarysecondaryerrorsurface and background colors, along with their respective secondary variants and “on” colors. Some of these have been reused from the AppCompat themes (eg. colorPrimarycolorError and android:colorBackground):
  • colorPrimary: The primary brand color of your app, used most predominantly in theming
  • colorPrimaryVariant: A lighter/darker variant of your primary brand color, used sparingly in theming
  • colorOnPrimary: The color used for elements displayed on top of your primary colors (eg. Text and icons, often white or semi-transparent black depending on accessibility)
  • colorSecondary: The secondary brand color of your app, used mostly as an accent for certain widgets that need to stand out
  • colorSecondaryVariant: A lighter/darker variant of your secondary brand color, used sparingly in theming
  • colorOnSecondary: The color used for elements displayed on top of your secondary colors
  • colorError: The color used for errors (often a shade of red)
  • colorOnError: The color used for elements displayed on top of your error color
  • colorSurface: The color used for surfaces (i.e. Material “sheets”)
  • colorOnSurface: The color used for elements displayed on top of your surface color
  • android:colorBackground: The color behind all other screen content
  • colorOnBackground: The color used for elements displayed on top of your background color
These colors can be added to your app theme like so:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    <item name="colorPrimary">#212121</item>
    <item name="colorPrimaryVariant">#000000</item>
    <item name="colorOnPrimary">#FFFFFF</item>
    <item name="colorSecondary">#2962FF</item>
    <item name="colorSecondaryVariant">#0039CB</item>
    <item name="colorOnSecondary">#FFFFFF</item>
    <item name="colorError">#F44336</item>
    <item name="colorOnError">#FFFFFF</item>
    <item name="colorSurface">#FFFFFF</item>
    <item name="colorOnSurface">#212121</item>
    <item name="android:colorBackground">@color/background</item>
    <item name="colorOnBackground">#212121</item>
</style><color name="background">#FAFAFA</color>
Note 1: Hex color codes are not currently supported for android:colorBackground, hence why a color resource was used.
Note 2: Use android:statusBarColor and android:navigationBarColor attributes to theme system bars.
The result can be observed in our playground screen:
Playground screen with global color attributes customized
A great way to quickly preview the appearance of primary/secondary colors is to use the Material Color Tool.

Typography

Type attributes adhere to the Material Type System in terms of text typefaceweightsizecase and letter spacing. The attributes reference TextAppearance.MaterialComponents.* styles that implement (and are named after) the various type scales:
  • textAppearanceHeadline1: Light, 96sp
  • textAppearanceHeadline2: Light, 60sp
  • textAppearanceHeadline3: Regular, 48sp
  • textAppearanceHeadline4: Regular, 34sp
  • textAppearanceHeadline5: Regular, 24sp
  • textAppearanceHeadline6: Medium, 20sp
  • textAppearanceSubtitle1: Regular, 16sp
  • textAppearanceSubtitle2: Medium, 14sp
  • textAppearanceBody1: Regular, 16sp
  • textAppearanceBody2: Regular, 14sp
  • textAppearanceCaption: Regular, 12sp
  • textAppearanceButton: Regular, 14sp, all caps
  • textAppearanceOverline: Regular, 12sp, all caps
The Material Components widgets will use these styles as per the Material guidelines.
You would typically want to keep the default weight, size, case and letter spacing for each style. However, a custom typeface can really make your app stand out. One might assume this requires overriding each and every one of these attributes. Thankfully, this can be done in a far more concise way by adding the following attributes to your app theme:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="fontFamily">@font/roboto_mono</item>
    <item name="android:fontFamily">@font/roboto_mono</item>
</style>
These attributes reference an XML Font or a Downloadable Font that you’ve added to your res/font folder and will apply a custom typeface to every widget and text style in your app. There was certainly a time when it wasn’t this easy on Android!
If you do, however, wish to customize one of the Material Components text appearance styles, you would do so like this:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="textAppearanceButton">@style/AppTextAppearance.Button</item>
</style><style name="AppTextAppearance.Button" parent="TextAppearance.MaterialComponents.Button">
    ...
    <item name="android:textAllCaps">false</item>
</style>
The results can be observed in our playground screen:
Playground screen with global type attributes customized
Lastly, Google Fonts is a great place to start if you’re looking for free-to-use, custom typefaces (which happen to work really well with Downloadable Fonts too).

Shape

Shape attributes refer to the general form of each surface and widget in your app. When you consider that these components can be of varying width/height and be raised/unelevated/outlined, this reduces down to one aspect of customization… Corners.
Material Components corners can either be part of the rounded (default) or cut cornerFamily and have a cornerSize to customize the size. A treatment can be applied to all corners or a subset. The shape theme attributes reference ShapeAppearance.MaterialComponents.* styles:
  • shapeAppearanceSmallComponent: For small components, such as Buttons and Chips
  • shapeAppearanceMediumComponent: For medium components, such as Cards
  • shapeAppearanceLargeComponent: For large components, such as Bottom Sheets
The Material Components widgets will use these styles as per the Material guidelines.
If you wish to customize the Material Components shape appearance styles, you would do so like this:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="shapeAppearanceSmallComponent">@style/AppShapeAppearance.SmallComponent</item>
    <item name="shapeAppearanceMediumComponent">@style/AppShapeAppearance.MediumComponent</item>
</style><style name="AppShapeAppearance.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent">
    <item name="cornerFamily">cut</item>
    <item name="cornerSize">8dp</item>
</style><style name="AppShapeAppearance.MediumComponent" parent="ShapeAppearance.MaterialComponents.MediumComponent">
    <item name="cornerFamily">cut</item>
    <item name="cornerSize">8dp</item>
</style>
The result can be observed in our playground screen:
Playground screen with global shape attributes customized

Widget styles and attributes 📱

While global theming covers the majority of our needs, there are times when we may wish to customize the attributes of individual widgets. We will explore the styles (and relevant attributes) of common widgets and how these can be referenced in your Material Components theme.

Buttons

Material Buttons include four main variants that all inherit from the base Widget.MaterialComponents.Button style, each with an optional style suffix: raised (default, no suffix), unelevated (*.UnelevatedButton), outlined (*.OutlinedButton) and text (*.TextButton). All button variants use the textAppearanceButton theme attribute for their typography styles.
The key attributes for customizing these styles are as follows:
  • backgroundTint: The tint color applied to the button background. The default enabled color is transparent for text buttons and colorPrimary for all other variants.
  • iconTint: The tint color applied to an optional button icon. The default enabled color is colorPrimary for text buttons and colorOnPrimary for all other variants.
  • rippleColor: The color of the button touch ripple. The default color is colorOnPrimary for raised/unelevated buttons and colorPrimary for outlined/text buttons.
  • strokeColor: The color of the stroke around the button background. The default color is colorOnSurface for outlined buttons and transparent for all other variants.
  • strokeWidth: The width of the stroke around the button background. The default value is 1dp for outlined buttons and 0dp for all other variants.
  • shapeAppearance: The shape appearance of the button background. The default value is shapeAppearanceSmallComponent.
The base button style (used by the MaterialButton widget class) can be customized and applied globally like so:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="materialButtonStyle">@style/AppButton</item>
</style><style name="AppButton" parent="Widget.MaterialComponents.Button">
    <item name="backgroundTint">?attr/colorSecondary</item>
</style>
The result can be observed in our playground screen:
Customized Button widget styles

Text Fields

Material Text Fields include two main variants. As a result of porting the pre-existing AppCompat TextInputLayout and TextInputEditText classes, there are in fact two base styles: Widget.MaterialComponents.TextInputLayout.* and Widget.MaterialComponents.TextInputEditText.*. The variants have a style suffix and include filled box (default, *.FilledBox) and outlined box (*.OutlinedBox). All text field variants use the standard text appearance for input and the textAppearanceCaption theme attribute for “helper” text (labels, errors, counters, etc.).
The key attributes for customizing the Widget.MaterialComponents.TextInputLayout.* styles are as follows:
  • boxBackgroundMode: The mode of the box background, which can be either filledoutline or none.
  • boxBackgroundColor: The color of the text field background. The default enabled color is colorOnSurface for filled box text fields and transparent for outlined box text fields.
  • boxStrokeColor: The color of the stroke around the text field background. The default color is colorOnSurface (in default state) for outlined box text fields and is ignored for filled box text fields.
  • hintTextColor/errorTextColor/counterTextColor: Various colors for different “helper” text sub-components.
  • shapeAppearance: The shape appearance of the text field background. The default value is shapeAppearanceSmallComponent.
The base text field style (used by the TextInputLayout widget class) can be customized and applied globally like so:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="textInputStyle">@style/AppTextField</item>
</style><style name="AppTextField" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
    <item name="boxBackgroundColor">@color/text_field_background</item>
</style>
Note: text_field_background is a res/color <selector> that uses colorSecondary and the same alpha values as the default boxBackgroundColor <selector>.
The result can be observed in our playground screen:
Customized Text Field widget styles

Cards

Material Cards are considered to be “surfaces” and make use of the Widget.MaterialComponents.CardView style. The key attributes for customizing them are as follows:
  • cardBackgroundColor: The color of the card background. The default color is colorSurface.
  • cardElevation: The elevation of the card. The default value is 1dp.
  • shapeAppearance: The shape appearance of the card background. The default value is shapeAppearanceMediumComponent.
The base card style (used by the MaterialCardView widget class) can be customized and applied globally like so:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="materialCardViewStyle">@style/AppCard</item>
</style><style name="AppCard" parent="Widget.MaterialComponents.CardView">
    <item name="cardElevation">8dp</item>
</style>
The result can be observed in our playground screen:
Customized Card widget style

Bottom Navigation

Material Bottom Navigation includes two main variants that inherit from the base Widget.MaterialComponents.BottomNavigationView style, with an optional style suffix: surface (default, no suffix) and colored (*.Colored). Bottom Navigation labels use the textAppearanceCaption theme attribute for their typography styles.
The key attributes for customizing these styles are as follows:
  • backgroundTint: The color of the bottom navigation background. The default color is colorSurface for surface bottom navigation and colorPrimary for colored bottom navigation.
  • itemTextColor/itemIconTint: The colors of bottom navigation item icons and labels. The default colors are colorOnSurface/colorPrimary(selected) for surface bottom navigation and colorOnPrimary for colored bottom navigation.
  • itemHorizontalTranslationEnabled: A flag to set whether or not a translation animation should occur when selecting bottom navigation items. The default value is false.
The base bottom navigation style (used by the BottomNavigationView widget class) can be customized and applied globally like so:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="bottomNavigationStyle">@style/AppBottomNavigation</item>
</style><style name="AppBottomNavigation" parent="Widget.MaterialComponents.BottomNavigation.Colored" />
The result can be observed in our playground screen:
Customized Bottom Navigation widget style
This is certainly not exhaustive. A more comprehensive list of all components and their attributes can be found in the Material Components for Android Docs.

Build a Material Theme

The Material Components for Android library includes a module that allows you to easily customize an existing Material Theme. It provides you with a set of XML files (color.xml/night/color.xmltype.xml and shape.xml) which include all of the necessary baseline theme attributes mentioned in this article. The values can be tweaked and previewed in a corresponding sample app. When you’re happy with the chosen values, the files can be dropped into a new/existing Android Studio project. A web version is also available on Glitch.
The “Build a Material Theme” sample app

More resources 📚


I hope this post has provided some insight into theming your app using Material Components for Android. If you have any questions, thoughts or suggestions then I’d love to hear from you!

Data Security(Encryption) in Android

Hello guys !!! hope you all are doing well. Today i am going to shed some light on data security in Android.
First start with basic , what is data security or encryption in Android?
Hiding plain data with some sort of changed format by using algo with key to convert and retrieve data is called data encryption.
Here Plain data will be any data(personal, financial etc) without any sort of hiding. So that any user can easily accessed your data.

Of course everything works vice versa, if you have a cipher data and you know the algorithm and have a key, you will get original plain data with ease.
Algorithm Types
As we saw a very basic example of encryption. Nowadays algorithms are more complex and are separated on Symmetric and Asymmetric (there’s also a Hash Functions, that do not require a key, I will discuss it in later blog).

Symmetric : —  the oldest and best-known technique. 
  • The encryption key and the decryption key are the same
  •  it is generally categorized as being either Stream Cipher or Block cipher
The most common Symmetric AES — the Advanced Encryption Standard (AES) is the algorithm trusted as the standard by the U.S. Government and numerous organizations.

Asymmetric  :—  a modern branch of cryptography. 

  • known as public-key cryptography in which the algorithms employ a pair of keys (a public key and a private key) 
  • use a different component of the pair for different steps of the algorithm
The most common Asymmetric algorithm is RSA — a public-key encryption algorithm and the standard for encrypting data sent over the internet.

Stream cipher : —  a symmetric encryption algorithm that processes the data a bit or a byte at a time with a key resulting in a randomized cipher data or plain data.

Block cipher  :—  deterministic algorithm operating on fixed-length groups of bits, called blocks. Block ciphers are important elementary components in the design of many cryptographic protocols, and are widely used to implement encryption of bulk data.

Modes & Paddings
Block cipher has different Modes and Paddings that increases it protection level.
Modes : —  a mode of operation describes how to repeatedly apply a cipher’s single-block operation to securely transform amounts of data larger than a block.
Padding : —  block cipher works on units of a fixed size (known as a block size), but messages come in a variety of lengths. So some modes (namely ECB and CBC) require that the final block be padded before encryption.

Most common modes :-
ECB : —  Electronic Codebook, the simplest of the encryption modes. The message is divided into blocks, and each block is encrypted separately.
CBC : —  Cipher Block Chaining, each cipher data block depends on all plain data blocks processed up to that point. To make each message unique, an initialization vector must be used in the first block.
But simply because algorithm is not symmetric does not mean it can not have modes and paddings. Thats, for instance, RSA algorithm can be used with ECB mode and PKCS1Padding.

Key Types
There are three key types: 

  • Secret key, 
  • Private key and 
  • Public key.
Secret key — a single secret key which is used in conventional symmetric encryption to encrypt and decrypt a message.
Private key — the secret component of a pair of cryptographic keys used for decryption in asymmetric cryptography.
Public key — The public component of a pair of cryptographic keys used for encryption in asymmetric cryptography.
Together Public and Private keys forms a public-private cryptographic Key Pair.


How Data security works in Android
Java Cryptography Architecture
  • Android data security builds on the Java Cryptography Architecture (JCA)
  • In Android JCA provides API for digital signatures, certificates, encryption, keys generation and management
KeyGenerator — provides the public API for generating symmetric cryptographic keys.
KeyPairGenerator — an engine class which is capable of generating a private key and its related public key utilizing the algorithm it was initialized with.
SecretKey — a secret (symmetric) key. The purpose of this interface is to group (and provide type safety for) all secret key interfaces (e.g., SecretKeySpec).
PrivateKey — a private (asymmetric) key. The purpose of this interface is to group (and provide type safety for) all private key interfaces(e.g., RSAPrivateKey).
PublicKey — a public key. This interface contains no methods or constants. It merely serves to group (and provide type safety for) all public key interfaces(e.g., RSAPublicKey).
KeyPair — this class is a simple holder for a key pair (a public key and a private key). It does not enforce any security, and, when initialized, should be treated like a PrivateKey.
SecureRandom — generates cryptographically secure pseudo-random numbers. We will not use it directly in this series, but it is widely used inside of KeyGenerator, KeyPairGenerator components and Keys implementations.
KeyStore — database with a well secured mechanism of data protection, that is used to save, get and remove keys. Requires entrance password and passwords for each of the keys. In other words it is protected file that you need to create, read and update (with provided API).
Certificate — certificate used to validate and save asymmetric keys.
Cipher — provides access to implementations of cryptographic ciphers for encryption, decryption, wrapping, unwrapping and signing.
Provider — defines a set of extensible implementations, independent API’s. Providers are the groups of different Algorithms or their customizations. There are 3rd party providers, such as Bouncy Castle and Spongy Castle (android version of Bouncy Castle), as well as providers available out of box, such as cut-down version of Bouncy Castle (we will take a bit deeper look on them, later on, during this article).
Android Key Store
AndroidKeyStore was introduced in API level 18.
Feature of Android Key Store(AKS):- 
  •  Lets you store cryptographic keys in a container to make it more difficult to extract from the device
  • Once keys are in the key store, they can be used for cryptographic operations with the key material remaining non-exportable
  • It offers facilities to restrict when and how keys can be used, such as requiring user authentication for key use or restricting keys to be used only in certain cryptographic modes
AndroidKeyStore is a JCA Provider implementation, where:
  • No KeyStore passwords is required (really, at all)
  • Key material never enters the application process
  • Key material may be bound to the secure hardware (Trust Zone)
  • Asymmetric keys are available from 18 +
  • Symmetric keys are available from 23 +
Notes:- 
  • If device manufacture supports Trusted Execution Environment(TTE), your keys will be saved there (the most secure option);
  • If device manufacture doesn’t support TTE, keys will be stored in emulated software environment, provided by the system.
  • In both cases, your keys will be automatically removed from the system after deleting the application. 
Also keys material is never exposed, even to us (we will see this later on). We will just work with key references, that is passed to KeyStore System Service, where, under the cover, all dirty work with key materials is done .
Sample Project 
In this project we will save user Secrets, locally, and keep them protected using Encryption, Fingerprint and Confirm Credentials API’s. 
User creates a master password (during sign up process). This password will be used to protect Secrets: to add new, view, edit and delete already created Secrets, user needs to enter master password.
What is Secret ? Anything user want to kept protected: gmail password, credit card pin code
In Next Blog I will discuss Lock Screen, Choose a Key, Key Storage, Key Generation, Key Management, Encryption & Decryption, Usage Example

Thanks
Happy Coding!!!!

AlarmManager Vs WorkManager Android Background task processing

AlarmManager Vs WorkManager Android Background task processing

 Hi Guys!!!

Today topic is " background processing in Android" . There is a lot of things added in Android from initial day to till now to perform background processing in android efficiently.

Today i am going to focus on Alarm Manager and Work Manager API in Android.

As we know every Android app has a main thread which is in charge of handling UI (including measuring and drawing views) , coordinating user interactions, and receiving lifecycle events.

If there is too much work happening on this thread, the app appears to hang or slow down, leading to an undesirable user experience. That's why we need to off load Main UI Thread and perform long operation in background.

When to use WorkManager
  • If the work dependent on system conditions
  • Your job to run only when the device meets certain conditions(such as being connected to power) 
WorkManager mWorkManager = WorkManager.getInstance(MainActivity.this);
PeriodicWorkRequest.Builder myWorkBuilder =
        new PeriodicWorkRequest.Builder(RebootWorker.class, 1, TimeUnit.MINUTES);
PeriodicWorkRequest workRequest = myWorkBuilder.build();
WorkManager mWorkManager.enqueue(workRequest);

When to use AlaramManager


  • Job need to run at a precise time
  • A calendar app might let a user set up a reminder for an event at a specific time

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, uniqueInt, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, pendingIntent);

Choosing the right background Processing for your work
There is lot more  long background task processing is avilable to perform your job as per your requirement. I named few below :-
  • WorkManager
  • Foreground services
  • AlarmManager
  • DownloadManager

Use below decision making daigram to choose right one


Thanks 
Saroj Kumar Malik

Git Command Line as easy as possible

Git Command Line as easy as possible

Git Status
git status
git status -- short

Manipulate the Changes
git add file_name  >> adds the file file to the stage section
git restore file_name >> discards changes to the file
git restore --staged file_name >> removes the file from the stage section

Inspecting the diffs
git diff . >> displays the not-staged changes in your working tree
git diff --staged >> displays the staged changes
git diff dev >> displays changes between the working tree and the dev branch. You might use a commit hash or tag instead.
git diff master..dev >>displays changes between the branches master and dev

Committing
git commit -m 'Commit message'
git config --global core.editor your-editor-executable-path

Switch
The switch command can be used to switch between branches.
git switch branch-name >> switches to a branch-name branch
git switch -b abc >> creates branch abc and switches to it
git switch - >> switches you to the previous branch
git checkout [branch_name] >> works as a switch but can also move HEAD to any commit/tag as well

Branches
git branch >>> returns a list of the local branches.
Use -r to list only remote branches or -a to get them all
git branch abc >>> creates abc branch
git branch -d abc >>> deletes abc if already merged.
If not, use -D to force deletion.

Log Results
git log >>> to see the commits’ history.
git log -p >>>Display the changes alongside the commit description:
git log -2 >>> display two recent commits
git log branch-name  >>>Display log for a specific branch/revision:
Filter log for a specific file(s) only (glob pattern applies here):
git log *.js # or git log branch-name:*.js
Filter commits by the author (accepts partial name):
git log --author saroj
Filter by date:
git log --since 2019-10-01
Filter by date using dynamic date ranges (days, weeks, months, years):
git log --since 2months --until 1week

Thanks
Saroj Kumar Malik

Scoped Storage in Android

Scoped Storage in Android

In Android 10 (SDK version 29) many new features were introduced and Scoped Storage is one of them. 

The Problem, Why scoped storage introduced in Android Q?

  • Before Android 10, we have a concept of Shared Storage
  • Every application in the device has some private storage in the internal memory and you can find this in android/data/your_package_name directory 
  • Apart from this internal storage, the rest of the storage is called the Shared Storage i.e. every application with the storage permission can access this part of the memory.
  • This includes media collections and other files of different applications. 

1st Problem

  • application having the storage permission doesn't require the access of all of these files always
  • For example,needs to select a user image to upload it as the profile picture and nothing else. 

So, why to provide them with the full access to that Shared Storage?

2nd problem 

  • application is having such a wide writing capability on the storage then the files generated by the application gets scattered 
  • when the user uninstalls the application then the files generated by the application remains in the storage and not deleted and takes a lot of space.

So, we need some kind of mechanism, with the help of which the apps can get the specific access they need without getting such a broad reading and writing power that they don't actually need.
This can be done with the help of Scoped Storage.

The Solution - Scoped Storage
Better Attribution: 

  • Better attribution means the system knows which file is generated by which application
  • when user uninstall an application from the device then all the contents related to the app will also be removed unless the user explicitly wants to keep it.

App data protection: 

  • the external storage is accessed by applications with storage permission
  • With the help of Scoped Storage, the data in the external storage can not be easily accessed by other applications

Key features of Scoped Storage
Unrestricted access: 
  • Every application has unrestricted access to its own storage( internal as well as external)
  • you don't need to provide storage permission to write files to your own app directory on the SD card.
Unrestricted media: 
  • unrestricted access to contribute files to the media collections and downloads of your own app.
  • No need to take permission if you want to save any image, video, or any other media file in media collection. 
  • You can read or write media files created by you
  • To read the media file of other application, you need to get the "READ_EXTERNAL_STORAGE" permission from the user. 
Organized collection: 
  • organized media collection like for images, videos, etc and downloads collection for non-media files.
  • There is new permission introduced in Android 10 i.e. ACCESS_MEDIA_LOCATION( get the location of the media )
For example, sometimes the picture taken by a camera also shows the location of the picture that was taken. So, if you want to show that location then you have to take this permission. 
It is runtime permission, so you need to declare this in your manifest file and from the MediaStore object, call the setRequireOriginal(), passing the URI of the image.
System Picker: 
  • In order to access other files except for these media files, we have to use System Picker which is accessed using the Storage Access Framework.
  • Read/write from outside: To read and write any files outside the collection, you need to use the System Picker.

How to access simple files(using System Picker)?
  • In order to access files on the device, you can use the Storage Access Framework (SAF).
  • By using ACTION_OPEN_DOCUMENT a dialog will be shown to the user where the needed documents can be selected. 
  • There’s also ACTION_OPEN_DOCUMENT_TREE to ask the user to select a directory and
  • ACTION_CREATE_DOCUMENT in order to save files.
Sample Application 
I am creating a sample application to demonstrate scope permission.  You can find it in my GitHub account 
screen shot

Thanks
Saroj Kumar Malik
Happy Coding !!!

How to enable scrollBar in RecyclerView

Markdown:
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical" />
Fortunately, RecyclerView has its own “android:scrollbars” option.
If you need a vertical scrollbar, then add your RecyclerView’s XML :
android:scrollbars="vertical"
If you need a horizontal scrollbar, then add your RecyclerView’s XML :
android:scrollbars="horizontal"
So easy and thanks Google Devs to put this option for us :P
If you have any question, ask me :)

How to create Menu and its items programmatically

Hey,
I needed to create a Menu XML programmatically for a library. After a lot of research about it, i got almost nothing useful but actually it is hilariously easy to create dynamically.
Firstly we need to create a Menu object :
Menu menu = new MenuBuilder(getApplicationContext());
Then we can create as many item as we need by :
menu.add(0, Menu.FIRST, Menu.NONE, R.string.itemName).setIcon(R.drawable.itemDrawable);menu.add(1, Menu.FIRST + 1, Menu.NONE, R.string.itemName2).setIcon(R.drawable.itemDrawable2);
It is extremely simple and easy to use.
If you have any question, ask me :)

How to create Menu item for NavigationDrawer programmatically

Hey,
If you need to create a menu item for your NavigationDrawer dynamically, then this is the best way to do it.
First we need to initialize our NavigationView, Menu and SubMenu objects :
// SubMenu Initialization
SubMenu subMenu;// NavigationView Initialization
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);// Menu Initialization
Menu menu = navigationView.getMenu();

How to add submenu and its items ?

subMenu = menu.addSubMenu(getString(R.string.subMenuTitle));
subMenu.add(0, Menu.FIRST, Menu.FIRST, getString(R.string.itemName))
        .setIcon(R.drawable.itemDrawable);
subMenu.add(1, Menu.FIRST + 1, Menu.FIRST, getString(R.string.itemName))
        .setIcon(R.drawable.itemDrawable);
As you can see first we create a submenu and set it a Title name. After that we can simple add a submenu item.

How to set that item onNavigationItemSelected? (Click Part)

int id = item.getItemId();if (id == subMenu.getItem(0).getItemId()) {
   // Magic Here
}
This code segment should be in “onNavigationItemSelected” part. Once you created a submenu, you can use it by getItem() and its item ID.

How to exit Application

Hey,
Unfortunately, Android Design does not provide any exit choice but we can exit the application via Intent.
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

This code segment let you perfectly exit the application.
If you have any question, ask me :)

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...