Multi Window Android 7.0

Google recently released Android 7.0 or Android Nougat, many new features were released with this on of them was Multi Window Support, cool right more than one app at the same time. So now you can chat as well as read something without switching between apps which in some way was frustrating for me.

So let’s see what is changed from development prospect.

The biggest relief for developers is that Multi Window doesn’t affect the life-cycle of activity. Activity the user has interacted with recently is active at a time, other activities are in paused state even though they are visible. If user interact with such paused activity then it becomes the topmost activity(active one) and the topmost goes to paused state(note only paused not hidden it would still be visible).

Note:  As now the activity which as paused is still visible so we have to keep in mind what code  is handled in onPause() and onStop(). For example now if one of your app is playing video then it must continue playing it even activity is paused(as it is still visible), so now we must not stop the video in onPause() and the code for that should be moved to onStop().

The handling multi window is same as Handling Runtime Changes. So when app resizes we have to handle it the same way we handle runtime changes.

App Configuration

Make target API level to 24 or higher and add the following attribute to your activity

android:resizeableActivity=["true" | "false"]

if this is set to true then only your app will support multi window. Also if you set this attribute true in root activity then all the activities will support multi window.
If your app target is API 24, and you didn’t specify this attribute then it is true by default.

Addition to Layout Attributes

android:minHeight="100dp"
android:minWidth="100dp"

These are the new addition which defines the minimum height and width which your activity can have while it is in multi-window.

For more details please refer to below link
Multi-Window

Thanks for reading 🙂

Happy developing.



			

Resolving Unsupported major.minor version 52.0 issue in Android Studio

Recently I opened my Android project and it showed me an annoying error which was something like

Error:Cause: com/android/build/gradle/internal/model/DefaultAndroidProject : 
Unsupported major.minor version 52.0

I had no clue what is this and how to resolve this.

I was using Java 7 so first thing I did was to update my Java environment to 8. But even this won’t resolve the issue so googled the problem and found many solutions but all of them are way different than another.

So I have mentioned all the steps here to resolve this issue and they are as follows

1. Update your Java to Java 8.
2. Open File -> Project Structure or simply shift + Ctrl +alt + s.
3. Open project level build.gradle and change the build tools to this

classpath 'com.android.tools.build:gradle:2.1.0'

 

After this clean your project and and everything will be fine again.

Parsing Json Data without giving KeyNames Android

For parsing json data we need to have keys and we either create a modal class to get data or use JSONObject to get data.

So In case if dynamic data is present in web service response, we wouldn’t have fixed key data to parse in that case you can do the following

Iterator<String> keys= jsonObject.keys(); 
while (keys.hasNext())  {         
String keyValue = (String)keys.next();         
String valueString = jsonObject.getString(keyValue);
}
That’s it you have parsed data without using keys.

Making EditText Look Cool Android

Hello,

Recently I was working with EditText, basically trying to make a login form and found something cool about a new layout i.e. InputTextLayout which is used with EditText to create some cool animation between hint and EditText content.

To use this first you have to add the following to your dependency in build.gradle(the one present within app folder).

 

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.4.0'
}

 

After this just your project will sync and you are ready to go.

Go to your layout file and add the below  xml content

<android.support.design.widget.TextInputLayout
    android:id="@+id/input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <EditText
        android:id="@+id/editText"
       android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Have Fun" />
</android.support.design.widget.TextInputLayout>

Yeah, you have add all the important things now let’s jump to code part.

One more cool thing with this layout is that you can also add error messages, so no need to show those ugly toast and snackbars(If you don’t know about this, add your comments below and I will create a blog for this).

TextInputLayout mInputLayout =(TextInputLayout) findViewById
(R.id.input_layout);

public void checkFieldValidity(View view) {
    if (TextUtils.isEmpty(mEditText.getText().toString().trim())) {
        mInputLayout.setErrorEnabled(true);
        mInputLayout.setError("Field Is Empty");
    } else {
        mInputLayout.setErrorEnabled(false);
    }
}

Please refer to gitHub repo for more details

https://github.com/ankitkhare/inputTextEx

