Android Interview



Android Architecture
android architechture

What are Android Components? 
  •  Activities
  •  Intent and broadcast receivers
  •  Services
  •  Content Providers

What is an Application class?

  • An Application class is a base class in Android Application that starts before all other classes or components like Activities or services. In this class, you can maintain your application's global state. 

What is a Context? What are the different types of Contexts?

  • A Context is like a handle to the environment of currently running applications. It provides services like resolving resources, obtaining access to databases and preferences, and so on. We have two types of context. 
  • Application context: This context is tied to the lifecycle of an Android application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity. The scope of application context is throughout the application.
  • Activity Context: This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.

What is an Activity?

  • Activities are basically containers or windows to the user interface in which the app draws Android components. This window typically fills the screen but maybe smaller than the screen and float on top of other windows. In Android, one activity implements one screen in an app. For instance, one of an app’s activities may implement a preferences screen, while another activity implements a select photo screen.

Activity Lifecycle
OnCreate(): This is when the view is first created. This is normally where we create views, get data from bundles, etc.
OnStart(): Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
OnResume(): Called when the activity will start interacting with the user. At this point, your activity is at the top of the activity stack, with user input going to it.
OnPause(): Called as part of the activity lifecycle when an activity is going into the background but has not (yet) been killed.
OnStop(): Called when you are no longer visible to the user.
OnDestroy(): Called when the activity is finishing
OnRestart(): Called after your activity has been stopped, prior to it being started again.


What are the different launch modes available in Android?
There are four launch modes for an Activity in Android as follows:

  • standard: create a new instance of an activity every single time. It is the default mode if not declared. 
  • single top : same as standard except that if the activity is at the top of the stack, then the same instance will be used. 
  • single task : a new task will be created whenever this activity is created. Also only one instance will be available among all the tasks. 
  • single instance : the activity will be created in a new task, and that task will contain only that activity. Also only 1 instance of that activity will be available for all the tasks.




What is an Intent Filter?
  • Intent filters provide the ability to launch an activity-based not only on an explicit request but also an implicit. For example, an explicit request can tell the system to start an activity to send an email in the Gmail app and an implicit request can tell the system to start an activity to send an email screen in any activity that can do the job.  When the system UI asks a user which app to use in performing a task, that’s an intent filter at work. Here's an example of how to declare Intent Filter in Android Manifest:
    <activity android:name=".LoginActivity" android:icon="@drawable/app_icon">
      <intent-filter>
          <action android:name="android.intent.action.SEND" />
          <category android:name="android.intent.category.DEFAULT" />
          <data android:mimeType="text/plain" />
      </intent-filter>
    </activity>
    

What is the Intent?

It is a kind of message or information that is passed to the Android components. It is used to launch an activity, display a web page, send SMS, send an email, etc. There are two types of intents in Android:
  • Implicit: Implicit intent is when you call system default intent like send an email, send SMS, dial number. Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. 
  • Explicit: Explicit intent is when you call an application activity from another activity of the same application. Explicit intents specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name. You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For example, you might start a new activity within your app in response to a user action, or start a service to download a file in the background. 

What is AAPT? or Build process in Android:

AAPT (Android Asset Packaging Tool) is a build tool that Android Studio and Android Gradle Plugin use to compile and package your app’s resources. AAPT parses, indexes, and compiles the resources into a binary format that is optimized for the Android platform. Android perform the following action to build apps:
  • First, it compile the resources folder (/res) using the AAPT tool. These are compiled to a single class file called R.java. that contains constants.
  • After that, the java source code is compiled to .class files by javac, and then the class files are converted to Dalvik bytecode by the "dx" tool, which is included in the SDK 'tools'. The output is classes.dex.
  • In the final step, the android apk builder which takes all the input and build the apk (android packaging key) file.
     
What is the Handler?
  • The handler is used for communicating between the background thread and the main thread. It receives messages and writes code on how to handle the message. They run outside of the activity’s lifecycle, so they need to be cleaned up properly or else you will have thread leaks.
  • A Handler class is preferred when we need to perform a background task repeatedly after every second or minute.
  • A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

What is HandlerThread?
  • HandlerThread is a Handy class to start a thread that has a Looper.
