December 16, 2024

How we can generate RSA KeyPair from AndroidKeyStore

           Here am going to explain how we can generate RSA  KeyPair (PrivateKey and PublicKey) from AndroidKeyStore also how we can get retrieve these keys from the AndroidkeyStore.

Here I am having an object file SecureStore.kt, where I am going to show you how we can generate RSA KeyPair (PrivateKey and PublicKey) also How we can read PrivateKey from the AndroidKeyStore.


Generate RSA KeyPair 

    fun generateDeviceKeyPair(): KeyPair {
        val keyGen = KeyPairGenerator.getInstance("RSA", provider)
        keyGen.initialize(
            KeyGenParameterSpec.Builder(
                DEVICE_KEYPAIR_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            ).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                .setKeySize(4096)
                .build()
        )
        return keyGen.generateKeyPair()
    }

The above function generateDeviceKeyPair() will generate a new RSA KeyPair from AndroidKeyStore with a KeySize 4096.




Getting PrivateKey from AndroidKeyStore


   fun getDevicePrivateKey() : PrivateKey?{
        if(androidKs.containsAlias(DEVICE_KEYPAIR_ALIAS))
            return  androidKs.getKey(DEVICE_KEYPAIR_ALIAS, null) as PrivateKey
        return null
    }

The above function getDevicePrivateKey() will return the PrivateKey of the RSA KeyPair which we created before



Final Code

package com.b-mates.utils

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey

object SecureStore {

    private const val provider = "AndroidKeyStore"
    private const val DEVICE_KEYPAIR_ALIAS = "DEVICE_KEYPAIR_ALIAS"
    val androidKs = KeyStore.getInstance(provider).apply { load(null) }

    fun generateDeviceKeyPair(): KeyPair {
        val keyGen = KeyPairGenerator.getInstance("RSA", provider)
        keyGen.initialize(
            KeyGenParameterSpec.Builder(
                DEVICE_KEYPAIR_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            ).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                .setKeySize(4096)
                .build()
        )
        return keyGen.generateKeyPair()
    }


   fun getDevicePrivateKey() : PrivateKey?{
        if(androidKs.containsAlias(DEVICE_KEYPAIR_ALIAS))
            return  androidKs.getKey(DEVICE_KEYPAIR_ALIAS, null) as PrivateKey
        return null
    }
}

May 12, 2024

Check Camera is Accessed By Other App in kotlin

We are create one Context function with a call back in kotlin, Using this function you can find is camera accessed by other app or not,


Function calling,

context.isCameraAccessedByOtherApp { accessed ->
if(accessed){

 
}else{

}
}


Function to check is camera accessed by other application

fun Context.isCameraAccessedByOtherApp(callback:(Boolean) -> Unit){
    try {
        val manager: CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val allCameraIds: Array<String> = manager.cameraIdList
        val busyCams = mutableListOf<String>()
        val availableCams = mutableListOf<String>()
        fun check(){
            if((busyCams.size + availableCams.size) == allCameraIds.size){
                callback(busyCams.isNotEmpty())
            }
        }
        manager.registerAvailabilityCallback(
            object: CameraManager.AvailabilityCallback(){
                override fun onCameraAvailable(cameraId: String) {
                    super.onCameraAvailable(cameraId)
                    availableCams.add(cameraId)
                    check()
                }
                override fun onCameraUnavailable(cameraId: String) {
                    super.onCameraUnavailable(cameraId)
                    busyCams.add(cameraId)
                    check()
                }
            },
            Handler(Looper.getMainLooper())
        )
    } catch (e: CameraAccessException) {
        callback(false)
    }
}

Integration of mutual TLS (mTLS) authentication using Retrofit Android Kotlin

Integrating mutual TLS (mTLS) authentication in Kotlin involves configuring both the client and server sides.  Android using BouncyCastleProvider for the integration of mutual TLS (mTLS). You basically you need to have 3 files (.pem format) for this use case:

1. Client private key

