Chapters

Hide chapters

Practical Android AI

First Edition · Android 13 · Kotlin 2.0 · Android Studio Otter

2. AI-Powered Developer Productivity with Android Studio & Gemini
Written by Zahidur Rahman Faisal

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Android Studio is being transformed into an AI-powered development environment, with Gemini deeply integrated to enhance developer productivity throughout the entire software development lifecycle. The sheer breadth of Gemini’s integration into Android Studio – from basic code completion to advanced crash report analysis and multi-file refactoring via Agent Mode – indicates Google’s ambition to make Android Studio the definitive AI-native development environment. It is not just adding AI features; it is embedding AI into the core fabric of the IDE. This deep integration will likely set a new standard for developer tools, pushing other IDEs and platforms to follow suit. It aims to create an unparalleled developer experience for Android, potentially attracting more developers to the platform and accelerating the pace of innovation.  

Gemini in Android Studio

Gemini in Android Studio acts as a coding companion powered by AI, understanding natural language queries related to Android development. It aims to make building high-quality Android apps faster and easier.

These are the key features that Gemini brings in for developer productivity:

  • Code Generation & Completion: Generates code snippets and provides intelligent, context-aware code completion.  
  • Code Transformation & Refactoring: Assists with transforming and refactoring existing code.  
  • Naming & Documentation: Helps with naming variables, methods, classes, and generating documenting code.  
  • UI Creation: Aids in creating Compose previews and even building app UI based on images (Image to Code).  
  • Testing & Debugging: Analyzes crash reports from App Quality Insights, provides summaries, recommends next steps, and assists in writing unit tests.  
  • Commit Messages: Helps draft descriptive commit messages.  
  • Contextual Assistance: Can offer to open relevant documentation pages and troubleshoot common errors. Developers can highlight code directly in the editor and ask Gemini questions.

Get started with Gemini

Getting help from Gemini within Android Studio is simple and straightforward! You can enable Gemini by following these steps:

Studio Labs
Fkabaa Ponj

AI-assisted coding with Gemini Chat

The Gemini Chat window is the main interface for interacting with Gemini within Android Studio. You can start using it by simply asking questions in the Ask tab about specific problems that you need help with. Open the Gemini Chat window by selecting the Gemini icon from the Android Studio side-navigation panel as follows:

Gemini Chat Window
Qixedi Mdep Dedbep

Some tips for prompting Gemini:

  • Describe the structure of the desired answer. For example: “Give me top keywords on Android AI as a Kotlin List”.
  • Be specific, if you want to use certain approaches, APIs, or libraries, mention them in your prompt.
  • Break down complex requests into a series of simpler questions. This will help generate more accurate output.

Gemini Agent Mode

Gemini, designed for Android Studio’s Agent mode, is tailored to handle complex, multi-stage development tasks beyond what’s achievable through simple conversations. By describing a high-level goal, you can guide the agent to create and execute a plan. This plan involves invoking the necessary tools, making changes across multiple files, and iteratively fixing bugs. This agent-assisted workflow empowers you to tackle intricate challenges, ultimately accelerating your development process.

Hands-off to Agent Mode

To use the Gemini Agent Mode in Android Studio, follow these steps:

Agent Mode
Opiqb Yuhu

class MainViewModel : ViewModel() {

    private val _catBreeds = MutableStateFlow<List<String>>(emptyList())
    val catBreeds: StateFlow<List<String>> = _catBreeds

    init {
        _catBreeds.value = listOf(
            "Siamese",
            "Persian",
            "Maine Coon",
            "Ragdoll",
            "Bengal",
            "Abyssinian",
            "Birman",
            "Oriental Shorthair",
            "Sphynx",
            "Devon Rex",
            "Himalayan",
            "American Shorthair"
        )
    }
}
class MainActivity : ComponentActivity() {

    private val viewModel: MainViewModel by viewModels() // Added ViewModel

    // catBreeds list is now removed from here

    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.AppTheme)
        super.onCreate(savedInstanceState)

        setContent {
            KodecoSampleTheme {
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
                    val catBreeds by viewModel.catBreeds.collectAsState()
                    val context = LocalContext.current
                    CatBreedsListScreen(
                        breeds = catBreeds,
                        onItemClick = { breed ->
                            Toast.makeText(context, breed, Toast.LENGTH_SHORT).show()
                        }
                    )
                }
            }
        }
    }
}
Agent Mode
Okafk Vulo

Transform UI with Gemini

Building that list with Gemini was easy, but you can do more! While developing your app, you may have a UI design or mockup ready, and you need to translate it into code.

UI from image
IU yheg okamo

@Composable
fun CatBreedsListScreen(breeds: List<String>, onItemClick: (String) -> Unit) {
    if (breeds.isEmpty()) {
        Text(text = "No cat breeds available.", modifier = Modifier.padding(16.dp))
        return
    }
    LazyColumn(
        modifier = Modifier.padding(vertical = 8.dp)
    ) {
        items(breeds) { breed ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 4.dp, horizontal = 8.dp)
                    .clickable { onItemClick(breed) },
                shape = RoundedCornerShape(16.dp),
            ) {
                Row(
                    modifier = Modifier
                        .padding(16.dp)
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = breed,
                        style = TextStyle(
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Normal,
                            color = Color.Black
                        )
                    )
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.ArrowForward,
                        contentDescription = "Go to details",
                        modifier = Modifier.height(16.dp)
                    )
                }
            }
        }
    }
}
Compose Preview Generation
Backiha Vcumoal Waviqasiiq