What is a Service?
  • A service is an Android component that doesn't provide any user interface. It performs long-running operations in the background like downloading stuff, playing music, etc. It can run in the background, even when the user is not interacting with the application. By default, service runs on the main UI thread of system that might cause ANR errors. To avoid this error, we can start service by creating a new thread or use an IntentService that can do work in the background. 

    What are the different types of services?
    These are the three different types of services:

    • Foreground Service: A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track and display a notification. Foreground services continue running even when the user isn't interacting with the app. 
    • Background Service: A background service performs some actions that aren't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service. 
    • Bound Service: A service called bound service if 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, and even do so across processes with interprocess communication. A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed by the system.

    When does a Bound Service stop?

    • A Bound Service will stop automatically by the system when all the Application Components bound to it are unbinded.

    What is an Intent Service?
    • IntentService is a Service that can perform tasks using worker thread.


    How to Stop an IntentService?

    • An IntentService automatically stops itself after its job is done. We do not need to explicitly call any methods to stop an IntentService unlike Service which requires stopSelf() or StopService(intent:Intent).

    When Intent Service is Useful?

    • The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

    What is the difference between 
    • START_NOT_STICKY
    • START_STICKY 
    • START_REDELIVER_INTENT

    • START_NOT_STICKY: If the Android system kills the service after onStartCommand() returns. This flag of service does not recreate the service unless there are pending intents to deliver. We can use it to avoid long running service when not necessary and when an application can restart any unfinished jobs. 
    • START_STICKY: If the system kills the service after onStartCommand() method. This flag recreates the service and call onStartCommand(), but do not redeliver the last intent. Instead, the system calls onStartCommand() with a null intent unless there are pending intents to start the service. In that case, those intents are delivered. This is suitable for media players based applications that are not executing commands but are running indefinitely and waiting for a job. 
    • START_REDELIVER_INTENT: If the Android system kills the service after onStartCommand(). This flag recreates the service and call onStartCommand() with the last intent that was delivered to the service. Any pending intents are delivered in turn. This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file.

    What is the method that differentiates it to make Service run in the background?

    • onHandleIntent() is the method that helps the IntentService to run a particular code block declared inside it, in worker/background thread.

    Advantages of Retrofit over Volley?
    • Retrofit is type-safe. Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.

    Advantages of Volley over Retrofit?

    • Android Volley has a very elaborate and flexible cache mechanism. When a request is made through Volley, first the cache is checked for Response. If it is found, then it is fetched and parsed, else, it will hit Network to fetch the data. Retrofit does not support cache by default.

    What is the advantage of using Retrofit over AsyncTask?
    • Retrofit reduces boiler plate code by internally using the GSON library which helps to parse the JSON file automatically. Retrofit is a type-safe library. This means - it checks if the wrong data type is assigned to variables at compilation time itself. More use-cases at: https://stackoverflow.com/a/16903205/3424919


    How to handle the crashing of AsyncTask during screen rotation?

    • The best way to handle AsyncTask crash is to create a RetainFragment, i.e., a fragment without UI as shown in the gist below: https://gist.github.com/vamsitallapudi/26030c15829d7be8118e42b1fcd0fa42 We can also avoid this crash by using RxJava instead of AsyncTask as we will be subscribing and unsubscribing at onResume() and onPause() methods respectively.

    How to handle multiple network calls using Retrofit?
    • In Retrofit, we can call the operations asynchronously by using enqueue() method where as to call operations synchronously, we can use execute() method. In addition, we can use zip() operator from RxJava to perform multiple network calls using Retrofit library.

    What is the role of Presenter in MVP?

    • The Presenter is responsible to act as the middle man between View and Model. It retrieves data from the Model and returns it formatted to the View. But unlike the typical MVC, it also decides what happens when you interact with the View.

    What is the advantage of MVVM over MVP?

    • In MVP, Presenter is responsible for view data updates as well as data operations where as in MVVM, ViewModel does not hold any reference to View. It is the View's responsibility to pick the changes from ViewModel. This helps in writing more maintainable test cases since ViewModel does not depend upon View.

    When to use AsyncTask and when to use services?
    • Services are useful when you want to run code even when your application's Activity isn't open. AsyncTask is a helper class used to run some code in a separate thread and publish results in main thread. Usually AsyncTask is used for small operations and services are used for long running operations.

    What is a Looper?

    • A Looper is a class used to loop through the Message Queue attached to the Thread. By default, a thread halts when the execution completes. But, for Example, if we take Android's Main thread, it should not halt upon execution. Rather it should loop through the runnables(Messages) that its assigned in order to work properly. For more info, refer to this link.

    How to save password safely in Android?
    Using Android Keystore
    https://medium.com/@josiassena/using-the-android-keystore-system-to-store-sensitive-information-3a56175a454b

    String a = “abc”; String b = new String(“abc”); Will a == b ??
    A) It depends. Here with the first statement, i.e, String a = “abc”, JVM will search for a string with “abc” in String constant pool(SCP) and if its not there it will create a new Object. If we wrote second statement similarly, i.e., String b = “abc”, then b will point to same string from SCP. However, String b = new String(“abc”) always creates a new String object.

    What is Alarm Manager?

    • AlarmManager is a class which helps scheduling application code to run at some point of time or particular time intervals in future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

    What is Pending Intent?

    • A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code. It specifies a task that requires to be performed in future.

    What is ABI Management?
    • Different Android handsets use different CPUs, which in turn support different instruction sets. Each combination of CPU and instruction sets has its own Application Binary Interface, or ABI. The ABI defines, with great precision, how an application's machine code is supposed to interact with the system at runtime. You must specify an ABI for each CPU architecture you want your app to work with. You can checkout the full specifcations here
    Why bytecode cannot be run in Android?
    • Android uses DVM (Dalvik Virtual Machine ) rather using JVM(Java Virtual Machine).
    What is a BuildType in Gradle? And what can you use it for?
    • Build types define properties that Gradle uses when building and packaging your Android app. A build type defines how a module is built, for example whether ProGuard is run. A product flavor defines what is built, such as which resources are included in the build. Gradle creates a build variant for every possible combination of your project’s product flavors and build types.

    Explain the build process in Android:

    First step involves compiling the resources folder (/res) using the aapt (android asset packaging tool) tool. These are compiled to a single class file called R.java. This is a class that just contains constants.
    Second step involves the java source code being compiled to .class files by javac, and then the class files are converted to Dalvik bytecode by the "dx" tool, which is included in the sdk 'tools'. The output is classes.dex.
    The final step involves the android apkbuilder which takes all the input and builds the apk (android packaging key) file.

    0 comments:

    Post a Comment

    We're Social

    Categories

    Ad here

    • Cover art Blend

      Blend app is very advanced app there are lots of features like shayari, status, chat, feed....