Keep developing….keep having fun 🙂

Strict Mode Developer Option

We all might have face a serious issue of ANR i.e. Application not responding dialog. This is because of the blocking of UI thread, whenever the app has taken more than 5 seconds to return from an event handler  this dialog appears(some of the clients faint after seeing this ;)).

Whenever the UI thread is blocked for long the application has nothing to show to user because all the user input are processed and draw to the screen in UI thread only. Basically the system calls are the major components that are responsible for blocking UI thread .So let’s try to understand the major areas where this can happen

  • Network operations.
  • Loading 100 of bitmaps.
  • Reading or writing certain content to a file.
  • And goes on…..

Here i’m going to tell you how to find a blocking call in your app.

  • Go to settings
  • Then developer options(if not already present click on About Device and the click build number multiple times.)
  • Check mark strict mode enabled(in monitoring category)

After that open your app and do your work and whenever their is a blocking call you will see red border around your device corners indicating their  is a potential performance issue.So you can check these blocking call’s to prevent your app ANR(the horror).

Using strict mode is like defining the policy for various threads in your application. And like every other policy there are certain rules for it.

  • One would be detecting a blocking call(Detection Mode).
  • The other would be what to do when a blocking call is present(Penalty Mode.)

For Penalty mode Strict Mode API contains many options such as flashing red, writing to logs show ANR.

http://developer.android.com/reference/android/os/StrictMode.html

For more details on Strict Mode see the above link.

For more performance pattern related things visit this channel.

http://goo.gl/4ZJkY1

Thanks for reading :).

Securing Your Code Using ProGuard In Android

Hello Developers have you ever given a thought about securing your code so that no one could look at it by reverse engineering your apk. If yes then this blog will help you learning about ProGuard. Proguard is a tool which shrinks,optimize and obfuscate your code. It removes unused code and changes classes, variables name to unreadable form so that it is hard to reverse engineer your .apk. The other advantage of  ProGuard tool is it reduces the size of your .apk file. Important points about ProGuard tool in android are:

  • Android build system already comes integrated with ProGuard tool so you do not have to do anything extra.
  • ProGuard tool only runs in release mode so that in debug mode you don’t have to deal with obfuscate code.
  • ProGuard is completely optional but it is highly recommended that you use this in release mode.