2. Client certificate chain

3. Trusted server certificate

Here we are using  Retrofit (Retrofit2) Client for the mTLS integration


Step1 :  Create .pem file of the above mentioned files(Client private key,  Client certificate chain, Trusted server certificate). You can copy the certificate on notepad and save it as .pem file, Here is the sample file formats,

1. Client private key

-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKc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MCMA4GA1UdDwEB/wQEAwIFoDA5BgNVHR8EMjAwMC6gLKAqhihodHRwOi8vY3Js
LmdvZGFkZHkuY29tL2dkaWcyczEtMTI1OTEuY3JsMF0GA1UdIARWMFQwSAYLYIZI
AYb9bQEHFwEwOTA3BggrBgEFBQcCARYraHR0cDovL2NlcnRpZmljYXRlcy5nb2Rh
Eztn7A0CIQCNbL3lir3b0zB6/240tqI6TWL/eDBt3Un9LwnNlUyn3AB2ANq2v2s/
tbYin5vCu1xr6HCRcWy7UYSFNL2kPTBI1/urAAABjBoMfFsAAAQDAEcwRQIhAMTd
RFDg8qL4LyHxp+CsMR41DADbBbf0dm9QbRNDq1bVAiBoe3ZTfDWGbcO115X23Dzy
Zm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ8wDQYDVQQKDAZCYWRTU0wx
IjAgBgNVBAMMGUJhZFNTTCBDbGllbnQgQ2VydGlmaWNhdGUwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQDHN18R6x5Oz+u6SOXLoxIscz5GHR6cDcCLgyPa
x2XfXHdJs+h6fTy61WGM+aXEhR2SIwbj5997s34m0MsbvkJrFmn0LHK1fuTLCihE
Xw41pTYYN6xNEdJ0vVejAHUAfVkeEuF4KnscYWd8Xv340IdcFKBOlZ65Ay/ZDowu
ebgAAAGPUjS5TgAABAMARjBEAiBpXLn4s9j2LFc4cvASbnFWKUpYP3oQyCTbFWGW
9R8Lag==
-----END CERTIFICATE-----


Once you create these files save these files on the raw folder inside the res folder,

res/raw/server_certificate.pem
res/raw/client_private_key.pem
res/raw/client_certificate_chin.pem


ApiService.kt file 

import okhttp3.ResponseBody
import retrofit2.http.*
interface ApiService {
    @POST("/apipath/function")
    suspend fun sendMtlsRequest(@HeaderMap headerMap: HashMap<String, Any>, @Body hashMap: HashMap<String, Any>): ResponseBody
}



Making API Call,

    fun sendApiRequest(context : Context, headerMap: HashMap<String, Any>, map: HashMap<String, Any>) = getApiResult<Nothing> {
        var attestationSpiService = getApiServiceWithMTLS(context)
        attestationSpiService.sendMtlsRequest(headerMap, map)
    }

Function to making ApiService,


import android.content.Context
import java.security.cert.CertificateFactory;
import java.io.InputStream;
import java.security.cert.Certificate;
import com.google.common.io.ByteStreams
import java.security.KeyStore
import java.util.Base64;
import javax.net.ssl.X509TrustManager
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.io.InputStream;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import okhttp3.OkHttpClient
import com.google.gson.GsonBuilder
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.NoSuchAlgorithmException
import java.security.cert.CertificateException
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.security.KeyStoreException


