Question library

Android interview questions and answers

45 Android interview questions with answers: 10 junior, 15 mid-level and 20 senior. Junior answers are free to read.

Junior Mid Senior Updated How these answers are created

* View counts were reset on 18 October 2026, when Interviewplus moved to interviewplus.app. Votes were not affected.

Answer

In Android, a Service is a component that runs in the background, independently of the user interface, and performs long-running operations. It can be used for tasks such as downloading data from the internet, playing music, or syncing data with a server.

An Intent Service, on the other hand, is a specialized type of Service that can handle asynchronous requests on a separate thread. It is typically used for short-lived operations that do not require interaction with the user or synchronization with other threads. For example, an Intent Service could be used to handle a request to download a file from the internet or to send a message to a server.

One key difference between a Service and an Intent Service is that a Service runs on the same thread as the main application, while an Intent Service runs on a separate thread. This means that an Intent Service can perform background operations without blocking the main thread, which could cause the application to become unresponsive. Additionally, an Intent Service automatically stops itself once it has completed its task, while a Service must be manually stopped by the application.

Answer

1. Create a new Android Studio project and add the following dependencies to the 'build.gradle' file:

dependencies {
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-location:18.0.0'
    implementation 'com.google.android.gms:play-services-places:17.0.0'
}

2. Create a new activity layout file called 'activity_main.xml' with a search bar for entering the location and a MapView to display the map:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:queryHint="Enter location"/>
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:queryHint="Enter location"/>
    <com.google.android.gms.maps.MapView
        android:id="@+id/map_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/search_view"/>
        android:id="@+id/map_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/search_view"/>
</RelativeLayout>

3. In the 'MainActivity.java' file, add the following code to initialize the MapView and search for nearby restaurants using the Places API:

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest;
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse;
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponseListener;
import com.google.android.libraries.places.api.net.FindPlaceFromQueryRequest;
import com.google.android.libraries.places.api.net.FindPlaceFromQueryResponse;
import com.google.android.libraries.places.api.net.FindPlaceFromQueryResponseListener;


import java.io.IOException;
import java.util.Arrays;
import java.util.List;


