Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use python to control Android phone

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to use python to control Android phones, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to control Android phones with python. Let's take a look.

I. introduction

ADB (Android Debug Bridge) is a command line tool (CLI) that can be used to control and communicate with Android devices. You can perform many actions, such as installing applications, debugging applications, finding hidden functions, and connecting directly to the device using a shell. To enable ADB, your device must first unlock the developer options and enable USB debugging. To unlock developer options, you can go to device settings, and then scroll down to the about section to find the build number of the current software on the device. Click the build number 7 times to enable the developer option. You can then go to the developer options panel in the settings and enable USB debugging from there. Now, the only other thing you need to do is connect the device to your computer's USB cable.

This is today's journey:

1. Installation requirements

two。 Introduction

3. The basis for scripting

4. Create a selfie timer

5. Build a definition searcher

II. Installation requirements

The first of the two things we need to install is the ADB tool on the computer. It is automatically bundled with Android Studio, so if you already have it, don't worry about it.

After installing the ADB tool, you need to get the python library, which we will use to interface with ADB and our devices. You can install the pure-python-adb library using pip install pure-python-adb.

Optional: to make it easier for us to develop scripts, we can install an open source program called scrcpy, which allows us to display and control our android devices on our computers using the mouse and keyboard. If you are using Windows, extract the zip file into a directory, and then add this directory to your path. In this way, we can access the program from anywhere on the system by typing scrcpy in the terminal window.

III. Getting started

Now that we have all the dependencies installed, we can start ADB and connect the device. First, connect the device to the PC using a USB cable, and if USB debugging is enabled, a message pops up asking if PC can control the device, just answer yes. Then on your PC, open a terminal window and start the ADB server by typing adb start-server. This should print out the following message:

Daemon not running; starting now at tcp:5037

Daemon started successfully

If you also have scrcpy installed, you can start it by typing * * scrcpy in the terminal. However, this works only when you add it to the path, otherwise you can open the executable by changing the terminal directory to the directory where scrcpy is installed and typing scrcpy.exe**. Hopefully all goes well, you should be able to see your device on PC and be able to control it using the mouse and keyboard.

Now we can create a new python file and check to see if we can use the library to find the connected device:

Rom ppadb.client import Client as AdbClientif _ _ name__ = ='_ main__': client = AdbClient (host= "127.0.0.1", port=5037) # Default is "127.0.0.1" and 5037 devices = client.devices () if len (devices) = 0: print ('No devices') quit () device = devices [0] print (f'Connected to {device}')

Here, we import the AdbClient class and use it to create a client object. Then we can get a list of connected devices. Finally, we get the first device from the list (usually the only device if only one device is connected).

IV. The basis of scripting

The main way we want to connect to the device is to use a shell, in which we can send commands to simulate a touch at a specific location or slide from A to B. To simulate screen touch (tap), we first need to work to understand how the screen coordinates work. To help solve these problems, we can activate the pointer position setting in the developer options. After activation, no matter where you touch on the screen, you can see the coordinates of the point displayed at the top.

The figure shows how the coordinate system works

The upper left corner of the display screen has * x and y coordinates (0P0), respectively, and the coordinates in the lower right corner are the maximum possible values of x and y *.

Now that we know how the coordinate system works, we need to check the different commands that can be run. I have a list of commands below and how to use them for quick reference:

Input tap x yInput text "hello world!" Input keyevent eventIDHere is a list of some common eventID's:3: home button4: back button5: call6: end call24: volume up25: volume down26: turn device on or off27: open camera64: open browser66: enter67: backspace207: contacts220: brightness down221: brightness up277: cut278: copy279: paste 5. Create a selfie timer

Now that we know what we can do, let's get started. In the first example, I'll show you how to create a quick selfie timer. First, we need to import our library and create a connect function to connect to our device:

Import timefrom ppadb.client import Client as AdbClientdef connect (): client = AdbClient (host= "127.0.0.1", port=5037) # Default is "127.0.0.1" and 5037 devices = client.devices () if len (devices) = 0: print ('No devices') quit () device = devices [0] print (f'Connected to {device}') return device, client

You can see that the connect function is the same as the previous example of how to connect to a device, except here we return the device and client objects for later use.

If _ _ name__ ='_ _ main__': device, client = connect () # open up camera app device.shell ('input keyevent 27') # wait 5 seconds time.sleep (5) # take a photo with volume up device.shell (' input keyevent 24') print ('Taken a photocatalyst')

In our main code, we can call the connect function to retrieve the device and client objects. From there we can open the camera app, wait 5 seconds and take a picture. It's really that simple! As I said before, this is just copying what you usually do, so if you do it manually and write down the steps first, it's best to think about how to do it.

Create a definition searcher

Now, we can do something more complicated, which is to ask the browser to find the definition of a particular word and take a screenshot to save it on our computer.

The basic flow of the program is as follows:

1. Open the browser

two。 Click the search bar

3. Enter search query

4. Wait a few seconds.

5. Take a screenshot and save it

However, before we begin, you need to find the coordinates of the search bar in the default browser, and you can easily find them using the method I suggested earlier. To me, they are (440200).

First, we will have to import the same library as before, and we will also have the same connect method.

Import timefrom ppadb.client import Client as AdbClientdef connect (): client = AdbClient (host= "127.0.0.1", port=5037) # Default is "127.0.0.1" and 5037 devices = client.devices () if len (devices) = 0: print ('No devices') quit () device = devices [0] print (f'Connected to {device}') return device, client

In our main function, we can call the connect function and assign a variable to the * x and y * coordinates of our search bar. Note that this is a string, not a list or tuple, so we can easily merge the coordinates into our shell command. We can also get input information from users to see the definition of which word they want:

If _ _ name__ ='_ _ main__': device, client = connect () search_bar = '440 200' # x y query = input (' What word do you want to find the definition of:') search_query = f'what is the definition of {query}'

We will add the query to the complete sentence and search for it so that we can always get the definition. After that, we can open a browser and enter the search query into the search bar, as follows:

Device.shell ('input keyevent 64') time.sleep (0.25) # wait for browser to loaddevice.shell (f'input tap {search_bar}') device.shell (f'input text "{search_query}") # make sure you have the quotation marks around your textdevice.shell ('input keyevent 66') time.sleep (3) # wait for results to load

Here, we use eventID 66 to simulate the press of the input key to perform the search. If necessary, you can change the wait time as needed.

Finally, we will use the screencap method on the device object to take a screenshot, which can then be saved as a * .png * file:

Screenshot = device.screencap () with open ('result.png',' wb') as f: # save the screenshot as result.png f.write (screenshot) print ('Saved screenshotgun')

Here, we have to open the file in write byte mode, because the screencap method returns bytes that represent the image.

If everything goes according to plan, there should be a quick script to search for specific words.

This is the end of the article on "how to use python to control Android phones". Thank you for reading! I believe you all have a certain understanding of "how to use python to control Android phones". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report