fun getApiServiceWithMTLS(context : Context): ApiService {

        val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")

        var certificateChin = context.getResources().getIdentifier("server_certificate","raw", context.getPackageName());
        val trustedCertificateAsInputStream: InputStream = context.resources.openRawResource(certificateChin)
        val trustedCertificate: Certificate = certificateFactory.generateCertificate(trustedCertificateAsInputStream)
 
        val trustStore: KeyStore = createEmptyKeyStore("secret".toCharArray())
        trustStore.setCertificateEntry("edfapay-server", trustedCertificate);

        var pkeyBytes = ByteStreams.toByteArray(context.resources.openRawResource(R.raw.client_private_key))
        val privateKeyContent = String(pkeyBytes, StandardCharsets.UTF_8)
            .replace("-----BEGIN PRIVATE KEY-----", "")
            .replace(System.lineSeparator().toRegex(), "")
            .replace("-----END PRIVATE KEY-----", "")
            .replace("\\n","")

        var privateKeyAsBytes = Base64.getMimeDecoder().decode(privateKeyContent);

        val keyFactory: KeyFactory = KeyFactory.getInstance("RSA")
        val keySpec = PKCS8EncodedKeySpec(privateKeyAsBytes)

        val certificateChainAsInputStream: InputStream = context.resources.openRawResource(R.raw.client_certificate_chin)
        val certificateChain: Certificate = certificateFactory.generateCertificate(certificateChainAsInputStream)
        var certificate: Array<Certificate> =  arrayOf(certificateChain)

        val identityStore = createEmptyKeyStore("secret".toCharArray())
        var privateKey = keyFactory.generatePrivate(keySpec)
        identityStore.setKeyEntry("client", privateKey, "".toCharArray(), certificate);

        trustedCertificateAsInputStream.close();
        certificateChainAsInputStream.close();

        val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(trustStore);
        val trustManagers = trustManagerFactory.trustManagers

        val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
        keyManagerFactory.init(identityStore, "secret".toCharArray());
        val keyManagers = keyManagerFactory.keyManagers

        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(keyManagers, trustManagers, null);

        val socketFactory: SSLSocketFactory = sslContext.socketFactory

        val okHttpClient = OkHttpClient.Builder()
            .sslSocketFactory(socketFactory, trustManagers[0] as X509TrustManager)
            .build()

        val json = GsonBuilder().setLenient().create()

        val retrofit = Retrofit.Builder()
            .baseUrl("https://api.shidhints.com/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(json))
            .build()
        return retrofit.create(ApiService::class.java)
    }


    @Throws(CertificateException::class, NoSuchAlgorithmException::class, IOException::class, KeyStoreException::class)
    fun createEmptyKeyStore(keyStorePassword: CharArray?): KeyStore {
        val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
        keyStore.load(null, keyStorePassword)
        return keyStore
    }



June 27, 2022

Advanced android interview questions

 What is Application class?

The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.


What is onSavedInstanceState() and onRestoreInstanceState() in activity?

onSavedInstanceState() - This method is used to store data before pausing the activity.

onRestoreInstanceState() - This method is used to recover the saved state of an activity when the activity is recreated after destruction. So, the onRestoreInstanceState() receive the bundle that contains the instance state information.


What is the difference between FragmentPagerAdapter vs FragmentStatePagerAdapter?

FragmentPagerAdapter: Each fragment visited by the user will be stored in the memory but the view will be destroyed. When the page is revisited, then the view will be created not the instance of the fragment.

FragmentStatePagerAdapter: Here, the fragment instance will be destroyed when it is not visible to the user, except the saved state of the fragment.


What is the purpose of addToBackStack() while commiting fragment transaction?

By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button. 


What are ViewGroups and how they are different from the Views?

View: View objects are the basic building blocks of User Interface(UI) elements in Android. View is a simple rectangle box which responds to the user’s actions. Examples are EditText, Button, CheckBox etc. View refers to the android.view.View class, which is the base class of all UI classes.

ViewGroup: ViewGroup is the invisible container. It holds View and ViewGroup. For example, LinearLayout is the ViewGroup that contains Button(View), and other Layouts also. ViewGroup is the base class for Layouts.


What is a Sticky Intent?

Sticky Intents allows communication between a function and a service. sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). For example, if you take an intent for ACTION_BATTERY_CHANGED to get battery change events: When you call registerReceiver() for that action — even with a null BroadcastReceiver — you get the Intent that was last Broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.


What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes.

Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).

