Skip to content

Android

Information

Join the global Android community of millions of users and developers who collaborate to improve the open-source mobile operating system, giving you endless possibilities to customize your device. Unleash your creativity and make your smartphone, tablet, or smartwatch truly your own with the endless array of apps and features available on Android, tailored to fit your unique needs and preferences. Our job at KBVE will be to provide you with everything you need to deploy your own Android application on almost any device!

Cheatsheet

The ADB cheatsheet is an essential resource for navigating and managing Android operating systems and applications via the Android Debug Bridge (ADB). It offers a comprehensive list of basic commands that facilitate various tasks such as installing apps, debugging issues, and accessing device logs. While the cheatsheet covers a wide range of functionalities, it’s important to note that some commands require root access, and certain Android versions may necessitate specific tweaks to the standard commands. This makes the cheatsheet a versatile and indispensable tool for both novice users and experienced developers working with Android devices.

Device Commands

Android ADB Device commands are commands that you can use to control the Android device over USB from a computer. You can use them to list all devices, restart server and reboot!

  • adb devices - List all connected devices.

    • adb devices -l - Query additional information from devices.
    • adb get-state - Information on the device state.
    • adb get-serialno - Query the device serial number.
  • adb root - Launch module adbd with root permission.

    • Error 1: adbd cannot run as root in production builds
      • Resolution:
  • adb start-server - Start the adb server.

  • adb kill-server - Terminate the adb server.

  • adb reboot - Restart the current device.

  • adb help - Display additional information.

Shell

Warning: Shell commands can brick your operating system, so make sure to double check them before running.

ADB shell is a command-line interface that you can use to access the shell and run various commands on your Android device. You can use ADB shell commands to perform actions such as changing the resolution of your device display, uninstalling bloatware or system apps, enabling and disabling features, modifying the system files, ect..

Remember to keep a backup of the commands that you run via shell, I recommend creating a log.txt file and output all the commands to that file.

  • adb shell - Launch the shell terminal for the device.
  • adb -s $deviceString $deviceCommand - Send the $deviceCommand to a specific device named $deviceString
  • adb shell pwd - Command to list current directory.
  • adb shell ls - Command to list all the directory contents of the device.
    • adb shell ls -s - Additional size information.
    • adb shell ls -R - Recursion of the folders.
  • adb shell netstat - Query the TCP information
  • adb shell dumpsys - An android tool that dumps information related to system services.
    • adb shell dumpsys iphonesybinfo - Query the IMEI information.
    • adb shell dumpsys battery - Query battery information.
      • adb shell dumpsys battery set level $v - Device battery level from 0 to 100.
      • adb shell dumpsys battery reset - Reset the device battery.
    • adb shell dumpsys activity $package - Query activity of package.
  • adb shell pm list features - Query device features.
  • adb shell service list - Query device services.
  • adb shell wm - ◈Null
    • adb shell wm size - Current device screen resolution.
      • adb shell wm size $WxH - Change device screen resolution.
      • adb shell wm size reset - Reset device screen resolution.
    • adb shell wm density - ◈Null
      • adb shell wm density reset - Reset device density.
  • adb shell ps - Query process status on the device.
  • exit - To exit ADB.

Key Events

Android Key Events - A quick breakdown for each event and how the operating system handles them.

Generic Android Keyevents:

  • adb shell input keyevent

    • adb shell input keyevent 0 - Keycode 0
    • adb shell input keyevent 1 - Soft Left
    • adb shell input keyevent 2 - Soft Right
    • adb shell input keyevent 3 - Home Button Event.
    • adb shell input keyevent 4 - Back Button Event.
    • adb shell input keyevent 5 - Call Event.
    • adb shell input keyevent 6 - End Call / Hangup Event.
    • Events 7 to 18 are generic cell phone events.
      • adb shell input keyevent 7 - Keycode 0
      • adb shell input keyevent 8 - Keycode 1 aka Number 1
      • adb shell input keyevent 9 - Keycode 2 aka Number 2
      • adb shell input keyevent 10 - Keycode 3 aka Number 3
      • adb shell input keyevent 11 - Keycode 4 aka Number 4
      • adb shell input keyevent 12 - Keycode 5 aka Number 5
      • adb shell input keyevent 13 - Keycode 6 aka Number 6
      • adb shell input keyevent 14 - Keycode 7 aka Number 7
      • adb shell input keyevent 15 - Keycode 8 aka Number 8
      • adb shell input keyevent 16 - Keycode 9 aka Number 9
      • adb shell input keyevent 17 - STAR Key
      • adb shell input keyevent 18 - Pound Key
  • Koltin: open class KeyEvent: InputEvent, Parcelable

  • Java: public class KeyEvent extends InputEvent implements Parcelable


Android Data Storage

In Android, there are several ways to store data persistently. The choice of storage mechanism depends on the nature of the data and the requirements of the app. Below are the primary methods for data storage in Android:

Comparison of Storage Options

