Android Interview Questions

Here is the next best thing for Android developers: a list of commonly asked Android interview questions. Here are the top Android interview questions and their answers prepared by Android experts. These Android developer interview questions cover various topics like MVVM, ART, ConstraintLayout, fragment, activity and help you understand the different purpose of AndroidManifest.xml file. Prepare with these Android basic interview questions and live your dream career as an Android developer, iOS developer, and countless other profiles.

  • 4.6 Rating
  • 42 Question(s)
  • 60 Mins of Read
  • 7651 Reader(s)

Beginner

There is no direct way to terminate a thread but using the two following ways it can be done. 

  1. Calling ‘interrupt()’ method on the thread object (e.g. threadObj), this will throw an InterruptedException inside the run method of thread. This exception will indicate that we should release the resources gracefully and then exiting the ‘run’ method of thread will terminate the thread.
  2. In case if the InterruptedException is swallowed by the code or ignored as well as If inside the thread’s ‘run’ method if any looping is there, if yes then adding a method check in that loop that if this thread should exit now or not, is done by checking ‘Thread.currentThread().isInterrupted()’ that returns true and then exit the run method.

MVVM stands for Model-View-ViewModel. Android applications built using MVVM are more robust, fast, scalable and very less prone to memory leaks. In MVVM ViewModel is the key between View and Model.

Data flow Reference

The important key point about MVVM is that View has reference to the ViewModel but not in reverse and that makes the application’s UI-Components related memory leak-proof. Each View may have a dedicated ViewModel or may be shared by multiple in case of fragments to enable sharing data cross fragments of an activity. MVVM is a more suitable candidate for automated testing.

It stands for Android Run Time. ART is used for running Android applications. It uses AOT (Ahead Of Time) compilation on the device. When an APK is getting installed on the Android device, the .dex files from the APK file will be converted to processor’s native instructions set/machine code (.art extension) and that will be stored in the app’s runtime cache directory on the device’s internal storage. This will make installation little bit longer and take more space on the device storage but it makes apps run much faster, less battery consumption, robots application debugging support and better user experience.

The recommended way going forward is using WorkManager APIs, that makes it easy to specify deferrable, asynchronous tasks and when they should run under the circumstances you choose, or recurring tasks that run at a specified interval. Internally WorkManager might use JobScheduler, Firebase-JobDispatcher, Executor, and AlarmManager for running the task.

Android is a ‘Linux based software stack’ created for a wide array of devices and form factors. It is open source. It has layers of major components from bottom to top as follows…

  1. The Linux Kernel: It is the foundation of the Android platform
  2. Hardware Abstraction Layer (HAL): It provides standard interfaces that expose device hardware capabilities to the higher-level Java API framework. Vendors/OEMs must explicitly extend the HAL, due to this no need to open source the vendor-specific source code.
  3. Android Runtime (ART) & Native C/C++ Libraries: ART uses Ahead-of-time (AOT) and just-in-time (JIT) compilation to run the android application and Optimized garbage collection (GC) to reclaim memory. It provides better debugging support.
  4. Java API Framework: The entire feature-set of the Android OS is available through APIs implemented using Java language. These APIs form the building blocks to create Android apps by simplifying the reuse of core, modular system components, and services, which include e.g. View System, Resource manager, Notification manager, Activity manager, Content Provider
  5. System Apps: Pre-installed a set of core apps for email, SMS messaging, calendars, internet browsing, contacts, and other apps.

It is the foundation for any Android application. It will be in app module’s src/main/ directory for Android Studio projects. This file contains information of application package, including components of the application such as activities, services, broadcast receivers, content providers etc. It performs some other tasks also: It is responsible to protect the application to access any protected parts by provision of permissions.

  1. A layout defines the structure for a user interface in an android app, such as in an activity.
  2. All elements in the layout are built using a hierarchy of View and ViewGroup objects.
  3. A View is visible and interact-able whereas a ViewGroup is an invisible container that defines the layout structure for View and other ViewGroup objects under it.
  1. A Fragment represents a behavior or a portion of user interface.
  2. A fragment must always be hosted in an activity and the fragment's lifecycle is directly affected by the host activity's life-cycle.
  3. When a fragment is added as a part of activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout.
  1. A Service is an application component that can perform long-running operations in the background; it can run in a new process itself or as a part of your application’s process.
  2. It doesn't provide a user interface, but various APIs to interact with it.
  3. Another application component can start a service, and it continues to run in the background even if the user switches to another application.
  4. A component can bind to a service to interact with it and even perform interprocess communication (IPC)