There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activity, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-running background tasks, a different mechanism (such as a service) should be employed.

Note: AsyncTasks by default run on a single thread using a serial executor, meaning it has only 1 thread and each task runs one after the other.


What is commit() and apply() in SharedPreferences?

commit() returns a boolean value of success or failure immediately by writing data synchronously.

apply() is asynchronous and it won't return any boolean response. If you have an apply() outstanding and you are performing commit(), then the commit() will be blocked until the apply() is not completed.


What is a SpannableString?

A SpannableString has immutable text, but its span information is mutable. Use a SpannableString when your text doesn't need to be changed but the styling does. Spans are ranges over the text that include styling information like color, heighliting, italics, links, etc


Differences between abstract classes and interfaces?

An abstract class, is a class that contains both concrete and abstract methods (methods without implementations). An abstract method must be implemented by the abstract class sub-classes. Abstract classes cannot be instantiated and need to be extended to be used.

An interface is like a blueprint/contract of a class (or it may be thought of as a class with methods, but without their implementation). It contains empty methods that represent, what all of its subclasses should have in common. The subclasses provide the implementation for each of these methods. Interfaces are implemented.


What is the difference between iterator and enumeration in java?

In Enumeration we don't have remove() method and we can only read and traverse through a collection.

Iterators can be applied to any collection. In Iterator, we can read and remove items from a collection.


What are the access modifiers you know? What does each one do?

There are four access modifiers in Java language (from strictest to the most lenient):

private variables, methods, constructors or inner classes are only visible to its' containing class and its' methods. This modifier is most commonly used, for example, to allow variable access only through getters and setters or to hide underlying implementation of classes that should not be used by user and therefore maintain encapsulation. Singleton constructor is also marked private to avoid unwanted instantiation from outside.

Default (no keyword is used) this modifier can be applied to classes, variables, constructors and methods and allows access from classes and methods inside the same package.

protected can be used on variables, methods and constructors therefore allowing access only to subclasses and classes that are inside the same package as protected members' class.

public modifier is widely-used on classes, variables, constructors and methods to grant access from any class and method anywhere. It should not be used everywhere as it implies that data marked with public is not sensitive and can not be used to harm the program.


Can an Interface implement another Interface?

Yes, an interface can implement another interface (and more than one), but it needs to use extends, rather than implements keyword. And while you can not remove methods from parent interface, you can add new ones freely to your sub-interface.


What does it means to say that a String is immutable?

It means that once created, String object's char[] (its' containing value) is declared final and, therefore, it can not be changed during runtime.


What is String.intern()? When and why should it be used?

String.intern() is used to mange memory in Java code. It is used when we have duplicates value in different strings. When you call the String.intern(), then if in the String pool that string is present then the equals() method will return true and it will return that string only.


What is garbage collector? How does it work?

All objects are allocated on the heap area managed by the JVM. As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.


Android Interview Questions 2

 Describe different types of Services in Android ?

A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. It can run in the background, even when the user is not interacting with your application. These are the three different types of services:

  • Foreground Service: A foreground service performs some operation that is noticeable to the user. For example, we can use a foreground service to play an audio track.
  • Background Service: A background service performs an operation that isn’t directly noticed by the user. In Android API level 26 and above, there are restrictions to using background services and it is recommended to use WorkManager in these cases.
  • Bound Service: A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results. A bound service runs only as long as another application component is bound to it.


How can two distinct Android apps interact?

At the simplest level there are two different ways for apps to interact on Android: via Intents, passing data from one application to another; and through Services, where one application provides functionality for others to use.


What are Retained Fragments?

By default, Fragments are destroyed and recreated along with their parent Activity’s when a configuration change occurs.

Calling setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated.


What are the permission protection levels in Android?

Normal — A lower-risk permission that gives requesting applications access to isolated application-level features, with minimal risk to other applications, the system, or the user. The system automatically grants this type of permission to a requesting application at installation, without asking for the user’s explicit approval.

