File: README.md
Bitwarden Android
Contents
Compatibility
- Minimum SDK: 29 (Android 10)
- Target SDK: 37 (Android 17)
- Device Types Supported: Phone and Tablet
- Orientations Supported: Portrait and Landscape
Setup
Clone the repository:
sh$ git clone https://github.com/bitwarden/androidCreate a
user.propertiesfile in the root directory of the project and add the following properties:gitHubToken: A "classic" Github Personal Access Token (PAT) with theread:packagesscope (ex:gitHubToken=gph_xx...xx). These can be generated by going to the Github tokens page. See the Github Packages user documentation concerning authentication for more details.localSdk: A boolean value to determine if the SDK should be loaded from the local maven artifactory (ex:localSdk=true). This is particularly useful when developing new SDK capabilities. Review Linking SDK to clients for more details.
Setup the code style formatter:
All code must follow the guidelines described in the Code Style Guidelines document. To aid in adhering to these rules, all contributors should apply
docs/bitwarden-style.xmlas their code style scheme. In IntelliJ / Android Studio:- Navigate to
Preferences > Editor > Code Style. - Hit the
Managebutton next toScheme. - Select
Import. - Find the
bitwarden-style.xmlfile in the project'sdocs/directory. - Import "from"
BitwardenStyle"to"BitwardenStyle. - Hit
ApplyandOKto save the changes and exit Preferences.
Note that in some cases you may need to restart Android Studio for the changes to take effect.
All code should be formatted before submitting a pull request. This can be done manually but it can also be helpful to create a macro with a custom keyboard binding to auto-format when saving. In Android Studio on OS X:
- Select
Edit > Macros > Start Macro Recording - Select
Code > Optimize Imports - Select
Code > Reformat Code - Select
File > Save All - Select
Edit > Macros > Stop Macro Recording
This can then be mapped to a set of keys by navigating to
Android Studio > Preferencesand editing the macro underKeymap(ex : shift + command + s).Please avoid mixing formatting and logical changes in the same commit/PR. When possible, fix any large formatting issues in a separate PR before opening one to make logical changes to the same code. This helps others focus on the meaningful code changes when reviewing the code.
- Navigate to
Setup JDK
Version21:- Navigate to
Preferences > Build, Execution, Deployment > Build Tools > Gradle. - Hit the selected Gradle JDK next to
Gradle JDK:. - Select a
21.xversion or hitDownload JDK...if not present. - Select
Version21. - Select your preferred
Vendor. - Hit
Download. - Hit
Apply.
- Navigate to
Setup
detektpre-commit hook (optional):
Run the following script from the root of the repository to install the hook. This will overwrite any existing pre-commit hook if present.
echo "Writing detekt pre-commit hook..."
cat << 'EOL' > .git/hooks/pre-commit
#!/usr/bin/env bash
echo "Running detekt check..."
OUTPUT="/tmp/detekt-$(date +%s)"
./gradlew -Pprecommit=true detekt > $OUTPUT
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
cat $OUTPUT
rm $OUTPUT
echo "***********************************************"
echo " detekt failed "
echo " Please fix the above issues before committing "
echo "***********************************************"
exit $EXIT_CODE
fi
rm $OUTPUT
EOL
echo "detekt pre-commit hook written to .git/hooks/pre-commit"
echo "Making the hook executable"
chmod +x .git/hooks/pre-commit
echo "detekt pre-commit hook installed successfully to .git/hooks/pre-commit"Dependencies
Application Dependencies
The following is a list of all third-party dependencies included as part of the application beyond the standard Android SDK.
AndroidX Activity
- https://developer.android.com/jetpack/androidx/releases/activity
- Purpose: Allows access composable APIs built on top of Activity.
- License: Apache 2.0
AndroidX Appcompat
- https://developer.android.com/jetpack/androidx/releases/appcompat
- Purpose: Allows access to new APIs on older API versions.
- License: Apache 2.0
AndroidX Autofill
- https://developer.android.com/jetpack/androidx/releases/autofill
- Purpose: Allows access to tools for building inline autofill UI.
- License: Apache 2.0
AndroidX Biometrics
- https://developer.android.com/jetpack/androidx/releases/biometric
- Purpose: Authenticate with biometrics or device credentials.
- License: Apache 2.0
AndroidX Browser
- https://developer.android.com/jetpack/androidx/releases/browser
- Purpose: Displays webpages with the user's default browser.
- License: Apache 2.0
AndroidX Camera
- https://developer.android.com/jetpack/androidx/releases/camera
- Purpose: Display and capture images for barcode scanning.
- License: Apache 2.0
AndroidX Compose
- https://developer.android.com/jetpack/androidx/releases/compose
- Purpose: A Kotlin-based declarative UI framework.
- License: Apache 2.0
AndroidX Core
- https://developer.android.com/jetpack/androidx/releases/core
- Purpose: Backwards compatible platform features and APIs.
- License: Apache 2.0
AndroidX Credentials
- https://developer.android.com/jetpack/androidx/releases/credentials
- Purpose: Unified access to user's credentials.
- License: Apache 2.0
AndroidX Lifecycle
- https://developer.android.com/jetpack/androidx/releases/lifecycle
- Purpose: Lifecycle aware components and tooling.
- License: Apache 2.0
AndroidX Navigation
- https://developer.android.com/jetpack/androidx/releases/navigation
- Purpose: Provides a consistent API for navigating between Android components.
- License: Apache 2.0
AndroidX Room
- https://developer.android.com/jetpack/androidx/releases/room
- Purpose: A convenient SQLite-based persistence layer for Android.
- License: Apache 2.0
AndroidX Security
- https://developer.android.com/jetpack/androidx/releases/security
- Purpose: Safely manage keys and encrypt files and sharedpreferences.
- License: Apache 2.0
AndroidX WorkManager
- https://developer.android.com/jetpack/androidx/releases/work
- Purpose: The WorkManager is used to schedule deferrable, asynchronous tasks that must be run reliably.
- License: Apache 2.0
Dagger Hilt
- https://github.com/google/dagger
- Purpose: Dependency injection framework.
- License: Apache 2.0
Glide
- https://github.com/bumptech/glide
- Purpose: Image loading and caching.
- License: BSD, part MIT and Apache 2.0
kotlinx.collections.immutable
- https://github.com/Kotlin/kotlinx.collections.immutable
- Purpose: Immutable collection interfaces and implementation prototypes for Kotlin.
- License: Apache 2.0
kotlinx.coroutines
- https://github.com/Kotlin/kotlinx.coroutines
- Purpose: Kotlin coroutines library for asynchronous and reactive code.
- License: Apache 2.0
kotlinx.serialization
- https://github.com/Kotlin/kotlinx.serialization/
- Purpose: JSON serialization library for Kotlin.
- License: Apache 2.0
OkHttp 3
- https://github.com/square/okhttp
- Purpose: An HTTP client used by the library to intercept and log traffic.
- License: Apache 2.0
Retrofit 2
- https://github.com/square/retrofit
- Purpose: A networking layer interface.
- License: Apache 2.0
Timber
- https://github.com/JakeWharton/timber
- Purpose: Extensible logging library for Android.
- License: Apache 2.0
ZXing
- https://github.com/zxing/zxing
- Purpose: Barcode scanning and generation.
- License: Apache 2.0
The following is an additional list of third-party dependencies that are only included in the non-F-Droid build variants of the application.
Firebase Cloud Messaging
- https://github.com/firebase/firebase-android-sdk
- Purpose: Allows for push notification support.
- License: Apache 2.0
Firebase Crashlytics
- https://github.com/firebase/firebase-android-sdk
- Purpose: SDK for crash and non-fatal error reporting.
- License: Apache 2.0
Google Play Reviews
- https://developer.android.com/reference/com/google/android/play/core/release-notes
- Purpose: On standard builds provide an interface to add a review for the password manager application in Google Play.
- License: Apache 2.0
Development Environment Dependencies
The following is a list of additional third-party dependencies used as part of the local development environment. This includes test-related artifacts as well as tools related to code quality and linting. These are not present in the final packaged application.
detekt
- https://github.com/detekt/detekt
- Purpose: A static code analysis tool for the Kotlin programming language.
- License: Apache 2.0
JUnit 5
- https://github.com/junit-team/junit5
- Purpose: Unit Testing framework for testing application code.
- License: Eclipse Public License 2.0
MockK
- https://github.com/mockk/mockk
- Purpose: Kotlin-friendly mocking library.
- License: Apache 2.0
Robolectric
- https://github.com/robolectric/robolectric
- Purpose: A unit testing framework for code directly depending on the Android framework.
- License: MIT
Turbine
- https://github.com/cashapp/turbine
- Purpose: A small testing library for kotlinx.coroutine's Flow.
- License: Apache 2.0
CI/CD Dependencies
The following is a list of additional third-party dependencies used as part of the CI/CD workflows. These are not present in the final packaged application.
Fastlane
- https://fastlane.tools/
- Purpose: Automates building, signing, and distributing applications.
- License: MIT
Kover
- https://github.com/Kotlin/kotlinx-kover
- Purpose: Kotlin code coverage toolset.
- License: Apache 2.0
File: authenticatorbridge/README.md
Authenticator Bridge SDK
Contents
Other Documents
Compatibility
- Minimum SDK: 29 (Android 10)
- Target SDK: 37 (Android 17)
Building
To build an AAR for inclusion in consumer applications, run:
$ ./gradlew authenticatorbridge:assembleReleaseVersioning
This repository conforms to the following versioning convention:
v[MAJOR].[MINOR].[PATCH]
where [RELEASE] is incremented to represent major milestones that indicate a significant change in the library.
[MINOR] is incremented when any standard changes (breaking or otherwise) are introduced to the library.
[PATCH] is incremented when a hot-fix patch is required to an existing minor
release due to a bug introduced in that release.Some things to note:
All updates should have a corresponding
CHANGELOG.mdentry that at a high-level describes what is being newly introduced in it. For more info, see Changelog Format GuideWhen incrementing a level any lower-levels should always reset to 0.
Dependencies
[!IMPORTANT]
The SDK does not come packaged with these dependencies, so consumers of the SDK must provide them.
Module Dependencies
The following is a list of project modules required by the SDK.
bitwarden-core
bitwarden-annotations
- Annotations
- Purpose: Internal annotations used by the SDK.
- License: LICENSE
Application Dependencies
The following is a list of all third-party dependencies required by the SDK.
AndroidX Appcompat
- https://developer.android.com/jetpack/androidx/releases/appcompat
- Purpose: Allows access to new APIs on older API versions.
- License: Apache 2.0
AndroidX Lifecycle
- https://developer.android.com/jetpack/androidx/releases/lifecycle
- Purpose: Lifecycle aware components and tooling.
- License: Apache 2.0
kotlinx.coroutines
- https://github.com/Kotlin/kotlinx.coroutines
- Purpose: Kotlin coroutines library for asynchronous and reactive code.
- License: Apache 2.0
kotlinx.serialization
- https://github.com/Kotlin/kotlinx.serialization/
- Purpose: JSON serialization library for Kotlin.
- License: Apache 2.0
Development Environment Dependencies
The following is a list of additional third-party dependencies used as part of the local development environment. This includes test-related artifacts as well as tools related to code quality and linting. These are not present in the final packaged SDK.
JUnit 5
- https://github.com/junit-team/junit5
- Purpose: Unit Testing framework for testing SDK code.
- License: Eclipse Public License 2.0
MockK
- https://github.com/mockk/mockk
- Purpose: Kotlin-friendly mocking library.
- License: Apache 2.0
Turbine
- https://github.com/cashapp/turbine
- Purpose: A small testing library for kotlinx.coroutine's Flow.
- License: Apache 2.0
File: core/README.md
Core module
A collection of platform specific objects and extensions used by other Bitwarden applications and
libraries.
Contents
Compatibility
- Minimum SDK: 29 (Android 10)
- Target SDK: 37 (Android 17)
File: data/README.md
Data module
An Android library containing common data sources, types, and utilities.
Contents
Compatibility
- Minimum SDK: 29 (Android 10)
- Target SDK: 37 (Android 17)
File: docs/ARCHITECTURE.md
Architecture
Overview
The Bitwarden Android project employs a multi-module architecture to enhance separation of concerns, maintainability, and build efficiency. This architecture distinguishes between application modules, which are user-facing, and library modules, which provide shared functionalities.
Application modules
These modules represent the entry points and primary user interfaces for the applications. They are structured with standard Android source sets to organize code for different build types and testing:
Bitwarden.app: This module constitutes the Bitwarden Password Manager application. It integrates various library modules to deliver password management and secure data storage features. It is responsible for the application's top-level setup, primary navigation graph, and dependency injection rooting for password manager functionalities. Theappmodule utilizes product flavors to generate different versions of the application:src/standard/: Contains code and resources specific to the 'standard' product flavor. Builds produced from this flavor are intended for distribution via the Google Play Store and include functionality dependent on Google Play Services.src/fdroid/: Contains code and resources specific to the 'fdroid' product flavor. Builds produced from this flavor are intended for distribution via F-Droid. This flavor is stripped of all Google Play Services libraries and, as such, does not contain features like push notifications for real-time syncing.src/debug/: Contains code and resources specific to the 'debug' build type (e.g., for enabling debug-specific features, configurations, or alternative API endpoints), which can be combined with any product flavor.src/release/: Contains code and resources specific to the 'release' build type (e.g., for ProGuard/R8 configurations, release-specific API keys, or analytics configurations), which can be combined with any product flavor.
Bitwarden.authenticator: This module implements the Bitwarden Authenticator application. Its purpose is to store and generate two-factor authentication (2FA) codes, such as Time-based One-Time Passwords (TOTP), directly on the user's device. It provides the user interface and logic for managing authenticator accounts and displaying codes, functioning as a standalone authenticator application.src/debug/: Contains code and resources specific to the 'debug' build type of the Authenticator.src/release/: Contains code and resources specific to the 'release' build type of the Authenticator.
Core Library Modules
These libraries provide foundational capabilities utilized by application modules and other feature-specific libraries:
Bitwarden.core: A fundamental library containing shared business logic, essential data models (entities, value objects), domain-specific utilities, and common interfaces. It is designed with minimal or no direct Android framework dependencies to ensure high reusability and testability.Bitwarden.data: Manages the data layer for the applications. Responsibilities include defining repositories, data sources (for network APIs and local persistence like Room), data transformation logic (mappers), and managing data synchronization. It abstracts data origin and storage details from other parts of the system.Bitwarden.network: Encapsulates all network communication logic. This includes API client setup (e.g., using Retrofit or Ktor), defining request/response models for network operations, and handling network interceptors and authentication.Bitwarden.ui: A library module providing common UI elements, theming resources (colors, typography, shapes), custom Jetpack Compose components, base UI classes, and UI-related utility functions. It ensures a consistent user experience across different features and applications.
Specialized Library Modules
These libraries offer more targeted functionalities:
Bitwarden.authenticatorbridge: Serves as an interface or bridge facilitating communication and integration between theBitwarden.authenticatormodule's functionalities and theBitwarden.appmodule. This allows for controlled interaction while maintaining modular decoupling.Bitwarden.annotation: Contains custom Java/Kotlin annotations used throughout the project. These annotations support compile-time code generation (e.g., for dependency injection with Dagger Hilt, or database schema generation with Room) and provide metadata for other development tools.
Supporting Modules (Source Sets and Test Fixtures)
The project structure includes conventional Gradle source sets and test fixture modules that support
development and testing:
src/main/: The primary source set of a module, containing its functional code.src/test/: Contains local unit tests (JVM-based) for the associated module.src/testFixtures/: Provides shared testing utilities, mock objects, sample data, or helper
functions reusable across various test modules.
Data Layer
The data layer is where all the UI-independent data is stored and retrieved. It consists of both raw data sources as well as higher-level "repository" and "manager" classes.
Note that any functions exposed by a data layer class that must perform asynchronous work do so by exposing suspending functions that may run inside coroutines while any streaming sources of data are handled by exposing Flows.
Data Sources
The lowest level of the data layer are the "data source" classes. These are the raw sources of data that include data persisted in Room / SharedPreferences, data retrieved from network requests using Retrofit, and data retrieved via interactions with the Bitwarden SDK.
Note that these data sources are constructed in a manner that adheres to a very important principle of the app: that function calls should not throw exceptions (see the style and best practices documentation for more details.) In the case of data sources, this tends to mean that suspending functions like those representing network requests or Bitwarden SDK calls should return a Result type. This is an important responsibility of the data layer as a wrapper around other third party libraries, as dependencies like Retrofit and the Bitwarden SDK tend to throw exceptions to indicate errors instead.
Managers
Manager classes represent something of a middle level of the data layer. While some manager classes like VaultLockManager depend on the the lower-level data sources, others are wrappers around OS-level classes (ex: AppStateManager) while others have no dependencies at all (ex: SpecialCircumstanceManager). The commonality amongst the manager classes is that they tend to have a single discrete responsibility. These classes may also exist solely in the data layer for use inside a repository or manager class, like AppStateManager, or may be exposed directly to the UI layer, like SpecialCircumstanceManager.
Repositories
Repository classes represent the outermost level of the data layer. They can take data sources, managers, and in rare cases even other repositories as dependencies and are meant to be exposed directly to the UI layer. They synthesize data from multiple sources and combine various asynchronous requests as necessary in order to expose data to the UI layer in a more appropriate form. These classes tend to have broad responsibilities that generally cover a major domain of the app, such as authentication (AuthRepository) or vault access (VaultRepository).
Repository classes also feature functions that do not throw exceptions, but unlike the lower levels of the data layer the Result type should be avoided in favor of custom sealed classes that represent the various success/error cases in a more processed form. Returning raw Throwable/Exception instances as part of "error" states should be avoided when possible.
In some cases a source of data may be continuously observed and in these cases a repository may choose to expose a StateFlow that emits data updates using the DataState wrapper.
Note on Dependency Injection
Nearly all classes in the data layer consist of interfaces representing exposed behavior and a corresponding ...Impl class implementing that interface (ex: AuthDiskSource / AuthDiskSourceImpl). All ...Impl classes are intended to be manually constructed while their associated interfaces are provided for dependency injection via a Hilt Module (ex: PlatformNetworkModule). This prevents the ...Impl classes from being injected by accident and allows the interfaces to be easily mocked/faked in tests.
UI Layer
The UI layer adheres to the concept of unidirectional data flow and makes use of the MVVM design pattern. Both concepts are in line what Google currently recommends as the best approach for building the UI-layer of a modern Android application and this allows us to make use of all the available tooling Google provides as part of the Jetpack suite of libraries. The MVVM implementation is built around the Android ViewModel class and the UI itself is constructed using the Jetpack Compose, a declarative UI framework specifically built around the unidirectional data flow approach.
Each screen in the app is associated with at least the following three classes/files:
- A
...ViewModelclass responsible for managing the data and state for the screen. - A
...Screenclass that contains the Compose implementation of the UI. - A
...Navigationfile containing the details for how to add the screen to the overall navigation graph and how navigate to it within the graph.
ViewModels / MVVM
The app's approach to MVVM is based around the handling of "state", "actions", and "events" and is encoded in the BaseViewModel class.
State: The "state" represents the complete internal and external total state of the ViewModel (VM). Any and all information needed to configure the UI that is associated with the VM should be included in this state and is exposed via the
BaseViewModel.stateFlowproperty asStateFlow<S>(whereSrepresents the unique type of state associated with the VM). This state is typically a combination of state from the data layer (such as account information) and state from the UI layer (such as data entered into a text field).There should be no additional
StateFlowexposed from a VM that would represent some other kind of state; all state should be represented byS. Additionally, any internal state not directly needed by the UI but which influences the behavior of the VM should be included as well in order to keep all state managed by the VM in a single place.Actions: The "actions" represent interactions with the VM in some way that could potentially cause an update to that total state. These can be external actions coming from the user's interaction with the UI, like click events, or internal actions coming from some asynchronous process internal to the VM itself, like the result of some suspending functions. Actions are sent by interacting directly with
BaseViewModel.actionChannelor by using theBaseViewModel.sendActionandBaseViewModel.trySendActionhelpers. All actions are then processed synchronously in a queue in thehandleActionfunction.It is worth emphasizing that state should never be updated inside a coroutine in a VM; all asynchronous work that results in a state update should do so by posting an internal action. This ensures that the only place that state changes can occur is synchronously inside the
handleActionfunction. This makes the process of finding and reasoning about state changes easier and simplifies debugging.Events: The "events" represent discrete, one-shot side-effects and are typically associated with navigation events triggered by some user action. They are sent internally using
BaseViewModel.sendEventand may be consumed by the UI layer via theBaseViewModel.eventFlowproperty. An EventsEffect should typically be used to simplify the consumption of these events.
VMs are typically injected using Dagger Hilt by annotating them with @HiltViewModel. This allows them to be constructed, retrieved, and cached in the Compose UI layer by calling hiltViewModel() with the appropriate type. Dependencies passed into the VM constructor will typically be singletons of the graph, such as AuthRepository. In cases where the VM needs to initialized with some specific data (like an ID) that is sent from the previous screen, this data should be retrieved by injecting the SavedStateHandle and pulling out data using a type-safe wrapper (ex: LoginArgs).
Example
The following is an example that demonstrates many of the above principles and best practices when using BaseViewModel to implement a VM. It has the following features:
- It is injected with a repository (
ExampleRepository) that provides streamingExampleDataand aSavedStateHandlein order to pull initial data using aExampleArgswrapper class. - It has state that manages several properties of interest to the UI:
exampleData,isToggledEnabled, anddialogState. - It receives external actions from the UI (
ContinueButtonClickandToggleValueUpdate) as well as internal actions launch from inside different coroutines coroutines (Internal.ExampleDataReceive,Internal.ToggleValueSync). These actions result in state updates or the emission of an event (NavigateToNextScreen). - It saves the current state to the
SavedStateHandlein order to restore it later after process death and restoration. This ensures the user's actions and associated state will not be lost if the app goes into the background and is temporarily killed by the OS to conserve memory.
Show example
/* Detailed source-code truncated for AI context efficiency. */Screens / Compose
Each unique screen destination is represented by a composable ...Screen function annotated with @Composable. The responsibilities of this layer include:
- Receiving "state" data from the associated
ViewModeland rendering the UI accordingly. - Receiving "events" from the associated
ViewModeland taking the corresponding action, which is typically to trigger a passed-in callback function for navigation purposes. An EventsEffect should be used to simplify this process. - Sending "actions" to the
ViewModelindicating user interactions or UI-layer events as necessary. - Interacting with purely UI-layer "manager" classes that are not appropriate or possible to be injected into the
ViewModel(such as those concerning permissions or camera access).
In order to both provide consistency to the app and to simplify the development of new screens, an extensive system of reusable composable components has been developed and may be found in the components package. These tend to bear the prefix Bitwarden... to easily distinguish them from similar OS-level components. If there is any new unique UI component that is added, it should always be considered if it should be made a shareable component.
Refer to the style and best practices documentation for additional information on best practices when using Compose.
State-hoisting
Jetpack Compose is built around the idea that the state required to render any given composable function can be "hoisted" to higher levels that may need access to that state. This means that the responsibility for keeping track of the current state of a component may not typically reside with the component itself. It is important, therefore, to understand where the best place is to manage any given piece of UI state.
This is discussed in detail in Google's state-hoisting documentation and can be summarized roughly as follows: state should be hoisted as high as is necessary to perform any relevant logic and no higher. This is a pattern that is followed in the Bitwarden app and tends to lead to the following:
- Any state that will eventually need to be used by the VM should be hoisted to the VM. For example, any text input, toggle values, etc. that may be updated by user interactions should be completely controlled by the VM. These state changes are communicated via the "actions" that the Compose layer sends, which trigger corresponding updates the VM's total "state".
- Any UI state that will not be used by logic inside the VM should remain in the UI layer. For example, visibility toggle states for password inputs should typically remain out of the VM.
These rules can lead to some notable differences in how certain dialogs are handled. For example, loading dialogs are controlled by events that occur in the VM, such as when a network request is started and when it completes. This requires the VM to be in charge of managing the visibility state of the dialog. However, some dialogs appear as the result of clicking on an item in the UI in order to simply display information or to ask for the user's confirmation before some action is taken. Because there is no logic in the VM that depends on the visibility of these particular dialogs, their visibility state can be controlled by the UI. Note, however, that any user interaction that results in a navigation to a new screen should always be routed to the VM first, as the VM should always be in charge of triggering changes at the per-screen level.
Example
The following shows off the basic structure of a composable ...Screen implementation. Note that:
- The VM is "injected" using the
hiltViewModel()helper function. This will correctly create, cache, and scope the VM in production code while making it easier to pass in mock/fake implementations in test code. - An
onNavigateToNextScreenfunction is also passed in, which can be called to trigger a navigation via a call to a NavController in the outer layers of the navigation graph. Passing in a function rather than theNavControlleritself decouples the screen code from the navigation framework and greatly simplifies the testing of screens. - The VM "state" is consumed using
viewModel.stateFlow.collectAsStateWithLifecycle(). This will cause the composable to "recompose" and update whenever updates are pushed to theviewModel.stateFlow. - The VM "events" are consumed using an EventsEffect and demonstrate how the
onNavigateToNextScreenmay be triggered. - The current state of the text, switch, and button are hoisted to the VM and pulled out from the
state. User interactions with the switch and button result in "actions" being sent to the VM usingviewModel.trySendAction. - Reusable components (
BitwardenLoadingDialog,BitwardenSwitch, andBitwardenFilledButton) are used where possible in order to build the screen using the correct theming and reduce code duplication. When this is not possible (such as when rending theTextcomposable) all colors and styles are pulled from the BitwardenTheme object.
Show example
/* Detailed source-code truncated for AI context efficiency. */Navigation
Navigation in the app is achieved via the Compose Navigation component. This involves specifying "destinations" within a NavHost and using a NavController to trigger actual navigation events. The app uses a mix of state-based navigation at the highest level (in order to determine the overall app flow the user is in) and event-based navigation (to handle navigation within a flow based on user interactions).
State-based Navigation
State-based navigation is handled by the RootNavViewModel and RootNavScreen. The current navigation state is determined within the RootNavViewModel by monitoring the overall UserState along with any SpecialCircumstance. The UserState encodes whether there are any user accounts, whether they are logged in, etc., while the SpecialCircumstance describes a particular circumstance under which the app may have been launched (such as being opened in order to manually select an autofill value). The RootNavState calculated by the RootNavViewModel is then used by the RootNavScreen in order to trigger a navigation only if the overall state has changed.
The benefit of state-based navigation at this level is that it allows for a variety of state changes that may happen deep within the data layer to automatically trigger navigation to the correct top-level flow without the rest of the UI needing to be concerned with these details. For example, when logging out the current user, the data layer can decide the new state and the RootNavViewModel can decide where to go next, rather than having the screen that triggered the logout action choose the next navigation state (which would then need to be redundantly handled in multiple places in the app).
State-based navigation should be limited to specific cases that affect the overall flow of the app and are driven by data emitted from the data layer. All other navigation should use event-based navigation.
Event-based Navigation
Event-based navigation is ultimately the result of some "action" sent to a VM, whether that comes directly from a user-interaction with the current screen or from some internal action of the VM sent as the result of some asynchronous call. The VM will send an "event" to the Compose layer, which will trigger a callback that will eventually make a call to a NavController.
Navigation Implementation
At its most basic level, Compose Navigation relies on constructing String-based URIs with a root path to specify a destination and both path and query parameters to handle the passing of required and optional parameters. This process can typically be very error prone. The Bitwarden app borrows a pattern best exemplified by the Now In Android sample project in order to make this process more type-safe. This consists of:
- A type-safe
...Destinationextension function on NavGraphBuilder for any single screen destination or a type-safe...Graphextension function on NavGraphBuilder for any nested graph destination. - A type-safe
navigateTo...extension function on NavController for any destination that is not simply the root of a graph. - A type-safe
...Argsclass that pulls data from aSavedStateHandlefor consumption by a VM.
These are all then grouped into a single ...Navigation.kt file where all of the raw String-based details can be hidden and only the exposed type-safe functions must be used by the rest of the app.
Example
The following example demonstrates a sample ExampleNavigation.kt file with:
- An
ExampleArgsclass that wrapsSavedStateHandleand allows for theisToggleEnabledInitialValueto be extracted in a type-safe way. - A
NavGraphBuilder.exampleDestinationextension function that can be used to safely add theExampleScreento the navigation graph. - A
NavController.navigateToExampleextension function that can be called to navigate to theExampleScreenin a type-safe way.
Note in particular how consumers of the above do not need to know the details of the actual route or path parameter.
Show example
@Serializable
data class ExampleRoute(
val isToggleEnabled: Boolean,
)
data class ExampleArgs(
val isToggleEnabledInitialValue: Boolean,
)
fun SavedStateHandle.toExampleArgs(): ExampleArgs {
val route = this.toRoute<ExampleRoute>()
return ExampleArgs(isToggleEnabledInitialValue = route.isToggleEnabled)
}
fun NavGraphBuilder.exampleDestination(
onNavigateToNextScreen: (CompletionData) -> Unit,
) {
composableWithSlideTransitions<ExampleRoute> {
ExampleScreen(onNavigateToNextScreen = onNavigateToNextScreen)
}
}
fun NavController.navigateToExample(
isToggleEnabled: Boolean,
navOptions: NavOptions? = null,
) {
this.navigate(
route = ExampleRoute(isToggleEnabled = isToggleEnabled),
navOptions = navOptions,
)
}File: docs/STYLE_AND_BEST_PRACTICES.md
Code Style Guidelines
Contents
The following outlines the general code style and best practices for Android development. It is expected that all developers are familiar with the code style documents referenced here and have them bookmarked for quick reference when necessary.
Rather than repeating the rules listed in those documents, this guide only mentions rules that override or are in addition to the ones present in them. Also note that while the bitwarden-style.xml formatter and detekt tool will enforce many of the rules (such as the 100 character line limit) there are many it can not or will not enforce and it is therefore extremely important that all developers read and follow this document. For more details on what the formatter does handle, refer directly to the settings in Android Studio under Preferences > Editor > Code Style and select the language of interest.
Style : Kotlin
The library's Kotlin code style adheres closely to both the code style documentation for the Kotlin language itself and the code style documentation for the Android Open Source Project. The former provides the "base" reference while the AOSP docs should be viewed as tweaks to that document. In the rare cases where the two documents disagree, the AOSP rules should apply.
Disagreements between the Kotlin language and Android code style documents
Some notable disagreements between the two documents include:
AOSP rules do not allow for two-letter acronyms to be capitalized separately when part of a member name. For example
kotlin// Bad val fetcher: IDFetcher // Good val fetcher: IdFetcher
Custom library style
In general, the code style documents referenced above cover most of the basic cases of interest. There will always be situations, however, where the documents are unclear, vague, or simply do not offer an opinion. Furthermore, there are some cases where we will directly break with the code style documents. Below are some examples of these cases (though it should be noted that no single document can ever fully classify our complete style and existing code should always be sought for a reference in questionable cases.)
Class and file layout
The documents specify that a class layout should use the following order:
- Property declarations and initializer blocks
- Secondary constructors
- Method declarations
- Companion objectWe will adhere to this order, but there are a few additions / modifications :
Nested class definitions should be placed after the Companion object. In cases where the nested
class is only used internally, it is also valid to simply place the class in the same file after
the main source class.The code style documents say to use "logical ordering" for method declarations. We will adhere to this principle while also noting that does not mean new code in a file should simply be added to the end; be thoughtful about placement! In the absence of any compelling logistical ordering, alphabetization is a valid choice (though not required).
Also please note the following:
- Methods with certain "special modifiers" (
override,operator,abstact, etc.) should come first and methods with the same modifiers should be grouped together. Certain types of annotations may also qualify as a "special modifier" (refer to existing library code). - If any kind of method group described above requires "sub-groups", these can be denoted by the use of the
//region <Name> ... //endregion <Name>markers. These regions should be used for a very small set of methods, such as for the overrides to a single interface.
- Methods with certain "special modifiers" (
Type omission
We generally prefer to omit types whenever the compiler allows it and the return type is unambiguous. This is true for functions, properties, and variable declarations.
// Good: This is clearly an integer value.
val durationInSeconds = 100// Bad: The return type can only be inferred by looking at the signature of another function, which
// might itself be omitting a type.
fun requestData() = apiService.getData()When omitting a type for a function, it is very important that it is done thoughtfully; a function's type should not be the accidental consequence of overly concise code.
Expression functions
We generally prefer using expression functions whenever possible to keep the code concise and free of unnecessary boilerplate. This should only be done when a call chain naturally suggests such a form, though; complicated functions should not be forced into a single expression simply to take advantage of this feature.
Functions as parameters
We strongly encourage the direct use of functions as parameters rather than defining one-off listener classes. For example
// Good
fun waitForEvent(handler: (Event) -> Unit) {
val event = produceEvent()
handler(event)
}is preferable to
interface EventHandler {
fun handleEvent(event: Event): Unit
}
...
// Bad
fun waitForEvent(handler: EventHandler) {
val event = produceEvent()
handler.handleEvent(event)
}This not only reduces the amount of boilerplate code necessary, but it also ensures lambdas can be used properly from within Kotlin. When an interface is preferred for some reason, strongly consider the user of functional interfaces to continue to take advantage of SAM conversions at the callsite.
Long function calls
As discussed in the code style document long function calls should place each argument on their own line. The closing parenthesis should be on its own line as well:
drawSquare(
x = 10,
y = 10,
width = 100,
height = 100,
fill = true,
)Unlike those rules, however, we don't allow grouping "multiple closely related arguments on the same line".
When there is only one argument but the function call must wrap to multiple lines, that argument should still be placed on its own line(s).
// Good
.register(
object : Callback<DeviceEvent>() {
override fun onSuccess() = ...
override fun onError() = ...
}
)// Bad
.register(object : Callback() {
override fun onSuccess() = ...
override fun onError() = ...
})Annotation-related formatting
When annotating properties, the annotations should be on their own lines and there must be a space between each annotated property. The following is correct:
// Good
@Inject
val propertyA: PropertyA
@Inject
val propertyB: PropertyB
@Inject
@CustomAnnotation
val propertyC: PropertyC
@Inject
val propertyD: PropertyDwhile this is not:
// Bad
@Inject val propertyA: PropertyA
@Inject val propertyB: PropertyB
@Inject @CustomAnnotation
val propertyC: PropertyC
@Inject val propertyD: PropertyDChained call formatting
As mentioned in the main documents, for long call chains it is preferred to put all method calls on their own lines, even the first:
val anchor = owner
?.firstChild!!
.siblings(forward = true)
.dropWhile { it is PsiComment || it is PsiWhiteSpace }The goal should always be to keep the start of function calls and the closing parenthesis vertically aligned. Consider the following example:
// Good
fragmentComponent
.customFragmentComponent(
CustomFragmentModule(
this,
argument,
)
)
.inject(this)Notice what happens if the first method call to .customFragmentComponent is placed on the first line:
// Bad
fragmentComponent.customFragmentComponent(
CustomFragmentModule(
this,
argument,
)
)
.inject(this)The closing parenthesis for .customFragmentComponent() does not align with either it nor with .inject.
Note that in cases where a single method is being called, it is valid for it to be on the same line as the instance:
// Good
return Bundle().apply {
putParcelable(KEY_ARGUMENTS, arguments)
}If a chain is created here, however, the method must be moved down:
// Good
return Bundle()
.apply {
putParcelable(KEY_ARGUMENTS, arguments)
}
.also { ... }Failure to do so will result in the following incorrect formatting:
// Bad
return Bundle().apply {
putParcelable(KEY_ARGUMENTS, arguments)
}
.also { ... }In some cases proper formatting will be impossible. Each of the following---while not ideal---is in the "correct" format because there is no good alternative:
// Acceptable (no better alternative)
topLevelFunction(
...long argument list...
)
.apply { ... }// Acceptable (no better alternative)
ObjectConstructor(
...long argument list...
)
.apply { ... }These types of scenarios should be avoided when possible (as described above) but are allowed when necessary.
Miscellaneous Code Formatting
Whenever questions about code formatting arise in which multiple options are valid according to all previously described rules, the Rectangle Rule is a good test to use to prefer one style over the other.
Documentation
All public classes, functions, and properties should include documentation in the KDoc style. Private classes, companion objects, functions, and properties may optionally be documented as needed.
Class Documentation
Classes with more than 2 constructor properties should document each individually using the @property label; otherwise the property descriptions can be incorporated into the class description:
// Good. The class contains a single constructor property that is included in the class's own
// documentation
/**
* A wrapper class for a unique idenfitier, [id].
*/
data class IdWrapper(
val id: String,
)// Good. The class contains more than two properties and each are documented separately.
/**
* A class containing various data.
*
* @property id The unique identifier for the data.
* @property name The name of the data.
* @property value The value associated with the data.
*/
data class Data(
val id: String,
val name: String,
val value: String,
)// Bad. The constructor properties are not documented.
/**
* A class containing various data.
*/
data class Data(
val id: String,
val name: String,
val value: String,
)// Bad. The constructor properties are not documented individually.
/**
* A class containing various data ([id], [name], [value]).
*/
data class Data(
val id: String,
val name: String,
val value: String,
)// Bad. Not using KDoc style.
// A class containing various data ([id], [name], [value]).
data class Data(
val id: String,
val name: String,
val value: String,
)Functions
Functions are typically allowed to include documentation for parameters within the body of the function documentation itself independent of their number:
// Good
/**
* Gets the data for the given [id].
*/
fun getData(id: String): Data// Good
/**
* Gets a list of data items from the [startDateInMillis] to the [endDateInMillis]. This number of
* items in the list will not exceed [maxCount].
*/
fun getDataList(
startDateInMillis: Long,
endDateInMillis: Long,
maxCount: Long
): List<Data>// Bad. Not in KDoc style.
// Gets the data for the given [id].
fun getData(id: String): DataWhen each parameter appears to require more focused documentation, @param may be used;
// Good
/**
* Gets a list of data items.
*
* @param startDateInMillis The beginning data (in epoch time as milliseconds) to begin searching
* for data items.
* @param endDateInMillis The end data (in epoch time as milliseconds) to stop searching
* for data items.
* @param maxCount The maximum number of items to return.
*/
fun getDataList(
startDateInMillis: Long,
endDateInMillis: Long,
maxCount: Long
): List<Data>Inline comments
Inline comments are encouraged, particularly when the logic being described is not self-explanatory. The comments should:
- begin with
//. - include a space before the first word.
- capitalize the first word.
- optionally include punctuation for sentence fragments or single sentences.
- include punctuation for multiple sentences.
- prefer the "imperative" voice.
// Good
// Get the data from the database
val data = databaseDataSource.getData(id)// Good
// Get the data from the database. This will happen synchronously.
val data = databaseDataSource.getData(id)// OK. Not in the imperative voice.
// Gets the data from the database
val data = databaseDataSource.getData(id)// Bad. Missing space before first word and missing capitalization on first word.
//get the data from the database
val data = databaseDataSource.getData(id)// Bad. Missing punctuation for multiple sentences.
// Get the data from the database
// This will happen synchronously
val data = databaseDataSource.getData(id)Style : ViewModels
- Private functions that handle actions should be prefixed with "handle" and suffixed with the name of the action. (ex:
handleSubmitClick)
Best Practices : Kotlin
The following contains general tips and best practices that apply for Kotlin code (unless otherwise specified) that has not already been mentioned in their specific sections above.
We will be adhering to the 100 character line limit. This will be enforced in most places by the auto-formatter.
Avoid unnecessary
if/elsenesting and keep code as left-aligned as possible by using early return statements. For examplekotlin// Bad fun someMethod() { if (someCondition) { // ...many lines of code... } else { // Do nothing } } // Bad fun someMethod() { if (someCondition) { // ...many lines of code... } } // Good fun someMethod() { if (!someCondition) { return } // ...many lines of code... }When an early return is not possible because additional code is required to run after the
if, consider moving theifto its own method.kotlin// Bad fun someMethod() { if (someCondition) { // ...many lines of code... } // ...more code... } // Good fun someMethod() { internalHelperMethod() // ...more code... } // where... fun internalHelperMethod() { if (!someCondition) { return } // ...many lines of code... }Using an expression like
true == someBooleanis acceptable only whensomeBooleanis nullable (i.e.Boolean?) and requires unwrapping:kotlin// Bad val nonNullBoolean: Boolean = true if (nonNullBoolean == true) ... // Good val nonNullBoolean: Boolean = true if (nonNullBoolean) ... // Bad (does not compile) val nullableBoolean: Boolean? = true if (nullableBoolean) ... // Good val nullableBoolean: Boolean? = true if (nullableBoolean == true) ...Any method or constructor left blank deliberately (such as an unneeded interface method) should be formatted as a one-line expression function with the explicit return type of
Unit:kotlinoverride fun unusedMethod() = UnitNullability should be very clearly communicated. In Kotlin, only objects expected to be null should be given nullable types:
kotlin// Bad: Are these all *really* nullable? An network object with an "optional" ID does not make // much sense. data class NetworkData { val id: String? val name: String? val iconUrl: String? } // Good: The API docs for this class communicate that "id" and "name" will never be null, so // they should not be given nullable types. "iconUrl" is not guaranteed, so it may be made // nullable. data class NetworkData { val id: String val name: String val iconUrl: String? }Whenever possible, pass and return interfaces rather than implementations. For example:
kotlin// Bad: Why should the method care what type of List is passed to it and why should the caller // care what type of List is passed back? fun filter(input: ArrayList<String>): ArrayList<String> { ... } // Good fun filter(input: List<String>): List<String> { ... }With very few exceptions, static variables should never be used. Their use is typically a symptom of a failure to properly declare and pass dependencies from one area of the library to another. It is better to explicitly pass the dependencies when possible. When "static" behavior is absolutely needed, an injected singleton should be used to provided the data instead:
kotlin// Bad: This class should not depend on the static data held by another. Not only does it make // it hard to understand what the dependencies are here, this code is potentially unstable and // unpredictable and hard to control during tests. class NeedsExternalData { fun someMethod() { val data = SomeOtherClass.staticData // ...code requiring Data instance... } }kotlin// Good: This class requires a Data object to function properly so it is instantiated with it. class NeedsExternalData( private val data: Data, ) { fun someMethod() { // ...code requiring Data instance... } }kotlin// Good: This class requires a Data object for someMethod to function properly, so it is passed // in. class NeedsExternalData { fun someMethod(data: Data) { // ...code requiring Data instance... } }kotlin// Good: This class requires a Data object for someMethod to function properly, so we inject // an instance of DataProvider. class NeedsExternalData @Inject constructor( private val dataProvider: DataProvider ) { fun someMethod() { val data = dataProvider.getData() // ...code requiring Data instance... } }Functions should not intentionally throw exceptions! Any function that needs to represent the possibility of both a success and an error should either:
- Return the Result type.
- Return a custom sealed class to model the possibilities.
- Return a nullable value and clearly indicate a
nullrepresents an empty/failure state of some kind.
When it is absolutely required (such as when dealing with external libraries that throw) exception handling should be done properly and only when necessary. This means that (except for rare cases):
Never catch
Exceptiongenerically. Always catch the specific errors that are known to be possible:kotlin// Bad: What exception is being thrown here and why? Is it something we can fix by trying // again or is it unrecoverable? try { service.makeServiceCall() } catch (e: Exception) { // ... } // Good try { service.makeServiceCall() } catch (e: RemoteException) { // ... }Never catch a
RuntimeExceptionthat can't happen:kotlin// Bad: A NumberFormatException is not possible here based on what we know about the value // we're using, so we're adding code that isn't necessary. val definitelyANumber = "1234" val value = try { Integer.parseInt(definitelyANumber) } catch (e: NumberFormatException) { // ... }kotlin// Good val definitelyANumber = "1234" val value = Integer.parseInt(definitlyANumber)Never use
e.printStackTrace(). Instead, use a configurable logging class:kotlin// Bad: This will print directly to the system, even in production. try { service.makeServiceCall() } catch (e: RemoteException) { e.printStackTrace() }kotlin// Good try { service.makeServiceCall() } catch (e: RemoteException) { Timber.e(e, "Error making a service call.") }Never catch exceptions to "solve" bugs that should be managed elsewhere.
kotlin// Bad: Why does the method throw the NPE? Is it our fault or a problem in the method itself? // It is impossible to tell here. val locationID = methodReturningNullableString() try { methodRequiringNonNullArguments(locationId) } catch (e: NullPointerException) { return }kotlin// Good val locationId = methodReturningNullableString() if (locationId == null) { return } methodRequiringNonNullArguments(locationId)Never wrap huge chunks of code in a
try/catch; only wrap the lines that throw anException:kotlin// Bad: It is difficult to follow the flow here. Which lines throw? At what point in the // code might we be forced to the catch block? try { val value = lineThatThrows() // ...many more lines of code... } catch (e: RemoteException) { // ... }kotlin// Good val value = try { lineThatThrows() } catch (e: RemoteException) { // ...handle the error case... return } // ...many more lines of code...When multiple lines throw the same exception, they may all be placed in the same
tryblock:kotlinval value1: String val value2: String val value3: String try { value1 = lineThatThrows1() value2 = lineThatThrows2() value3 = lineThatThrows3() } catch (e: RemoteException) { // ... }When there is code between them that does not throw, then each call should be wrapped separately:
kotlinval value1 = try { lineThatThrows1() } catch (e: RemoteException) { // ... } // ...code that does not throw... val value2 = try { lineThatThrows2() } catch (e: RemoteException) { // ... } // ...code that does not throw... val value3 = try { lineThatThrows3() } catch (e: RemoteException) { // ... }
Best Practices : Jetpack Compose
When writing UI layer code using Jetpack Compose, the Compose API guidelines should be considered the go-to reference for style and best practices.
Special consideration should be taken to avoid unnecessary recompositions. There are now numerous sources that address the topic, including the following:
- https://developer.android.com/jetpack/compose/performance/bestpractices
- https://getstream.io/blog/jetpack-compose-guidelines/
- https://multithreaded.stitchfix.com/blog/2022/08/05/jetpack-compose-recomposition/
Best Practices : Time and Clock Handling
To ensure testability and deterministic behavior, all code that needs the current time should use an injected Clock rather than calling Instant.now() or DateTime.now() directly.
Why
- Direct calls to
Instant.now()orDateTime.now()create non-deterministic behavior - Testing requires brittle
mockkStaticthat can interfere across tests - Injected
Clockenables deterministic testing withClock.fixed(...) - Follows the dependency injection principle (no hidden dependencies)
Pattern
In ViewModels and classes with DI:
// Good: Clock injected via Hilt
class MyViewModel @Inject constructor(
private val clock: Clock,
// other dependencies...
) : BaseViewModel<...>(...) {
private fun handleSaveClick() {
val item = Item(
createdAt = clock.instant(),
// ...
)
}
}
// Bad: Direct call creates hidden dependency
class MyViewModel @Inject constructor(
// missing Clock...
) : BaseViewModel<...>(...) {
private fun handleSaveClick() {
val item = Item(
createdAt = Instant.now(), // โ Non-testable
// ...
)
}
}In extension functions and utilities:
// Good: Accept Clock as parameter
fun SomeState.getRevisionDate(
originalItem: Item?,
clock: Clock,
): Instant = originalItem?.revisionDate ?: clock.instant()
// Bad: Hidden dependency on system clock
fun SomeState.getRevisionDate(
originalItem: Item?,
): Instant = originalItem?.revisionDate ?: Instant.now() // โTesting
// Good: Fixed clock for deterministic tests
private val FIXED_CLOCK: Clock = Clock.fixed(
Instant.parse("2023-10-27T12:00:00Z"),
ZoneOffset.UTC,
)
@Test
fun `test time-dependent logic`() = runTest {
val viewModel = MyViewModel(
clock = FIXED_CLOCK,
// ...
)
// Test with predictable time
}
// Bad: Static mocking is fragile
mockkStatic(Instant::class) // โ Avoid
every { Instant.now() } returns fixedInstantClock Provider
The Clock is provided via Hilt in CoreModule:
@Provides
@Singleton
fun provideClock(): Clock = Clock.systemDefaultZone()Reference: core/src/main/kotlin/com/bitwarden/core/di/CoreModule.kt
File: network/README.md
Network module
A client library for communicating with the Bitwarden web API.
Contents
Compatibility
- Minimum SDK: 29 (Android 10)
- Target SDK: 37 (Android 17)
File: ui/README.md
Data module
An Android library containing common UI components, types, and utilities.
Contents
Compatibility
- Minimum SDK: 29 (Android 10)
- Target SDK: 37 (Android 17)
Theme
Icons & Illustrations
Naming Convention
All drawables should be named with the appropriate prefix to identify what they are and how they are intended to be used.
| Prefix | Description |
|---|---|
bg_ |
backgrounds |
gif_ |
gifs |
ic_ |
Icons |
ill_ |
Illustrations |
img_ |
Raster Images |
logo_ |
Brand Imagery |
Multi-tonal Illustrations
The app supports light mode, dark mode and dynamic colors. Most icons in the app will display correctly using tinting but multi-tonal icons and illustrations require extra processing in order to be displayed properly with dynamic colors.
All illustrations and multi-tonal icons require the svg paths to be tagged with the name attribute in order for each individual path to be tinted the appropriate color. Any untagged path will not be tinted and the resulting image will be incorrect.
The supported tags are as follows:
- outline
- primary
- secondary
- tertiary
- accent
- logo
- navigation
- navigationActiveAccent