Intermediate

In Android, UI is representing as an Activity. Single Screen in an application represents as Activity while Fragments are reusable UI with business logic. Activity is a collection of Screen. In android application, Fragments are using in Navigation Drawer in our entire screen. You can also use fragment to display Google Map on screen.

Following are important points about a fragment:

  •         The fragment life cycle is closely related to the lifecycle of its host activity.
  •         A fragment can implement a behaviour that has no user interface component.
  •         A fragment has its own layout and its own behaviour with its own lifecycle callbacks.
  •         You can add or remove fragments in an activity while the activity is running.
  •         You can combine multiple fragments in a single activity to build a multi-pane UI.
  •         A fragment can be used in multiple activities.
  •         When the activity is paused, all the fragments available in the activity will also be stopped.

Android OS provides back stack function for Activity, it also provides back stack function for Fragment. If you add one Fragment into the back stack, when you press the android device back menu, you can find the Fragment that is saved in back stack popup. Until all saved Fragments in back stack popup, then the activity will exit.

We have to create  “FragmentTransaction objects on the back stack and when the user presses the Back button, the “FragmentManager pops the most recent transaction off the back stack and performs the reverse action.

As mentioned in below code:

getSupportFragmentManager().beginTransaction()
                          .add(detailFragment, "detail")
                          // Add this transaction to the back stack
                          .addToBackStack(null)
                          .commit();

In Android when we want to share data between two applications we are using Content Provider. It has a complete mechanism to share data between applications. It will also provide security while sharing data from one application to another application. For getting data from any Content Provider you need to create Content Resolver. For Creating Content Resolver, you need to call Activity’s getContentResolver method.

For Modifying data from Content Provider, you can invoke the basic method of Content Resolver like insert, delete, update and query. These operations are the same as the SQLite DB Operation.

Android we have two steps for retrieving data from a Content Provider:

  • Write-read permission for reading data from Content Provider
  • Write a query to send a request to the content provider.

For this, we can modify our build Gradle file of the application. In Gradle file we will add code for adding build type and build flavour like below:

buildTypes {
   debug {
       applicationIdSuffix '.debug'
       versionNameSuffix '-DEBUG'
       resValue "string", "app_name", "AppName debug"
   }
   release {
       minifyEnabled true
       shrinkResources true
       proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       signingConfig signingConfigs.release
       zipAlignEnabled true
       resValue "string", "app_name", "AppName"
   }
}

When you need to send Object from one activity to another activity, we are using two techniques: 1. Serialization and 2. Parcelable. In other case passing data from one activity to another activity, we are using Intent. Parcelable is a faster approach compared to Serialization because it is using Android SDK.

There are some reasons also:

  • Serialization is a marker interface as it converts an object into a stream using the Java reflection API. Due to this, it ends up creating a number of garbage objects during the stream conversation process.
  • Parcelable is in the Android SDK; serialization, on the other hand, is available in Java. So Android developers prefer Parcelable over the Serialization technique.

Launch mode is an instruction for Android OS which specifies how the activity should be launched. It instructs how any new activity should be associated with the current task.

So in your scenario When using launchMode="singleInstance", there are two things that we need to remember:

  • The Activity will always be created in a new task
  • All Activities launched from this Activity will be created in a separate task

As such, an Activity with launchMode of singleInstance will always be isolated in its own task. There won't be another Activity inside of that task.

