[Andriod] Universal python script to install and uninstall apk using adb command

Article directory

  • 1 Introduction
  • 2. Connect the device
  • 3. Install apk through adb from your local machine
  • 4. Uninstall the apk from the local machine through adb

1. Preface

If you don’t know how to use adb, please read the previous article.
[Andriod] Do you know 3 ways to connect a real device or emulator when debugging an Android phone with adb?

2. Connect the device

import os #os module in python standard library

"""
Use python to write a script to automatically start the app
"""


class AdbConnect:
    #If the environment variable is configured, it can be empty here. I have not configured it, so I have to call adb from the root directory.
    ANDROID_SDB_ABS_PATH = "F:\dev_tools\android-sdk_r24.4.1-windows\android-sdk-windows\platform-tools"

    # Constructor
    def __init__(self, device_name):
        # During initialization, the device_name passed in represents the name of the simulator (the USB connection passes the device number, the simulator passes the ip port)
        self.device_name = device_name

    # Connect device
    def adb_connect(self):
        # (1) Both the popen and system methods can execute instructions, and popen can accept return objects. Here you need to view the list of connected devices, and save the queried connected device results in the variable device_list.
        device = os.popen(self.ANDROID_SDB_ABS_PATH + "adb devices")
        device_list = device.read()
        print("Connected device list 1:\
{}".format(device_list))

        # (2) Determine whether the device name is in the connected device list. If not, call the method of connecting the device, and then query whether the connection status is successful. If it is, directly query the connected device and status.
        # Determine whether the name of the connected device is in the connected device list
        if self.device_name not in device_list:
            self.connection_equipment() # Call the method of connecting the device
            # print(self.query_device_list())
            return self.query_device_list() # Query the connection device and status
        else:
            # print(self.query_device_list())
            return self.query_device_list() # Query the connection device and status

    # Query the list of connected devices (you can query the status of the connected device based on the name of the connected device)
    def query_device_list(self):
        device = os.popen(self.ANDROID_SDB_ABS_PATH + "adb devices")
        # popen and system can execute instructions, popen can accept return objects

        device_list = device.read()
        # Read the results returned by adb devices

        print("Connected device list 2:\
{}".format(device_list))
        #Print the list of connected devices

        con_attached_list = device_list[device_list.rfind(self.device_name):-2]
        # Intercept the string from the name of the connected device to the connection status part from the connected device list. The last two lines of the string in the connected device list are empty, so take -2
        # print(con_attached_list)# FJH7N19131000457 device

        dve_len = len(self.device_name)
        # Calculate the length of the connected device dve_len, and determine the location to intercept the connection status based on this length
        # print(dve_len) # 16

        dve_ps = con_attached_list.rfind(self.device_name)
        # Take out the connected device at the starting position of the connected device list dve_ps
        # print(dve_ps) # 0

        con_attached = con_attached_list[dve_ps + dve_len + 1:dve_ps + dve_len + 7]
        # Intercept the connection status of the connected device, add the length of the connected device dve_len + 1 from the starting position dve_ps (all spaces between the device name and the status + 1)
        # Extract 6 characters from the beginning of the state: dve_ps + dve_len + 7. Later, you only need to determine whether the intercepted result of this part is device.
        #print(con_attached)# device

        if self.device_name in con_attached_list and con_attached == 'device':
        
            # Determine whether the name of the connected device is in the connected device list and whether the status is device
            return "adb has connected to the device {}".format(self.device_name)
        elif self.device_name in con_attached_list and con_attached != 'device':
            return "The status of the connected device is abnormal\
{}".format(con_attached_list)
        elif self.device_name not in con_attached_list:
            return "The device is not connected, please check"
        else:
            return "Unknown error"

    def connection_equipment(self):
        os.system("adb connect {}".format(self.device_name))
        # Use adb connect to connect to the device


if __name__ == '__main__':
    a = AdbConnect("FJH7N19131000457")
    s = a.adb_connect()
    print(s)

Results of the

3. Install apk from the local machine through adb

import os
from adb_connect import AdbConnect