Storage MethodVisibilityPersistenceComplexityBest For
SharedPreferencesPrivateUntil app uninstallLowSmall key-value pairs
Internal StoragePrivateUntil app uninstallLowPrivate files
External StoragePublicUntil manually deletedMediumLarge/shared files
SQLite DatabasePrivateUntil app uninstallHighStructured data
RoomPrivateUntil app uninstallMedium-HighStructured data with compile-time safety

When choosing a storage method, consider the type of data you’re storing, how much data you need to store, the required level of security, and the complexity you’re willing to manage in your app.

  1. SharedPreferences

SharedPreferences is a framework that allows you to save and retrieve key-value pairs of primitive data types.

Use Cases

  • Storing user preferences.
  • Saving settings or configuration data.

Advantages:

  • Simple to use for small amounts of data
  • Data persists across app restarts

Disadvantages:

  • Not suitable for large or complex data structures
  • Not encrypted by default

Java Code Example

// Saving data to SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key_name", "value");
editor.apply();

// Retrieving data from SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String value = sharedPref.getString("key_name", "default_value");
  1. Internal Storage

Internal Storage is used to store private data within the device’s internal memory.

Use Cases

  • Storing sensitive data.
  • Files that should not be accessible to other apps.

Advantages:

  • Data is private to the app.
  • Files are removed when the app is uninstalled.

Disadvantages:

  • Limited by device storage.
  • Not easily accessible for backup.

Java Code Example

// Writing to internal storage
String filename = "myfile";
String fileContents = "Hello, World!";
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(fileContents.getBytes());
fos.close();

// Reading from internal storage
FileInputStream fis = openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
    sb.append(line);
}
String fileContents = sb.toString();
fis.close();
  1. External Storage

External Storage is used to store public data on the shared external storage. It’s typically used for storing larger files.

Use Cases

  • Storing media files (images, videos, audio)
  • Documents that need to be shared with other apps.

Advantages:

  • Larger storage capacity
  • Files can be shared with other apps

Disadvantages:

  • Not secure, as other apps can access the files
  • Files may remain after app uninstallation

Permissions

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

Java Code Example

// Writing to external storage
String filename = "myfile";
String fileContents = "Hello, World!";
File file = new File(getExternalFilesDir(null), filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(fileContents.getBytes());
fos.close();

// Reading from external storage
File file = new File(getExternalFilesDir(null), filename);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
    sb.append(line);
}
String fileContents = sb.toString();
fis.close();
  1. SQLite Database

SQLite is a lightweight relational database embedded within Android.

Use Cases

  • Structured data storage.
  • Complex querying requirements.
  • Managing complex data relationships

Advantages:

  • Efficient for complex queries and large datasets
  • Supports transactions and data integrity

Disadvantages:

  • More complex to set up and use compared to other options
  • Overkill for simple data storage needs

Java Code Example

// Creating a database helper
public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "mydatabase.db";
    private static final int DATABASE_VERSION = 1;

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS mytable");
        onCreate(db);
    }
}

// Using the database helper
MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();

// Inserting data
ContentValues values = new ContentValues();
values.put("name", "John Doe");
long newRowId = db.insert("mytable", null, values);

// Querying data
Cursor cursor = db.query("mytable", new String[]{"id", "name"}, null, null, null, null, null);
while (cursor.moveToNext()) {
    long itemId = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
    String itemName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
}
cursor.close();
db.close();
  1. Room Database

Room is an abstraction layer over SQLite that provides a more robust database access while harnessing the full power of SQLite.

Use Cases:

  • When you need a robust database solution but want to avoid the complexity of raw SQLite

Advantages:

  • Compile-time verification of SQL queries
  • Convenient annotations to define database structure
  • Easy integration with other Architecture components

Disadvantages:

  • Adds additional dependencies to your project
  • May be overkill for very simple data storage needs

Java Code Example

// Define Entity
@Entity(tableName = "user")
public class User {
    @PrimaryKey
    public int id;
    public String name;
}

// Define DAO
@Dao
public interface UserDao {
    @Insert
    void insert(User user);

    @Query("SELECT * FROM user WHERE id = :id")
    User getUserById(int id);
}

// Define Database
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

// Using Room
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "mydatabase").build();
UserDao userDao = db.userDao();

// Inserting data
User user = new User();
user.id = 1;
user.name = "John Doe";
userDao.insert(user);

// Querying data
User user = userDao.getUserById(1);
  1. Content Providers

Content Providers manage access to a structured set of data. They encapsulate the data and provide mechanisms for defining data security.

Use Cases

  • Sharing data between different applications.
  • Accessing data from other applications.

Java Code Example

// Querying a content provider
Cursor cursor = getContentResolver().query(
        ContactsContract.Contacts.CONTENT_URI,
        null,
        null,
        null,
        null);

while (cursor.moveToNext()) {
    String id = cursor.getString(
            cursor.getColumnIndex(ContactsContract.Contacts._ID));
    String name = cursor.getString(
            cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();