Dangerous — A higher-risk permission. Any dangerous permissions requested by an application may be displayed to the user and require confirmation before proceeding, or some other approach may be taken to avoid the user automatically allowing the use of such facilities.

Signature — A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user’s explicit approval.

SignatureOrSystem — A permission that the system grants only to applications that are in the Android system image or that are signed with the same certificate as the application that declared the permission.


What is a JobScheduler?

The JobScheduler API performs an operation for your application when a set of predefined conditions are met (such as when a device is plugged into a power source or connected to a Wi-Fi network). This allows your app to perform the given task while being considerate of the device's battery at the cost of timing control.

Unlike the AlarmManager class, the timing isn't exact. Compared to a custom SyncAdapter or the AlarmManager, the JobScheduler supports batch scheduling of jobs. The Android system can combine jobs so that battery consumption is reduced. JobManager makes handling uploads easier as it handles automatically the unreliability of the network. It also survives application restarts. Here are example when you would use this job scheduler:

  • Tasks that should be done once the device is connect to a power supply
  • Tasks that require network access or a Wi-Fi connection.
  • Task that are not critical or user facing
  • Tasks that should be running on a regular basis as batch where the timing is not critical



What is the ViewHolder pattern? Why should we use it?

Every time when the adapter calls getView() method, the findViewById() method is also called. This is a very intensive work for the mobile CPU and so affects the performance of the application and the battery consumption increases. ViewHolder is a design pattern which can be applied as a way around repeated use of findViewById(). A ViewHolder holds the reference to the id of the view resource and calls to the resource will not be required after you "find" them: Thus performance of the application increases.


What is the difference between Handler vs AsyncTask vs Thread?

The Handler class can be used to register to a thread and provides a simple channel to send data to this thread. A Handler allows you communicate back with the UI thread from other background thread.

The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.

And a Thread is basically the core element of multithreading which a developer can use with the 
following disadvantage:
  • Handle synchronization with the main thread if you post back results to the user interface
  • No default for canceling the thread
  • No default thread pooling
  • No default for handling configuration changes in Android


What is the difference between compileSdkVersion and targetSdkVersion?

The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.

The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.



What is the difference between a Bundle and an Intent?

A Bundle is a collection of key-value pairs.

However, an Intent is much more. It contains information about an operation that should be performed. This new operation is defined by the action it can be used for, and the data it should show/edit/add. The system uses this information for finding a suitable app component (activity/broadcast/service) for the requested action.


What is an Intent? Can it be used to provide data to a ContentProvider? Why or why not?

The Intent object is a common mechanism for starting new activity and transferring data from one activity to another. However, you cannot start a ContentProvider using an Intent.

When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application’s Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.



What is the difference between Service and IntentService? How is each used?

Service is the base class for Android services that can be extended to create any service. A class that directly extends Service runs on the main thread so it will block the UI (if there is one) and should therefore either be used only for short tasks or should make use of other threads for longer tasks.

IntentService is a subclass of Service that handles asynchronous requests (expressed as “Intents”) on demand. Clients send requests through startService(Intent) calls. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. Writing an IntentService can be quite simple; just extend the IntentService class and override the onHandleIntent(Intent intent) method where you can manage all incoming requests.



What is a broadcast receiver?

The broadcast receiver communicates with the operation system messages such as “check whether an internet connection is available,” what the battery label should be, etc.


Is it possible to create an activity in Android without a user interface ?

Yes, an activity can be created without any user interface. These activities are treated as abstract activities.


Android Interview Questions 1

What’s Android?

Android is a Linux-based, open-sourced operating system commonly found on mobile devices, such as smartphones and tablets. It’s a kernel-based system that gives developers the flexibility to design and deploy simple and/or advanced apps.


Explain the Android SDK?

This is a set of tools that Android developers use in order to develop or write apps. It features a graphical user interface that emulates a handheld, Android-driven environment, making it easier for developers to create, test, and debug their code.