classAppInstall:

    def __init__(self, device_name, apk_path, method=''):
        self.apk_path = apk_path # apk path
        self.install_method = method # Installed app method, regular installation (default), R (overlay installation), D (downgrade installation)
        self.device = device_name #The name of the device (the USB connection passes the device number, the simulator passes the ip port)

    def app_install(self): # Installation method
        adb_cont = AdbConnect(self.device) #Initialize the adb connection class and pass in the device name
        device_status = adb_cont.adb_connect() # Call the adb connection class method to connect to the device

        if "The device is connected" in device_status: # If the device is connected, perform the following steps to install the app
            print(device_status) #Print the list of connected devices
            try:
                if self.install_method == '': # Determine whether the incoming installation method is empty
                    self.app_direct_install() # Call the regular method of installing app
                elif self.install_method == 'R': # The R parameter is passed in, indicating overwriting the installation
                    self.app_replace_install() #Call the method to overwrite the installation
                elif self.app_downgrade_install() == 'D': # The D parameter is passed in, indicating downgrade installation
                    self.app_downgrade_install() # Call the downgrade installation method
                else:
                    pass
            except Exception as e: # If there is an error, print the error
                print(e)
        else:
            print(device_status) #If the device is not connected, print the list of connected devices

    def app_direct_install(self): # Conventional method of installing app
        install = os.popen(
            AdbConnect.ANDROID_SDB_ABS_PATH + "adb install {}".format(self.apk_path)) # Execute adb install command for regular installation
        install_re = install.read() # Assign the installation result to the variable install_re
        if 'Success' in install_re[-9:-1]: # The part that determines the installation result contains Success
            return print("app has been installed successfully") # Print app has been installed successfully
        else:
            return print("app was not installed successfully, installation result: {}\
Overwriting or downgrading installation requires adding additional installation parameters during initialization: R (overlay installation), D (downgrade installation)".format(install_re[-41:- 2]))

    def app_replace_install(self): # Override installation method
        install = os.popen(
            AdbConnect.ANDROID_SDB_ABS_PATH + "adb install -r {}".format(self.apk_path)) # Execute adb install -r command to overwrite the installation
        install_re = install.read()
        if 'Success' in install_re[-9:-1]:
            return print("app installed successfully")
        else:
            return print("app was not installed successfully, installation result: {}\
Overwriting or downgrading installation requires adding additional installation parameters during initialization: R (overlay installation), D (downgrade installation)".format(install_re[-41:- 2]))

    def app_downgrade_install(self): # Method of downgrade installation
        install = os.popen(
            AdbConnect.ANDROID_SDB_ABS_PATH + "adb install -r -d {}".format(self.apk_path)) # Execute adb install -r -d command to downgrade the installation
        install_re = install.read()
        if 'Success' in install_re[-9:-1]:
            return print("app installed successfully")
        else:
            return print("app was not installed successfully, installation result: {}\
Overwriting or downgrading installation requires adding additional installation parameters during initialization: R (overwrite installation), D (downgrade installation)".format(install_re[-41:- 2]))


if __name__ == '__main__':
    # a = AppInstall(r"D:\ac\APP\tools\yibijizhang.apk", "127.0.0.1:62001", method="R")
    # a.app_install()

    #b = AppInstall("127.0.0.1:62001", r"D:\download\meituan10.10.403.apk")
    #b.app_install()

    c = AppInstall("FJH7N19131000457", r"F:\my_tools\DigiFinex_V2023.10.12_debugT.apk","R")
    c.app_install()

Results of the

4. Uninstall apk from the local machine through adb

import os
from adb_connect import AdbConnect



classAppUninstall:
    def __init__(self, device_name):
        self.device = device_name #The name of the device (the USB connection passes the device number, the simulator passes the ip port)
        con = AdbConnect(self.device) # Instantiate the class of the connection device
        con.adb_connect() # Call the method of connecting the device

    def app_uninstall(self):
        app_pack_list = self.app_packages_three() # Call the method to query third-party package names and get a list containing the names of all third-party installation packages
        if app_pack_list: # Determine whether the list of third-party installation package names is not empty
            print("Installed app package name list:\
{}".format(app_pack_list)) # Print the list of third-party installation package names
            uninstall_app_pack = input("Please enter the package name of the app you want to delete:") # Enter the package name you want to delete
            if uninstall_app_pack in app_pack_list: # Determine whether the package name entered to be deleted is in the query result
                un_re = os.popen(AdbConnect.ANDROID_SDB_ABS_PATH + "adb uninstall {}".format(
                    uninstall_app_pack)) # Use adb uninstall <package name> command to uninstall app
                uninstall_re = un_re.read() # Read the results of uninstallation
                uninstall_result = uninstall_re[:7] # Intercept the first 7 letters of the uninstall result
                if uninstall_result == 'Success': # Determine the 7-digit letter of the uninstall result as Success
                    print("app uninstalled successfully") # Print app uninstalled successfully
                else:
                    print("Unknown error") # Print unknown error
            else:
                print("The package name you entered does not exist, please check!") # If the entered package name does not exist in the package name list, prompt
        else:
            print("No third-party installed app found") # Prompt if the list of third-party installation package names is empty

    def app_packages_three(self):
        packages = os.popen(AdbConnect.ANDROID_SDB_ABS_PATH + "adb shell pm list packages -3") # adb command to query the package name installed by a third party
        app_packages = packages.read() # Read the app package name installed by a third party
        print(app_packages)

        app_pack_str = app_packages.replace('\
', '') # Read the result and replace the newline character \
 with empty and delete the newline character
        app_pack_list = app_pack_str.split("package:") # Use the split method to slice and get a list of package names.
        print(app_pack_list)

        app_pack_list.pop(0) # Use the pop method of the list to delete the first data in the package name list
        return app_pack_list # Return the package name list


if __name__ == '__main__':
    a = AppUninstall("FJH7N19131000457")
    a.app_uninstall()

Results of the