So with your example from your question of Activities A, B, C, and D:

  • Activity A launches Activity B
  • Activity B is launchMode="singleInstance" so it's on a new task
  • Activity B launches Activity C
  • Activity C is launched in the same task as Activity A
  • Activity C launches Activity D
  • Activity D is launchMode="singleInstance" so it's on a new task

From what happened here, you have one a task that stores the launchMode="standard" Activity A and Activity C. Activity B is in its own task. Activity D is in its own task.

Therefore, if you choose to Back out of these Activities, you'll notice that:

  • Activity D is backed and Activity C appears
  • Activity C is backed and Activity A appears
  • This happens because Activity C is on the same task as Activity A.

Also, Activity D definitely won't be in the same task as Activity B because Activity B's task is meant only for Activity B due to launchMode="singleInstance".

There are many differences between IntentService and Bound Service:

  • Intent Service is performing the task in background and after finishing the task, the instance of IntentService will be killed itself.
  • Bound Service is running in Main Thread, while IntentService creates a worker thread and uses that thread to run the service.
  • IntentService is using Handler to handle Message. While Service class needs a manual stop using stopSelf().
  • IntentService implements onBind() that returns null. This means that the IntentService cannot be bound by default.
  • IntentService implements onStartCommand() that sends
  • Intent to queue and to onHandleIntent().

In Android Service is something that is running in the background. In a simple way, we can say that a background service is same as an Activity. The only difference is it doesn’t have UI. A background Service can be started by calling the startService method in your Activity. we need to create an explicit Intent, which means that you either make a reference to the Service’s class, or you include the package name of your app in the Intent. For example:

Intent intent = new Intent(mContext, MyService.class);
startService(intent);

There is one drawback with Service is that it is running on Main Thread so you can not assign any long running operation to service.  But if you want to run some long running operation in the background, you should use IntentService.

IntentService is creating its own Worker Thread which is running separately from the Main Thread. Examples for its usage would be to download certain resources from the Internet. For creating Intent Service you need to create a service class by extending IntentService and implementing onHandleIntent() method.