The tools include:

  • Dalvik Debug Monitoring Services
  • Android Emulator
  • Android Asset Packaging Tool
  • Android Debug Bridge


What is use of AndroidManifest.xml file?

AndroidManifest.xml file is responsible to protect the application from accessing any protected parts by providing the permissions. Every app project has an AndroidManifest.xml file which is also the root of the project source set. This file contains information about your package, Android operating system, the Android build tools, Google Play, and other including components of the application such as activities, content providers, services, broadcast receivers, etc.


What is an android application architecture?

The Android architecture consists of:

  • Android Framework
  • Android Applications
  • Linux Kernel
  • Libraries


Name the basic tools for developing an Android App?

The tools used for development are:

  • JDK
  • SDK Tools
  • Eclipse+ADT Plugin

What does APK mean?

It’s short for Android Packaging Kit. Every file in the Android packaging key is compressed into a single file, the APK.


What are Activities?

These are the parts of a mobile app that a user sees and interacts with. It represents a Graphic User Interface (GUI), representing one Android screen.


State the life cycle methods of Android activities?

There are seven lifecycle methods of Android activities. They are:

  • On create()
  • On start()
  • On resume()
  • On pause()
  • On stop()
  • On restart()
  • On destroy()


What are the four essential activity states?

The four states are:

  • Active: The activity is at the top of  the stack, running in the foreground
  • Paused: The activity is still visible but cannot receive user input events; it’s in the background
  • Stopped: The activity is invisible and consequently is paused, and obscured or hidden by a different activity
  • Destroyed: The activity’s process has been killed, completed, or terminated


What is a fragment in Android?

The fragment in Android is as follows.

A fragment has its own layout and behavior with its own life cycle callbacks.

Fragments can be added or removed in an activity while the activity is running and used in multiple activities.

Multiple fragments can be combined in a single activity to build a multi-pane UI.

The fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped

Fragments were added to the Android API in the Honeycomb version of Android API version 11.


What’s a content provider?

Content providers share information between different Android applications. They allow users to access data within an application. Examples include contact information, images, video, and audio.


What’s an intent in the context of Android? Describe the different types?

Much what it sounds like, it’s the intention to perform an action, a message that is passed between components. Intents request actions from a different component, such as sending an email, opening a web page, or launch a given activity. The two types are:

  • Implicit Intent : This is where the intent doesn’t define the target component, requiring the Android system to conduct an evaluation of the components.
  • Explicit Intent : On the other hand, the explicit intent directly identifies the target component.


What’s a sticky intent?

This is a broadcast using the send sticky broadcast() method. The intent sticks around after the broadcast, which allows others to collect data from it.


What is a Pending Intent?

A Pending Intent is an action to require in the future. It allows you to pass a future Intent to a different application and permit that application to execute the Intent.


What’s a “bundle” in Android?

Bundles are used to pass the required data to sub-folders


What is ANR?

This is an acronym for Application Not Responding, a pop-up or notification that kicks in when the application is experiencing lag time for the user due to too many functions being performed simultaneously.


What's the difference between onCreate() and onStart()?

The major difference between onCreate() and onStart() is as follows.

onCreate() is called when the Activity is created; that is, it is launched or started. (Additionally, this triggers when the orientation is changed.) It is called again when the process is killed, then returned to.

while onStart() called following onCreate() at startup. Additionally, it is also called when the app is navigated back to after onStop() (and following onRestart()), which occurs after the Activity is no longer visible (which is during the time that "the user can see the activity on-screen, though it may not be in the foreground and interacting with the user").


 What is service in Android? List its types?

Services in Android are a component that acts as an application to run in the background in order to perform long-running operation tasks.

The types of Services are listed below:

  • Background Services
  • Foreground Services
  • Bound Services

Explian the use of AsyncTasks?

Android AsyncTask going to do background operation on the background thread and update on the main thread. In android, We can't directly touch the background thread to the main thread in android development. asyncTask helps us to make communication between the background thread to the main thread.