@Preview(showBackground = true)
@Composable
fun CatBreedsListScreenPreview() {
    KodecoSampleTheme {
        CatBreedsListScreen(
            breeds = listOf("Abyssinian", "Aegean", "American Bobtail"),
            onItemClick = {}
        )
    }
}
Transformed UI
Hcelfvuttob IA

Testing and Documenting using Gemini

Once your feature is ready, you can command Gemini Agent to help with testing and documentation. These are the tasks you’ll want to perform next:

Generating Unit Tests

Insert this prompt into the Gemini Agent to add the required test dependencies and generate the MainViewModelTest file:

package com.kodeco.android.aam

import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

class MainViewModelTest {

  private lateinit var viewModel: MainViewModel

  @Before
  fun setUp() {
    viewModel = MainViewModel()
  }

  @Test
  fun `catBreeds initializes with correct list of breeds`() {
    val expectedBreeds = listOf(
      "Siamese",
      "Persian",
      "Maine Coon",
      "Ragdoll",
      "Bengal",
      "Abyssinian",
      "Birman",
      "Oriental Shorthair",
      "Sphynx",
      "Devon Rex",
      "Himalayan",
      "American Shorthair"
    )
    assertEquals(expectedBreeds, viewModel.catBreeds.value)
  }

  @Test
  fun `catBreeds initial list is not empty`() {
    assert(viewModel.catBreeds.value.isNotEmpty())
  }

  @Test
  fun `catBreeds initial list size is correct`() {
    assertEquals(12, viewModel.catBreeds.value.size)
  }
}

Verify Tests
Qizodc Jebky

Adding Documentation

Gemini makes adding documentation plain and simple – you can just command Gemini where you want to add documentation and it’ll prepare the documentation using the right format.

Documentation
Jiwoqenkaraey

package com.kodeco.android.aam

import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

/**
 * Unit tests for the [MainViewModel].
 * This class contains tests to verify the functionality of the [MainViewModel],
 * specifically focusing on the initial state of the `catBreeds` LiveData.
 */
class MainViewModelTest {

  private lateinit var viewModel: MainViewModel

  /**
   * Sets up the test environment before each test.
   * Initializes a new instance of [MainViewModel].
   */
  @Before
  fun setUp() {
    viewModel = MainViewModel()
  }

  /**
   * Tests if the `catBreeds` LiveData is initialized with the correct list of cat breeds.
   * It compares the actual list of breeds from the ViewModel with an expected list.
   * This ensures that the initial data for cat breeds is loaded as expected.
   */
  @Test
  fun `catBreeds initializes with correct list of breeds`() {
    val expectedBreeds = listOf(
      "Siamese",
      "Persian",
      "Maine Coon",
      "Ragdoll",
      "Bengal",
      "Abyssinian",
      "Birman",
      "Oriental Shorthair",
      "Sphynx",
      "Devon Rex",
      "Himalayan",
      "American Shorthair"
    )
    assertEquals(expectedBreeds, viewModel.catBreeds.value)
  }

  /**
   * Tests if the initial list of `catBreeds` is not empty.
   * This is a basic sanity check to ensure that the ViewModel initializes
   * `catBreeds` with some data.
   */
  @Test
  fun `catBreeds initial list is not empty`() {
    assert(viewModel.catBreeds.value.isNotEmpty())
  }

  /**
   * Tests if the size of the initial list of `catBreeds` is correct.
   * It verifies that the number of breeds loaded initially matches the expected count.
   * In this case, it checks if there are 12 cat breeds loaded.
   */
  @Test
  fun `catBreeds initial list size is correct`() {
    assertEquals(12, viewModel.catBreeds.value.size)
  }
}

Developer Control and Safety

Gemini in Android Studio offers developers a robust set of controls and safety features to ensure privacy, responsible AI usage, and effective integration into their workflows. It includes safety controls and mechanisms for feedback, and by default, does not see code in the editor unless you opt in for higher-quality responses and experimental features.

Developer Control over Data Sharing and Context Awareness

aiexclude
eeubkcahi

Context Awareness
Fojkoqr Uwowuyarw

Safety Settings and Content Filtering

  • // Example: Block content with a MEDIUM or HIGH probability of being harassment
    val hateSpeechSafety = SafetySetting(
      HarmCategory.HARASSMENT,
      HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE
    )
    
    // Initialize the GenerativeModel with the safety settings
    val generativeModel = GenerativeModel(
      modelName = "gemini-2.5-flash",
      apiKey = BuildConfig.GEMINI_API_KEY,
      safetySettings = listOf(
          hateSpeechSafety,
          dangerousContentSafety
      )
    )
    

Developer Oversight and Iteration in AI-Assisted Workflows

Business and Enterprise-Grade Features (Gemini Code Assist)

Conclusion

Gemini in Android Studio is designed to be a powerful AI assistant that empowers developers while prioritizing their control, code privacy, and the responsible use of AI. It provides a spectrum of configurable options to balance the benefits of AI assistance with the need for security and adherence to organizational policies.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now