public class TestIntentService extends IntentService{
    @Override
    protected void onHandleIntent(Intent intent) {
            }

In Intent Service we can start service by calling startService method passing intent which identifies the service. We can call startService any number of times, but in the background it will create only one instance of intent service and all requests are queued and processed in separate work thread. We don’t need to worry about calling stopService, as IntentService stops itself when there are no requests to serve.

In Android Sticky Intent is a type of Intent who will communicate between Service and Function. Sticky Intent is using with Sticky Broadcast that’s why they are calling as StickyIntent. In simple language, we can say that StickyIntent is stick with till Broadcast is not completed its job this intent will be present and return data of registerReceiver() method and will be re-delivered or re-broadcasted to the future requests from any broadcast receivers.  We have one more advantage of Sticky Intent that Sticky Broadcast will replace the previous instance of the sticky broadcast and save your application from memory leak.

For example, if we need to send a notification for Low status of Battery, we will

create a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. As soon broadcast that action we will get the Intent with data. For this first, we need to add special permission in the manifest file that allows an application to broadcast sticky intents.

<uses-permission android:name="android.permission.BROADCAST_STICKY"/>

Here's an example of how we can use a sticky broadcast for :

Intent intent = new Intent("action. ACTION_BATTERY_CHANGED");
intent.putExtra("status ", true);
sendStickyBroadcast(intent);

View is a basic building block of UI (User Interface) in android. A view is a small rectangular box which responds to user inputs. For example, a Text View is used to display some text to the user that is a subclass of View. In Android, we are using many View subclass like EditText, Button, CheckBox, Radio Button, ImageView, DatePicker etc.

ViewGroup is an invisible container of other child view. ViewGroup is a special kind of view which is extended from View as its base class. ViewGroup is the base class for layouts. Viewgroups can contain other views in it. For example LinearLayout, it is a group of many views those are arranging in Linear or Veridical way.  In Android, we have other layouts as well like Relative Layout, Table Layout, Frame Layout etc.

The Recycler view is the most advanced component of Android.  We can also say that RecyclerView is the most advanced form of ListView. Recycler view is containing new feature like ViewModel,  Adapter, LayoutManager, SoothScroller. There are many differences many difference between listview and RecyclerView.

In ListView we cannot do horizontal scrolling while in RecyclerView we have both option Horizontal and Vertical Scrolling.

In  RecyclerView class, it is using a ViewHolder object which is used by the adapter to bind ViewHolder with a position while in ListView we are not using ViewHolder.

In  ListView, if the data set is changed you have to call the notifyDataSetChanged method of the underlying adapter to refresh data. While in a RecyclerView adapter, if a single item or a range of items have changed, there are methods to notify the change accordingly like notifyItemChanged and notifyItemRangeChanged.

Having rotated the device, the following state change sequence should appear Clearly this has resulted in the activity being destroyed and re-created. To save the state information override onSaveInstanceState() method and add key-value pairs to the Bundle object. It will save data in the event that your activity is destroyed unexpectedly. This method gets called before onStop(). To get saved from an activity state, we are using method onRestoreInstanceState.

The first step in extending the StateChange application is to make sure that the text entered by the user is extracted from the EditText component within the onSaveInstanceState() method of the StateChangeActivity activity and then saved as a key-value pair into the Bundle object.

Alternately, use the onRestoreInstanceState( ) method to extract saved state from the Bundle and restore it into new instances of the activity.  The onRestoreInstanceState( ) method is another callback lifecycle method that is also rarely seen in the activity lifecycle diagrams. The onRestoreInstanceState( ) method is automatically invoked by Android between the onStart( ) and the onResume( ) lifecycle methods.

You can do it by setting an OnKeyListener on your EditText.  This is only useful

for hardware keyboards. A software input method has no obligation to trigger

this listener. Please find below code for more clarification:

Here I am overriding onKey Method which will return a false value if press key is not “Enter” Else it will clear text of Edit text as empty.

@Override
public boolean onKey(View v,
int keyCode, KeyEvent event) {
   if (keyCode == 66) {
       editText.setText("");
   }
   return false;
}

For creating AsyncTask with a specific interval, we can use a Handler. A Handler is a safe option because we don't need an extra thread to keep tracking when firing the event.

When we launch any android application it will create a thread which called the Main thread, this thread is handling all the UI event handling so it is also called as UI Thread. A Handler is also a Thread which is running on Main Thread. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. A Handler can be used to schedule messages or runnable to executed at some point in the future. You can send a message using Handler

// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
   @Override
   public void run() {
     // Do something here on the main thread
     Log.d("Handlers", "Called on main thread");
   }
};
// Run the above code block on the main thread after 2 seconds
handler.postDelayed(runnableCode, 2000);

In Android, we have many ways to store user data. SharedPreference is a class that allows us to save and retrieve user data in the form of Key and Values. If you kill your application still data will be saved in the shared preference.  It will store data in an XML file. For using shared preference we need to create an instance of the getSharedPreferences method. This method is taking two parameters:

  1. Name of the preference and
  1. Mode to control permissions.

For writing data in the sharedpreferences file we need to follow below steps:

  • Call edit() to get a SharedPreferences.Editor
  • Add values with methods such as putInt() and putString
  • Call commit() to save values.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "ABC");
editor.commit();

To read values use such methods as getString() and getInt() of SharedPreferences instance.

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
 String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
 }

Advanced

The first method is called 'onCreate()', which fires when the system first creates the activity. On activity creation, the activity enters the Created state.

The last method is guaranteed called ‘onPause()’. The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed), but you should save you work/variables/state here. Other methods e.g. onStop, onDestroy may be called or not depends on the system.

Explicit intents: 

They specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name.For example, 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. 

Implicit intents: 

They 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.

Using 'stopService()' that a given application service will be stopped. If the service is not running, nothing happens. Otherwise, it is stopped. Note that calls to startService() are not counted -- this stops the service no matter how many times it was started.
Using 'stopSelf()' is same as 'stopService()' but used within the service to indicate system to stop itself.