public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        OnMapReadyCallback {

    
        OnMapReadyCallback {
    private static final int REQUEST_PERMISSION_LOCATION = 101;
    
    private static final int DEFAULT_ZOOM = 15;
    
    private GoogleMap googleMap;
    
    private MapView mapView;
    
    private FusedLocationProviderClient fusedLocationProviderClient;
    
    private GoogleApiClient googleApiClient;
    
    private Location lastKnownLocation

Answer

In Android, when a device is rotated, the system destroys and recreates the current activity by default. This means that all the objects associated with the activity, including the layout and its views, are destroyed and need to be recreated. To handle orientation changes in an Android app, you can follow these steps:

  1. Handle configuration changes: If your app has resources, such as bitmaps or network connections, that you want to preserve across configuration changes, you can override the onSaveInstanceState() method to store the state in a Bundle object, and then retrieve the state in the onCreate() method. Additionally, you can add the android:configChanges attribute to your activity declaration in the manifest file to tell the system that you will handle the orientation change manually.

  2. Rebuild the layout: When the activity is recreated, you need to rebuild the layout and restore the state of the views. You can use the savedInstanceState Bundle to retrieve the previous state of the views and restore them in the onCreate() method. Additionally, you may need to adjust the layout depending on the new orientation.

  3. Handle resources: If your app has resources that are tied to the activity's lifecycle, such as media players or location managers, you should release them in the onPause() method and re-acquire them in the onResume() method.

Here's an example of how you can handle orientation changes in an activity:

class MyActivity : AppCompatActivity() {

    private lateinit var myTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        myTextView = findViewById(R.id.my_text_view)

        if (savedInstanceState != null) {
            myTextView.text = savedInstanceState.getString("my_text")
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString("my_text", myTextView.text.toString())
    }

    override fun onPause() {
        // Release resources here, such as media players or location managers
        super.onPause()
    }

    override fun onResume() {
        // Re-acquire resources here
        super.onResume()
    }
}

In this example, the onCreate() method sets the layout and initializes the myTextView object. If the savedInstanceState Bundle is not null, the previous state of the myTextView is retrieved and restored. The onSaveInstanceState() method is used to save the state of the myTextView in case the activity is destroyed and recreated. Finally, the onPause() and onResume() methods are used to release and re-acquire resources as necessary.

Answer

In Android, a BroadcastReceiver is a component that can receive and respond to system-wide broadcast announcements, such as when the device starts up or when the battery level changes. A BroadcastReceiver can be registered either in the manifest file or programmatically, and it can be used to perform tasks in response to certain events.

Here are some examples of when you would use a BroadcastReceiver:

  1. Battery Level Changes: You can use a BroadcastReceiver to detect when the battery level changes, and perform certain actions based on the battery level. For example, you can display a warning message when the battery level is low, or disable certain features to conserve battery life.

class MyBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == Intent.ACTION_BATTERY_CHANGED) {
            val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
            val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
            val batteryLevel = (level * 100 / scale.toFloat()).toInt()

            if (batteryLevel < 20) {
                Toast.makeText(context, "Battery level is low", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

In this example, the MyBroadcastReceiver class extends the BroadcastReceiver class and overrides the onReceive() method. The onReceive() method checks if the received intent is Intent.ACTION_BATTERY_CHANGED, and retrieves the current battery level using the BatteryManager class. If the battery level is less than 20%, a warning message is displayed using a Toast.

  1. Internet Connectivity Changes: You can use a BroadcastReceiver to detect when the internet connectivity changes, and perform certain actions based on the connectivity state. For example, you can disable certain features that require internet connectivity when the device is offline.

class MyBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        val cm = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork = cm.activeNetworkInfo

        if (activeNetwork != null && activeNetwork.isConnected) {
            Toast.makeText(context, "Internet connected", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(context, "Internet disconnected", Toast.LENGTH_SHORT).show()
        }
    }
}

In this example, the MyBroadcastReceiver class extends the BroadcastReceiver class and overrides the onReceive() method. The onReceive() method retrieves the connectivity state using the ConnectivityManager class, and displays a Toast message based on the state.

Overall, a BroadcastReceiver can be used to perform tasks in response to system-wide events, and can be useful for implementing functionality that needs to respond to changes in the system state.


Answer

Both AsyncTask and HandlerThread are used for performing background tasks in Android, but they have some differences in terms of their implementation and usage.

AsyncTask is a class provided by Android that allows you to perform background operations on a separate thread and communicate the results back to the UI thread. AsyncTask has four methods: onPreExecute(), doInBackground(), onProgressUpdate(), and onPostExecute(). onPreExecute() and onPostExecute() run on the UI thread, while doInBackground() runs on a separate background thread. onProgressUpdate() is used to update the UI during the background operation.

AsyncTask is easy to use and provides a simple way to perform background operations and update the UI. However, it has some limitations, such as the fact that it is not recommended for long-running tasks, and that it can only run a limited number of background tasks at a time.

HandlerThread is a class provided by Android that provides a way to create a thread that has its own message queue. The messages in the message queue can be processed on a separate thread, and the results can be sent back to the UI thread. HandlerThread is more flexible than AsyncTask because it allows you to process messages in the background thread in any order, and to perform long-running tasks.

HandlerThread is more complex to use than AsyncTask, because it requires you to create a Handler to communicate with the background thread. However, it can be more powerful and flexible because you have more control over the processing of messages in the background thread.

Here's an example of using AsyncTask to perform a background operation:

class MyAsyncTask : AsyncTask<String, Int, String>() {

    override fun onPreExecute() {
        // Update UI before background operation
    }

    override fun doInBackground(vararg params: String?): String {
        // Perform background operation
        return ""
    }

    override fun onProgressUpdate(vararg values: Int?) {
        // Update UI during background operation
    }

    override fun onPostExecute(result: String?) {
        // Update UI after background operation is complete
    }
}


And here's an example of using HandlerThread to perform a background operation:

class MyHandlerThread : HandlerThread("MyHandlerThread") {
    
    lateinit var handler: Handler
    
    override fun onLooperPrepared() {
        handler = object : Handler(looper) {
            override fun handleMessage(msg: Message) {
                // Process message in background thread
            }
        }
    }
}

In this example, MyHandlerThread extends HandlerThread, and overrides the onLooperPrepared() method to create a Handler that processes messages on the background thread. The handleMessage() method is called when a message is received, and the message can be processed in the background thread. To use the MyHandlerThread, you can create an instance of it, and send messages to it using its handler.

Answer

To implement a RecyclerView in an Android app, you need to follow these steps:

  1. Add the RecyclerView dependency to your project's build.gradle file:

implementation 'androidx.recyclerview:recyclerview:x.x.x'

  1. Add the RecyclerView widget to your XML layout file:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/myRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

  1. Create a layout file for each item in the RecyclerView. This layout will be inflated for each item in the list:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/itemTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/itemSubtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

  1. Create a ViewHolder class that holds references to the views in each item layout:

class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val titleTextView: TextView = itemView.findViewById(R.id.itemTitle)
    val subtitleTextView: TextView = itemView.findViewById(R.id.itemSubtitle)
}

  1. Create an Adapter class that extends RecyclerView.Adapter<MyViewHolder>. This class will be responsible for binding data to the RecyclerView:

class MyAdapter(private val itemList: List<Item>) : RecyclerView.Adapter<MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
        return MyViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val currentItem = itemList[position]
        holder.titleTextView.text = currentItem.title
        holder.subtitleTextView.text = currentItem.subtitle
    }

    override fun getItemCount() = itemList.size
}

  1. Set the adapter for the RecyclerView in your activity or fragment:

val itemList = listOf(
    Item("Item 1", "Subtitle 1"),
    Item("Item 2", "Subtitle 2"),
    Item("Item 3", "Subtitle 3")
)

val recyclerView = findViewById<RecyclerView>(R.id.myRecyclerView)
recyclerView.adapter = MyAdapter(itemList)

In this example, we have a simple RecyclerView with two text views per item. The MyViewHolder class holds references to the views in each item layout. The MyAdapter class binds data to the views in each item layout, and the getItemCount() method returns the number of items in the list. Finally, in the activity or fragment, we create a list of items and set the adapter for the RecyclerView. The adapter inflates the item layout for each item in the list, and binds data to the views in each item layout.

Answer

Yes, sure. Retrofit is a popular networking library for Android that makes it easy to consume RESTful web services. Here's how you can use Retrofit to make network requests in an Android app:

  1. Add the Retrofit dependency to your project's build.gradle file:

implementation 'com.squareup.retrofit2:retrofit:x.x.x'

  1. Create an interface that defines your API endpoints. Each method in the interface should correspond to an HTTP request:

interface ApiService {

    @GET("users/{id}")
    suspend fun getUser(@Path("id") userId: Int): Response<User>

    @POST("users")
    suspend fun createUser(@Body user: User): Response<Void>

}

  1. Create a Retrofit object by calling Retrofit.Builder().baseUrl() and passing in the base URL for your API:

val retrofit = Retrofit.Builder()
    .baseUrl("https://my-api.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

  1. Create an instance of your API interface by calling retrofit.create(ApiService::class.java):

val apiService = retrofit.create(ApiService::class.java)

  1. Make a network request by calling a method on your API interface:

CoroutineScope(Dispatchers.IO).launch {
    val response = apiService.getUser(1)
    if (response.isSuccessful) {
        val user = response.body()
        Log.d("MyApp", "User: $user")
    } else {
        Log.d("MyApp", "Error: ${response.code()}")
    }
}

In this example, we define an interface called ApiService that has two methods: getUser() and createUser(). The getUser() method makes a GET request to retrieve a user by ID, and the createUser() method makes a POST request to create a new user.

We then create a Retrofit object by specifying the base URL and adding a converter factory that converts JSON responses into Kotlin objects. We create an instance of the ApiService interface by calling retrofit.create(). Finally, we make a network request by calling apiService.getUser() and handling the response in a coroutine. We check whether the response was successful by calling response.isSuccessful, and we get the user object by calling response.body(). If there was an error, we log the response code.

Answer

Sure, here's an example implementation of an Android app that allows users to take a picture with their camera and apply filters to the image:

1. First, add permissions for camera and storage access in the AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.cameraapp">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        ...
    </application>
        ...
    </application>
</manifest>
2. Next, create a layout file for the main activity (activity_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />
    <Button
        android:id="@+id/button_capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Capture"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>
        android:id="@+id/button_capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Capture"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

3. Create a new activity class (MainActivity.java) and implement the camera functionality:

public class MainActivity extends AppCompatActivity {

    
    private static final int REQUEST_IMAGE_CAPTURE = 1;

    
    private ImageView mImageView;
    
    private Button mButtonCapture;

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = findViewById(R.id.image_view);
        mButtonCapture = findViewById(R.id.button_capture);

        mButtonCapture.setOnClickListener(
        setContentView(R.layout.activity_main);
        mImageView = findViewById(R.id.image_view);
        mButtonCapture = findViewById(R.id.button_capture);
        mButtonCapture.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();
            }
        });
    }

    
                dispatchTakePictureIntent();
            }
        });
    }
    private void dispatchTakePictureIntent() {
        
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        
        super.onActivityResult(requestCode, resultCode, data);

        
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            
            Bundle extras = data.getExtras();
            
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }
    }
}
            mImageView.setImageBitmap(imageBitmap);
        }
    }
}