Explain different launch modes in Android?

Different launch modes are explained below:

Android Launch mode 'Standard' — Multiple instances every time, A very default launch mode!

Launch mode 'SingleTop' — Multiple instances Conditionally

Specialized Launch mode 'SingleTask' — Single instance throughout System.

Specialized Launch mode 'SingleInstance' — Single instance throughout System.


What is Proguard?

Proguard detects and removes unused classes, fields, methods, and attributes. Mobile app development companies use the Proguard in android, it optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods by using short meaningless names.


What is the difference between Serializable and Parseable?

Serializable is a standard Java interface. It is not a part of the Android SDK. Its simplicity is its biggest beauty. Just by implementing this interface the POJO will be ready to jump from one particular activity to another. There is another interface known as parseable. It is a part of the Android SDK. Paracelable was specifically designed in a way that there is no reflection left while using.


Give a brief idea about Android application architecture?

The architecture of Android application has few components, which have their functions to perform:

Service: It performs the background functions

Intent: Performs the interconnection function between activities and data passing mechanism

Resource: Externalization it is used to perform strings and graphics functions

Notification: This shows the lights, sound, icon, notification, incoming chats messages dialogue box, etc.

Content providers: It shares the data between applications.


What are few exceptions in Android?

These are the following exceptions in Android:

  • Inflate exception
  • Surface.out of resource exception
  • Surface holder bad surface type exception
  • Window manager took exception.


Explain Orientation?

Orientation is set using set orientation (), dictates whether the linear layout is represented as a row or else as a column. There the values are set as HORIZONTAL or VERTICAL.


what is the differentiate between Activities and Services?

Activities can be closed or can be terminated easily as and when the user wants to. Services are designed to run on the background or behind the scenes and can act independently. Most of the services run on a continuous basis regardless of their certain or no certain activities been executed.


What are runnable in android?

Runnable is a concurrent unit of execution in Android. It is also a class that implements a Runnable interface. The Runnable interface is used extensively to execute code in Threads.



January 31, 2022

Splash Screen in Kotlin

          On this blog I am going to explain how to show a splash screen using Handler. You can find more about Handler from Here.  On this I am going to show the redirection to new Activity page after the delay I set.  Redirection will be from SplashActivity which is my splash screen to MainActivity which is my landing page

Here I am using a delay of 4000 MS (4 Seconds)


Here I am using  postDelayed function for this,

fun postDelayed(r: Runnable!, delayMillis: Long): Boolean


Sample Code


import android.content.Intent
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import com.example.MainActivity
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)

Handler().postDelayed({

val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
        }, 4000)

}
}

Setup new Kotlin project on Android Studio

                    

On this blog I am going to explain How to setup new Kotlin project on Android Studio. To setup new project on Kotlin on Android project we need Android Studio version 3.0 or more. For older version of studio we can user Pligins. You can able to download by selecting "Install JetBrains plugin". 

Here is the steps to start new Android Project with Kotlin Support.


Goto File => New => NewProject

While select New Project you can see the Create New Project window, 
              

 You can add the project details such as Application Name, Company domain, Project Location, Package name etc. And By selecting "Include Kotlin Support" you can enable the Kotlin support on your Project.

After This Screen while tap on "Next" button it will show the screen to Select the Target Device,
              

This screen will allow you to choose the Android  Target Device you need, While tap on Next button it will show the Choose Activity Screen
              

On this screen you can select the Type of Activity we need on the Application. While Tap on Next button it will show the screen to Configure the selected Activity page.
              

On this Screen we can Add the Activity Name and the layout name. And while Tap on Finish button it will Create the New Project with your Configurations. While tap on finish button it will setup your first project. Here is the project window.



November 29, 2021

How to avoid reverse engineering of an APK file

If someone changes the .apk extension to .zip then they can unzip it and easily access all the app's resources and assets, and using dex2jar and a Java decompiler, they can also access the source code. It's very easy to reverse engineer an Android APK file - for more details see Stack Overflow question Reverse engineering from an APK file to a project.