The main difference between FragmentPagerAdapter and FragmentStatePagerAdapter is FragmentPagerAdapter stores the whole fragment in memory, and If we used a large amount of Fragment in ViewPager it will increase memory while FragmentStatePagerAdapter only stores the savedInstanceState of fragments, and destroys all the fragments when they lose focus.

FragmentPagerAdapter stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter takes the new value from the adapter every time it is executed. Let's take an example of  Book Reader application here. I will use FragmentStatePagerAdapter and if I am creating an application which will store heavy data, then I will use FragmentPagerAdapter.

Fused location provider tries to get the best possible location which is certainly the location data from GPS. If you want location from your mobile network put the following permission in your manifest.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

The fused location provider is one of the location APIs in Google Play services. It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power. It also optimizes the device's use of battery power.

I would advise MVVM, it is the pattern of the future. And it is the only architecture that can give you full testing without dependencies. Once you get your head around the data-binding concept, it is super easy.  In MVVM we are using Android Architecture Components. There LiveData and ViewModel are the main components which will help in resolving the view dependency.

LiveData is an observable data holder class which is Lifecycle state of the Activity or Fragment. And ViewModel is like the state representation of UI which stores and manages UI-related data in a lifecycle conscious way.  It will also save data when screen orientation changed.

MVP is tight coupling, so there are many things that are difficult to test.

When you need to execute some background work fast and need a guarantee of that execution, create WorkerManager. Work manager APIs go beyond the only current state of the task and allows tasks to return data in key-value format. We are using LiveData to return data and state of Work. By using WorkManager, our activity can observe livedata and it will get notified whenever the task is finished.

For creating WorkManager, we need to create one subclass of the Worker class. This class has one abstract method called doWork(). As the name suggests, you need to perform the work you want to do in the background. This method will be called in the background/worker thread. Write a program to perform the task in this method.

In return, you have to return WorkerResult. Returning WorkerResult.SUCCESS indicates that the task you performed completed successfully. Returning WorkerResult.RETRY tells WorkManager to retry the work again. Returning WorkerResult.FAILURE indicates one or more errors occurred.

We can use  WorkManager for:

  • Uploading logs
  • Applying filters to images and saving the image
  • Periodically syncing local data with the network

By using LiveData, we can Observe activity lifecycle method, so livedata will not trigger the change method if view is destroyed. There are many advantages of LiveData

  • Since livedata is present inside View Model it's retained on configuration change
  • Activity View is observing to live data
  • There is no memory leak as View Model doesn’t have any reference of activity
  • Observers have their own lifecycle so they are automatically cleaned when their Lifecycle is destroyed
  • When your activity goes into any state other than STARTED or RESUMED it will not call the onChanged method on the observer.
  • ViewModel exposes livedata that view observes it. Whenever livedata changes view gets notified and it could re-render itself.

Notification Channels. Notification Channels allow us to separate notifications into different groups/categories. Basically, Notification Channel is designed for User. They can get full control of what they want to be notified about. If they don’t want any notification they can specifically turn off notifications for a certain channel. They can also specify importance as well as the preferred sound for a particular category of notifications and determine whether or not to override Do not disturb

The NotificationChannel constructor requires us to specify the channel_id and channel_name strings. The Importance argument is an int which specifies the level of interruption by the notification.