4. Add filter functionality to the app by creating a new class (ImageFilters.java) that contains methods for applying different image filters:

public class ImageFilters {

    
    public static Bitmap applyGrayScaleFilter(Bitmap src) {
        
        Bitmap result = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
        
        Canvas canvas = new Canvas(result);
        
        Paint paint = new Paint();
        
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(
        colorMatrix.setSaturation(0);
        
        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
        paint.setColorFilter(filter);
        canvas.drawBitmap(src, 
        paint.setColorFilter(filter);
        canvas.drawBitmap(src, 0, 0, paint);
        
        return result;
    }

    
    }
    public static Bitmap applySepiaFilter(Bitmap src) {
        
        Bitmap result = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
        
        Canvas canvas = new Canvas(result);
        
        Paint paint = new Paint();
        
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setScale(
        colorMatrix.setScale(1.0f, 0.95f, 0.82f, 1.

Answer

Sure! Here's an example of how to use SharedPreferences to store and retrieve a simple key-value pair in an Android app:

// Get a reference to the SharedPreferences object
SharedPreferences prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);

// Store a value in the SharedPreferences object
SharedPreferences.Editor editor = prefs.edit();
editor.putString("myKey", "myValue");
editor.apply();

// Retrieve a value from the SharedPreferences object
String myValue = prefs.getString("myKey", "defaultValue");

In this example, the SharedPreferences object is obtained by calling the getSharedPreferences method with a name and a mode. The name is used to identify the preferences file that will be used to store the data, and the mode determines the access level of the preferences file.

Once the SharedPreferences object is obtained, a value can be stored in the preferences file by creating an Editor object with the edit method, and using the various put methods on the Editor object to add key-value pairs to the preferences file. The changes are then applied to the preferences file by calling the apply method on the Editor object.

To retrieve a value from the preferences file, the getString method is called on the SharedPreferences object with the key and a default value. The default value is returned if the key is not found in the preferences file.

Note that SharedPreferences can be used to store values of different data types, such as boolean, float, int, long, and String. The get methods for each data type can be used to retrieve the values from the preferences file.

Answer

The onCreateOptionsMenu method in an Android Activity is used to inflate a menu resource and display it as an options menu when the user presses the "menu" button on their device or the overflow button on the action bar. The method is called only once, when the activity is created.

Here's an example of how to use onCreateOptionsMenu in an Android Activity:

public class MyActivity extends Activity {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu resource
        getMenuInflater().inflate(R.menu.my_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle menu item clicks
        switch (item.getItemId()) {
            case R.id.action_settings:
                // Open settings activity
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;
            case R.id.action_help:
                // Show help dialog
                showHelpDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

In this example, the onCreateOptionsMenu method inflates a menu resource called my_menu.xml, which defines two menu items: "Settings" and "Help". The onOptionsItemSelected method is used to handle clicks on these menu items. When the "Settings" menu item is clicked, the method starts a new activity to display the app's settings. When the "Help" menu item is clicked, the method displays a help dialog.

Note that the onCreateOptionsMenu method should return true to indicate that the menu was successfully created. If it returns false, the menu will not be displayed.

Answer preview

Both Serializable and Parcelable are interfaces in Java that allow you to serialize an object into a stream of bytes, which can then be passed between different components in an Android app, such as activities, services, and broadcast receivers. However, there are some differences between the two interfaces. The…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

To create an Android app that displays a list of items and allows users to add, delete, or edit items on the list, you will need to use the RecyclerView component and a custom adapter. Here is an example of how you can implement this: 1. Create a new project in Android Studio and add the RecyclerView dependency to…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The Handler class in Android is used to send and process messages between threads. It is often used in conjunction with the Looper class to create a message queue that allows background threads to communicate with the UI thread, which is responsible for updating the user interface. Here's an example of how to use a…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Data binding is a technique in Android development that allows developers to bind UI elements to data sources in a declarative manner, rather than having to manually update the UI with code. In order to use data binding in an Android app, you need to enable it in your project and then define a layout that uses data…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Android, both Activities and Fragments are used to create user interfaces, but they serve different purposes and have different lifecycles. An Activity is a single screen in an Android app that can contain multiple Views (e.g. buttons, text fields, images, etc.). It has its own lifecycle and manages its own…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Push notifications are a powerful way to keep users engaged with your Android app by sending them timely updates and messages. Firebase Cloud Messaging (FCM) is a popular service for implementing push notifications in Android apps, and it offers a simple and easy-to-use API. Here's an example of how to implement push…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The ViewModel class is part of the Android Architecture Components library, which provides a set of guidelines and libraries to help developers build robust and maintainable Android apps. The ViewModel class is designed to help manage UI-related data in a way that is both lifecycle-aware and separate from the UI…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here's an example program that uses the accelerometer and gyroscope sensors on an Android device to detect when the device is being shaken: To use this class in your Android app, you can create an instance of the ShakeDetector class and register it as a listener for the accelerometer sensor: This will start…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In Android, long-running tasks such as network requests or file I/O should be executed in the background to avoid blocking the UI thread and provide a better user experience. There are several ways to implement background tasks in Android, including AsyncTask, Handlers, and Threads. Here is an example of how to use…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Shared Preferences and SQLite are two ways to persist data in an Android application, but they differ in their usage and capabilities. Shared Preferences is a lightweight key-value storage mechanism in Android that can be used to store small amounts of primitive data such as strings, booleans, integers, and floats…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Retrofit is a type-safe HTTP client library for Android and Java that simplifies the process of consuming RESTful web services. It provides a high-level API that uses annotations to define the HTTP request and response mappings. Retrofit is different from other networking libraries in several ways: Type safety…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

In order to handle touch events in a custom view in Android, you need to override the onTouchEvent method of the view. This method is called whenever a touch event occurs on the view. The method takes a MotionEvent parameter, which contains information about the touch event. Here's an example of how to handle touch…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Fragments in Android are useful for building modular and flexible user interfaces. They allow you to break up your UI into small, reusable components that can be added, removed, and updated dynamically. Fragments can also be used in navigation to provide a consistent and cohesive user experience across different…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

ConstraintLayout is a layout class in Android that allows you to create complex layouts by defining constraints between view elements. These constraints define how the views are positioned relative to each other and to the parent container. The main advantage of ConstraintLayout is that it allows you to create complex…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

To create an Android app that allows users to search for and view information about movies, you could follow these general steps: 1. Use an API to retrieve information about movies, such as the OMDb API (https://www.omdbapi.com/). 2. Design a user interface for the app, which could include a search bar, movie posters…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure! Implementing a custom View in Android involves creating a new subclass of the View class and overriding its onDraw() method to draw custom graphics. Here are the steps to create a custom View: Create a new class that extends the View class: Override the onDraw() method to draw your custom graphics: Optionally…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Optimizing memory usage in an Android app is essential to ensure that the app performs well, does not crash frequently, and runs smoothly on a wide range of devices. Here are some techniques that you can use to optimize the memory usage of your Android app: Use the Android Profiler: The Android Profiler is an…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Here's an example implementation of an Android app that plays audio files and allows users to adjust the volume and playback speed. First, we need to define a layout for the app. In this case, we'll use a simple layout with a TextView to display the audio file name, two SeekBars to control the volume and playback…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The WorkManager API is a part of the Android Jetpack library, and it provides an easy way to schedule and manage background tasks in your Android application. WorkManager is designed to handle tasks that need to run in the background, even if the application is not currently running. It allows you to schedule tasks to…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

To create an Android app that allows users to create and store notes, you can follow these steps: 1. Create a new Android project in Android Studio and add a new layout file for the note taking activity. 2. In the layout file, add a text field for the user to enter the note and a button to save the note. 3. In the…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The Android Jetpack Navigation component is a part of the Android Jetpack library, which provides a framework for navigating between screens in an Android application. It allows you to define a graph of destinations (screens) and actions (transitions between screens), and it provides APIs for navigating between them…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Dagger is a popular library for dependency injection in Android apps. It allows you to define dependencies in a central location and inject them into classes that need them, reducing coupling and making your code more modular and testable. Here's an example of how to use Dagger in an Android app: Add the Dagger…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The Android Camera API allows you to access the camera hardware on an Android device to take pictures and record video. Here's an example of how to use it: Add the necessary permissions to your app's manifest file to access the camera and record audio: Create a SurfaceView in your layout to display the camera preview…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

To implement an Android app that allows users to drag and drop items to rearrange the list, we can follow these steps: 1. Create an activity with a ListView that displays the list of items. 2. Use a custom adapter to populate the ListView with the items and enable drag and drop support. 3. Implement a drag listener to…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The Room library in Android provides an abstraction layer over SQLite to allow developers to implement a local database in their apps more easily. Here's an example of how to use it to query data: Add the Room library to your app's dependencies in your app-level build.gradle file: Create an entity class that…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, the ViewModelProvider class is used to create and manage ViewModel instances in an Android app. Here's an example of how to use it: Define a ViewModel class that contains the data and logic for a particular view or UI component in your app: In this example, we define a MyViewModel class that contains a counter…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

 To support multiple languages in an Android app, you can use Android's built-in localization framework. Here's an example of how to define and apply translations: Define your app's strings in a default language (typically English) in a strings.xml file located in the res/values/ directory of your project: Create…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here's an outline of how you can create an Android app that uses the GPS sensor on an Android device to track the user's location and display it on a map: 1. Create a new Android Studio project and add the necessary permissions for accessing the device's GPS sensor and network location: 2. Add the necessary…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, the MediaCodec API in Android allows you to decode and encode audio and video data. It provides a low-level interface to the device's hardware codec, allowing for efficient processing of media data. Here's an example of how to use the MediaCodec API to decode video: In this example, we first create a new instance…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, I can explain how to use the Android Backup API to backup and restore app data. The Android Backup API provides a way to automatically backup and restore data for your app to and from the cloud. This means that if a user loses or replaces their device, they can easily restore their app data on the new device. The…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Android provides a set of Accessibility APIs that allows users with disabilities to interact with apps more easily. Some of the most common accessibility features include screen readers, magnification gestures, and color contrast adjustments. Here are some tips on how to make your app more accessible using the…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Implementing a custom launcher in an Android app involves creating a new activity that will serve as the launcher, and then registering it as the default launcher for the device. Here are the steps to implement a custom launcher: Create a new activity that will serve as the launcher. This activity should have an…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

The Android Animation API provides a set of classes and interfaces that allow you to create custom animations for your app. Here's an example of how to use the Animation API to create a complex animation: Define the layout for the animation: Define the animation: In this example, we define an AnimationSet and add…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Sure, here's an example code sample for an Android news app: 1. User Interface: The app should have a home screen with a list of articles, each containing a title, image, and brief summary. Users should be able to click on an article to read the full story. 2. API Integration: The app should use an API to retrieve the…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

Answer preview

Yes, I can explain the use of the Android NDK in an Android app. The Android NDK (Native Development Kit) allows developers to write performance-critical parts of their apps in C or C++ code, and then compile and link that code into their app's APK package as a shared library. This can be useful for tasks such as…

Sign in to view this answer

Mid and senior level answers are included in every paid plan. Sign in to choose a plan, or browse the junior level answers for free.

More practice

Go further with Android

Android code challenges

10 challenges with answers

Behavioral Questions

10 questions with answers

Cultural Fit Questions

10 questions with answers

Competency-Based Questions

10 questions with answers

Motivational Questions

10 questions with answers

Communication Skills Questions

10 questions with answers

Scenario-Based Questions

10 questions with answers

Problem-Solving and Analytical Questions

10 questions with answers

Ethical and Integrity Questions

10 questions with answers

Industry-Specific Questions

10 questions with answers

Leadership and Management Questions

10 questions with answers

Personal Questions

10 questions with answers

About this topic

Android interview questions and answers

This page lists 45 Android interview questions with answers, ordered from junior to senior level. Commonly asked questions include "What is the difference between a Service and an Intent Service?", "Create an Android app that allows users to input their location and displays a map with nearby restaurants." and "How do you handle orientation changes in an Android app?".

Other frequently asked questions include "Can you explain the difference between AsyncTask and HandlerThread in Android?", "How do you implement a RecyclerView in an Android app? Can you show an example of how to bind data to it?" and "Can you explain the differences between Serializable and Parcelable interfaces in Android? Which one would you use for performance-critical applications?". Review each answer and consider how you would adapt it to your own experience.

Practise Android in a mock interview

Answer questions one at a time and receive a score with written feedback on each answer.

Start a mock interview

Reviews and comments