Now for using ProGuard in your project perform the following steps:

  • Go to project-properties file which is present in the root folder of your project.
  • Edit this file and uncomment the “proguard.config” line and assign the path of your sdk like this “proguard.config=/home/ankitkhare/Android/Sdk/tools/proguard/proguard-android.txt:proguard-project.txt“(as i am using ubuntu so i have given this path in windows it would be like E:/android/sdk/tools/proguard/proguard-android.txt:proguard-project.txt” or where ever your sdk is installed).
  • If you are using Android Studio then in your project  you must have file named proguard – rules.pro and the build.gradle. Inside build.gradle add android { buildTypes { release { // Following lines to run progaurd in android. minifyEnabled true proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’ } }
  • Then export your project in release mode.
  • Once you are done with this there would be a ProGuard folder added to your project(If not then there must be some error).

Now navigate to your .apk file(the path of apk you mentioned while exporting application) and unzip it. Open any file and you will see that the file is in unreadable form to be more precise it is Obfuscated. I have created a demo project https://github.com/ankitkhare0804/ProguardDemo In next part would cover the important points to remember  while using ProGuard, how to use retrace and also debugging considerations for published applications. Hope you found this helpful. Thanks for reading :).

Securing Content in Google play In-app Billing

Hello Developers i am sure you all have worked on Google play In-app Billing(if not don’t worry you will be doing it in future). In-app billing is responsible for making purchase through your app. User buys an item through an app and pay money through their bank details.The whole process is achieved via Google play In-app Billing and we are here to discuss about the things which the developers should keep in mind while publishing In-app billing app to Play store. These points will help an application

Here are few points which you should keep in mind while you are working on In-app billing

  • Do not put your content in bundled in the apk as attackers can extract it and distribute it, so instead of putting them in apk trying to put them on a remote server and parse them as per your needs. This will ensure your content is safe and it is always fresh.
  • Use tools like Proguard to shrink optimize and obfuscate your code so that it would be difficult for the attackers to reverse engineer your code and the data integrity is ensured.
  • Do verification process on server side instead to doing it on device, doing verification this way will prevent attackers to know about the verification process by reverse engineering your apk.
  • Prevent your Google play API key at all cost try to manipulate it using bit manipulation to hide actual key.
  • In In-App billing version 3 API there is a developer payload string which is used for sending any details of purchase to Google play and Google play reverts back with the same string in response. Pass this string as token in your application, this will help you identifying the user who made purchase and whether that transaction was genuine or not.
  • If you have created the application by taking the sample application code then don’t forget to modify your code before releasing the app for production purpose and try to use sample provided by Google only.

Make sure you follow these points before publishing your application. as this would prevent the malicious attacks on your applications.

For more details on this go through the following link

http://developer.android.com/google/play/billing/billing_best_practices.html

Hope you find this useful.

Thanks for reading :).

Updating Security Provider Asynchronously In Android

SSL refers to Secure Socket layer which is responsible for secure communication between client and server. SSL encrypts data when it is being transferred over network, thereby securing the communication between client and server.

In android this work is done by security provider. Security provider provides secure communication over network. So security provider must remain updated all the time to prevent exploitation attacks.

This can be achieved by using Google Play Services. Google Play Services consists of ProviderInstaller which can be used to update device security provider.

Provider Installer is used to check whether device security provider is updated or not, if not it automatically updates the provider. It contains two method’s which are used to check whether the security provider is updated or not and they are

  • installIfNeeded().
  • InstallIfNeededAsync().

These two methods provides a way to update security provider either synchronously or asynchronously.

Here we will update the provider asynchronously.

Here are the steps which are required before updating the provider

  • Use Google Play Services(which can be found in your adt → sdk → extras → Google →Google_play_services → libproject → google-play-services_lib . If not found please open sdk manager and under extras tick Google play services and update) as library project in your application.
  • Set meta data tag in your android manifest inside application tag.
    <meta-data
       android:name="com.google.android.gms.version"
       android:value="@integer/google_play_services_version" />

Here is the class which is used to update the security provider.

/**
* This class checks for Security provider update , if it's not updated then the
* update is installed.
* 
* @author Ankit Khare
*/
public class MainActivity extends Activity implements ProviderInstallListener {
/**
* Updating provider asynchronously.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Update the provider asynchronously
ProviderInstaller.installIfNeededAsync(this, this);
}
/**
* The provider is already installed and up-to-date.
*/
@Override
public void onProviderInstalled() {
Toast.makeText(this, "Provider Installed.Google play Services are up-to-date", Toast.LENGTH_SHORT).show();
}
/**
* Provider Installation failed. Check errorCode whether it is recoverable
* or not.
*/
@Override
public void onProviderInstallFailed(int errorCode, Intent intent) {
if (GooglePlayServicesUtil.isUserRecoverableError(errorCode)) {
// Retry to install update in case of recoverable error.
ProviderInstaller.installIfNeededAsync(this, this);
} else {
// Please update your Google Play Services.
}
}
}

This class updates the security provider asynchronously by using callbacks to ProviderInstallListener. If the provider is already updated onProviderInstalled() is called otherwise the call goes to onPorviderInstallFailed().

For Detail Information refer to

https://developer.android.com/training/articles/security-gms-provider.html

Thanks for reading 🙂

Overview Of Android Security Structure

Android is world’s most popular mobile OS. The reason behind it’s popularity is it’s open nature. Applications can use hardware as per it’s requirements with no restrictions, at the same time maintaining it’s security aspects. Android design structure reduces the security concerns so that the developers do not have to worry about the security issues and have to focus only about the design and logic of the application.

Key Issues which a OS needs to worry about are

  • Prevent the misuse of hardware resources.
  • Prevent the application data from misuse.
  • Secured IPC(Interprocess Communication).
  • Restricting applications to perform malicious attacks.

These all issues were kept in mind while developing android, below are the points on which on which android focuses on.

Key Security Features of Android are 

  • *Sand-boxing of the applications.
  • Applications are signed before they are published.
  • **ASLR(Address Space Layout Randomization).
  • Before applications are installed on device permissions are displayed to the user so that he can choose whether to provide these permissions or not or in short install application or not.
  • Secured IPC(Interprocess Communication).

These all features reduces the pain of developers so that they only have to focus on application design and logic but not on security concerns.

All though Android provide most of the security features itself but the developers have to keep in mind the following points while creating an applications:

  • Only set those permissions which are required by the application for eg. if you want to access the images from sd card for read only purpose and have to intention to modify them, then you must only  provide “android.permission.READ_EXTERNAL_STORAGE” and not “android.permission.WRITE_EXTERNAL_STORAGE“.
  • If you are creating content provider in your application and it’s not intended to be shared among other applications then you  must mention “android:exported=false” in your application manifest otherwise another application can access  your application data.
  • Perform validations where necessary such as email or phone number.

For Detail Information visit the link.

http://developer.android.com/training/articles/security-tips.html

Thanks for reading 🙂

*Sandbox refers to separating your application data and code execution from other applications.

**https://khareankit0804.wordpress.com/2014/09/30/aslr-in-android/ 

AES Encryption In Android

AES stands for Advanced Encryption Standard is an encryption algorithm which is used to encrypt data so that it is converted to such a form which cannot be interpreted by anyone. AES is a symmetric algorithm which means same key is used to encrypt and decrypt the data. In AES the key which is used for encryption is in multiple of 32 bits with a minimum of 128 bits and maximum of 256 bits. There are three types of AES which are categorized on the basis of it’s key length. So “AES-128”, ”AES-192” and “AES-256” are all AES algorithm, but the major difference between them is of key length.

Here is AES Encryption class which contains all the methods which are required for encryption and decryption of data.

/**
* This is AES symmetric encryption helper which contains methods for encryption and decryption.
* @author Ankit Khare
*/
public class EncryptionHelper {
private static final String AES = "AES";
private Activity mActivity;
public EncryptionHelper(Activity iActivity) {
mActivity = iActivity;
}
/**
* This method generates the key with the help of which encryption and decryption is done.
* @param secretKey
* @return
* @throws NoSuchAlgorithmException
*/
public SecretKeySpec generateSecretKeySpec(String secretKey) throws NoSuchAlgorithmException {
SecureRandom secureRandom = new SecureRandom(secretKey.getBytes());
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(256, secureRandom);
SecretKeySpec keySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), AES);
return keySpec;
}
/**
* This method returns the encrypted form of the data.
* @param secretKey the key which is used for encryption. It should be of 128 bits.
* @param data data to be encrypted.
* @return encrypted string
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public String getEncodedString(String secretKey, String data) throws IllegalBlockSizeException, BadPaddingException {
byte[] encodedBytes = null;
try {
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
encodedBytes = cipher.doFinal(data.getBytes());
}
catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
Toast.makeText(mActivity, "Encryption failed!", Toast.LENGTH_SHORT).show();
}
if (encodedBytes != null)
return Base64.encodeToString(encodedBytes, Base64.DEFAULT);
else
return null;
}
/**
* This method is used to decrypt the encrypted data.
* @param secretKey the key which is used for encryption. It should be of 128 bits.
* @param encryptString encrypt string which is to be decrypted.
* @return the original data.
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
*/
public String getDecodedString(String secretKey, String encryptString) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
byte[] decodedBytes = null;
try {
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), AES);
Cipher cipher = Cipher.getInstance(AES);
byte[] encodedBytes = Base64.decode(encryptString.getBytes(), Base64.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
decodedBytes = cipher.doFinal(encodedBytes);
}
catch (IllegalBlockSizeException | BadPaddingException e) {
Toast.makeText(mActivity, "Decryption failed!", Toast.LENGTH_SHORT).show();
}
if (decodedBytes != null)
return new String(decodedBytes);
else
return null;
}
}

Use this code in your activity to encrypt and decrypt the data.

Thanks for reading 🙂