val  MessagesChannel = NotificationChannel(
                   MESSAGES_CHANNEL_ID,
                   context.getString(R.string_channel_name),
                   NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(privateMessagesChannel)

A toast can be displayed on the screen is defined by a flag as Duration. We can set duration Short or Long. The value for Short is 2.0 second and value for Long is 3.5 Second.

Context context = getApplicationContext();
Toast.makeText(context, "Testing Toast Message.", Toast.LENGTH_SHORT).show();

You can not directly change the duration of Toast Message which is showing in the show() method. But there is a workaround. You can use CountDownTimer Class or Handler Class to increase display time of Toast.

  • Schedule a countdown until a time in the future, with regular notifications on intervals along the way.
  • you need to create a new Window manager and show and hide the window for the desired duration using a handler

For sharing data from one application to another application we are using Content Provider in android.  Other application can access data from Content Provider using the provider client object. These provider client object providing an interface between application to access data and handle inter-process communication. Content Provider is saving data in the form of Tables. These tables are having the same schema as relational database tables.

To access the data from the content provider, we use the ContentResolver client object. ContentResolver provides basic methods related to database storage. ContentResolver object and Content Provider objects are handling interprocess communication between application. The ContentResolver methods provide the basic create, retrieve, update, and delete functions of persistent storage.

To retrieve data from a content provider, we need to follow these steps:

  • Send Request the read access permission for the provider.
  • Write the code that sends a query to the provider

For protecting the privacy of an Android user we are using Permission concept in android. When the application is trying to access user data like contact, Gallery they requesting permission. Depending on the feature, the system might grant the permission automatically or might prompt the user to approve the request

UsesPermission: Specifies system permission that the user must grant in order for the app to operate correctly. Permissions are granted by the user when the application is installed.

<uses-permission android:name="string"
       android:maxSdkVersion="integer" />

Permission: To enforce your own permissions, you must first declare them in your AndroidManifest.xml using one or more <permission> tags..Declares a security permission that can be used to limit access to specific components or features of this or other applications.

<permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"
       android:label="@string/permlab_deadlyActivity"
       android:description="@string/permdesc_deadlyActivity"
       android:permissionGroup="android.permission-group.COST_MONEY"
       android:protectionLevel="dangerous" />

An Intent object carries information that the Android system uses to determine which component to start. The Intent object contains information which is used either from the components that receive that intent or the Android system itself.

We are defining the Intent Filter in Manifest File. We can set the type of intents to accept perform some action using these elements:

  •         <action>:  Action defines the name of an intent action to be accepted and it must be a literal string value of an action, not the class constant. For example: Check BatteryLow, Boot
  •         <category>: Category defines the name of an intent category to be accepted and the same action which is a literal string value, not the class constant.
  •         <data>: Data defines the type of data to be accepted and by using one or more attributes we can specify various aspects of the data URI (scheme, host, port, path) and MIME type.
<intent-filter>
      <action android:name="android.intent.action.SEND" />
      <category android:name="android.intent.category.DEFAULT" />
      <data android:mimeType="text/plain" />
    </intent-filter>

For checking the status of BatteryLow and sending information to the user,  we can create a BroadCast Receiver who will send a triggers battery Low notification that you see on your mobile screen.

A Broadcast Receiver is an Android component which allows you to register for system or application events. Once Event occur it will Broadcast message to the user.

There are two steps to create a Broadcast Receiver:

  • Create a subclass of Android’s BroadcastReceiver.
  • Implement the onReceive() method: in our case ,for generate  battery low notification, the receiver is registered to Intent.ACTION_BATTERY_LOW event. As soon as the battery level falls below the defined level, this onReceive() method is called.
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
        <action android:name=" android.intent.action.BATTERY_LOW "/>
    </intent-filter>
</receiver>
  • At last, we will call our Broadcast Receiver using Implicit Intent.
Intent intent = new Intent(this, Reciver.class);
sendBroadcast(intent);

findViewById is a method that finds the view from the layout resource file that is attached to the current Activity. This method refers to a view with requested viewId.   is already created and exists. If you do not call findViewById for some view, then nothing changes.

Button button1 = (Button) findViewById(R.id.button1);
   TextView topLeft = (TextView) findViewById(R.id.textView2);

There is a disadvantage of findViewById() returns a View if it exists in the layout you provided in setContentView(), otherwise it returns null at  runtime. There is no compile time check for this method.

DataBinding: Android Data Binding creates a link between the Presentation layer or UI layer and the Business layer or data model that holds the information to display. Android Data Binding library reduce extra code for app logic with its UI view. It also removes the need for methods like  “findViewById” and “setText.” 

Android data binding generates binding classes at compile time for layouts.

<data>
       <variable
           name="user"
           type="com.example.databindingsample.User" />
   </data>

We have to add data<> tag before the UI view root within the layout tag. It will bind Object . data<> element can have multiple variable<> tag within it. Those are using to describe a property that can be used within the layout.

If you want to send data from fragment to another Fragment we need to use an interface. Intents are only usable for sending data on an Activity level. To pass data between fragments we need to create our own interfaces.

Fragment 1 -> MainActivity -> FragmentInterFace-> Fragment 2

In onAttach() lifecycle method , the fragment implement the Interface logic and it will call Interface methods to communicate with an activity.

@Override
   public void onAttach(Context context) {
       super.onAttach(context);
       if (context instanceof OnFragmentInteractionListener) {
           mListener = (OnFragmentInteractionListener) context;
       } else {
           throw new RuntimeException(context.toString()
                   + " must implement OnFragmentInteractionListener");
       }
   }

The activity that hosts fragment must implement the interface For receiving callback events from Fragment class. First host activity creates an instance of fragment using findFragmentById method then it can deliver a message to fragment directly by calling the fragment's public methods.

In, we can send information from one activity to another and vice-versa using startActivityForResult() method. The android startActivityForResult method requires a result from the second activity. For that, we need to override the onActivityResult method that is invoked automatically when the second activity returns a result.

public void startActivityForResult (Intent intent, int requestCode)

Now we will see how to send data from Activity B back to Activity A?

  • In Activity A we will call explicit Intent in Next Button click, this will call Intent and it will call ActivityB.
intentActivityD = new Intent(…);
   intentActivityD;
   startActivityForResult(intentActivityD, SOME_REQUEST_CODE)

In Activity B we will send someResultCode to Activity  A, which will handle it with the onActivityResult and send it back again with setResult(…) finish();

goBackToActivityA(){
   setResult(someResultCode);
   finish();
}
  • Once it received result from Activity B it will call method onActivityResult. Which will then know by the flag that the activity B no longer exists, hence the activity that should handle it is Activity A, which means the resultCode will finally arrive in the onActivityResultCode of Activity A.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
       // check if the requestCode is the wanted one and if the result is what we are expecting
       if (requestCode == REQUEST_FORM && resultCode == RESULT_OK) {
           val name = data?.getStringExtra(FormActivity.INPUT_NAME)
           addItemToList(name) // do something with the value
       }
   }