I have used the Proguard tool provided with the Android SDK. When I reverse engineer an APK file generated using a signed keystore and Proguard, I get obfuscated code.

However, the names of Android components remain unchanged and some code, like key-values used in the app, remains unchanged. As per Proguard documentation the tool can't obfuscate components mentioned in the Manifest file.



* How can I completely prevent reverse engineering of an Android APK? Is this possible?

AFAIK, there is not any trick for complete avoidance of reverse engineering. And also Whatever you do to your code, a potential attacker is able to change it in any way she or he finds it feasible. You basically can't protect your application from being modified. And any protection you put in there can be disabled/removed.



* How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?

You can do different tricks to make hacking harder though. For example, use obfuscation (if it's Java code). This usually slows down reverse engineering significantly.



* Is there a way to make hacking more tough or even impossible? What more can I do to protect the source code in my APK file?


As everyone says, and as you probably know, there's no 100% security. But the place to start for Android, that Google has built in, is ProGuard. If you have the option of including shared libraries, you can include the needed code in C++ to verify file sizes, integration, etc. If you need to add an external native library to your APK's library folder on every build, then you can use it by the below suggestion.

Put the library in the native library path which defaults to "libs" in your project folder. If you built the native code for the 'armeabi' target then put it under libs/armeabi. If it was built with armeabi-v7a then put it under libs/armeabi-v7a.

<project>/libs/armeabi/libstuff.so

March 31, 2021

How to Commit code to Git / Bitbucket from Android Studio

                             On this blog I am going to explain how to commit the code to a git or bitbucket repository from android studio.  I already created a got repository on bitbucket, Here I will show how to commit and push the code to the repository I created on bitbucket.

I am doing this using the command on Android studio Terminal,


Step 1

First we need to initialize the git on out code, 

git init

         This command creates a new Git repository. It can be used to convert an existing, unversioned project to a Git repository or initialize a new, empty repository.


Step 2

Remove Existing git repository, 

git remote rm origin

If you want to remove the old or existing git repository you can run the above comment.

you can try this code if the above code is not working.
rm -rf .git
Here -r means "recursive", so it will delete the entire contents of the folder instead of erroring out because the folder isn't empty, and -f makes it not ask if you're really sure about deleting stuff.


Adding a remote git repository, 

git remote add origin YOUR_GIT_REPOSITORY_HTTPS_LINK

          To add a new remote, use the git remote add command on the terminal, in the directory your repository is stored at. The git remote add command takes two arguments: A remote name, for example, origin.


git remote -v

This code will help us to knew did the previous code worked correctly, Is the  fetch and push URL is applied correctly.



Switch Branch / Create New Branch 


git checkout BranchName


This comment will switch BranchName branch which is already exist in the repository.



git checkout -b NewBranchName


This code will create a new branch NewBranchName and switch to it at the same time.



git branch –show-current


This code will show you the current branch.



Step 3

Adding the files or changes to the repository, 

git add --all

         If this code is not working with you you can try the below code also, 

git add -A

         If you are in any subdirectory of the working directory, git add -A will add all files from the entire working directory, and git add . will add files from your current directory.

git add .

         If you are in any subdirectory of the working directory, git add .  will add new files and modifications, without deletions (on the current directory and its subdirectories).

git add -u

         If you are in any subdirectory of the working directory, git add -u will add stages modifications and deletions, without new files.


Step 4

Moves changes from the working directory to the local repository, 

git commit -m "YOUR_COMMIT_MESSAGE"

      This command takes the staged snapshot and commits it to the project history. My passing the Message you can Identify the changes we made on that commit.


Step 5

Upload local repository content to a remote repository, 

git push origin master --force

      This command  is used to upload local repository content to a remote repository. Pushing is how you transfer commits from your local repository to a remote repository.

--force This option overrides the “fast forward” restriction and matches our local branch to the remote branch.