In Android, service is a component which is like activity and running in the background. Once it is started, it will run in the background even if the application goes background. But from Android O, they introduce a new concept that a user should know what task is running in the background and it also should show the notification to user with some action buttons so that the user can interact with the ongoing operation if they want. So for this, we have the best approach called as an Android Foreground Service. This foreground service is giving notification to the user that task is running in the background, for example, playing music or downloading files from the internet. And if the user wants to stop that service, then he can stop using Notification.

So to create foreground service you have to use NotificationManager.startServiceInForeground() method to send a notification to the user that the Background Service is running and if he wants he can stop it.

Description

Android is a software package and Linux based OS for mobile devices such as computers, tablets, and smartphones. Is developed by Google and later the OHA (Open Handset Alliance). The goal of the Android project is to create a successful real-world product that improves the mobile experience for end users. For today there are many codes names of Android such a Lollipop, KitKat, Jelly Bean, etc.

Today Android become the indisputable leader of the global smartphone market share. This is mainly due to an increase in the use of smartphones in Countries like India, USA, Brazil, China and many more. One of the important features of Android is the integration of Google products and services.

It’s the best time for you to launch a career in Android development. There’s a healthy supply of jobs, demand for Android apps. The expansion is increasing the demand for mobile application developers, currently, have lots of opportunities for employment. 2018 has been a game the dynamic year for the smartphone market.

So, if you are planning to start your career in Android development then you need to be well prepared with all the possible Android interview questions which could be asked in an Android interview. There are several complicated Android developer interview questions you might come across in the Android interview. This article will equip you to deal with Android interview questions asked in Android developer interviews.

Read More
Levels