Monday, January 11, 2016

Interact Android device and take screen short using python script

Here a complete python script which will be used to interact with device and take screen short.
Functionality of this scripit
  1. Save screenshort
  2. Lock the screen
  3. Unlock the screen
  4. Send touches to screen
to run this program, you need install python and tkinter ui plugin.
Save following code in screenshot.py: 
import tkinter as tk
import sys
import signal
import string
import os
import subprocess
import time
from tkinter import W
from adb import ADB
import threading
import time
class Application(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()     

    def createWidgets(self):
        self.moving = False
        self.close = tk.Button(self, text="Exit", fg="red",
                                            command=root.destroy)

        self.download = tk.Button(self, text="Save Screen", fg="blue", bg="yellow",
                                            command=self.takeScreenShort)
        self.filelabel = tk.Label(self, text="File Name")
        self.lock = tk.Button(self, text="Lock", fg="blue",
                                            command=self.lock_screen) 
         self.unlock = tk.Button(self, text="UnLock", fg="blue",
                                            command=self.unlock_screen)

        self.result = tk.Label(self, textvariable=res)     
        self.enter = tk.Entry(self, textvariable=filename)
        self.frame = tk.Frame(self, width=280, height=500, background='white')
        self.frame.pack_propagate(0)     
        self.img = tk.PhotoImage(file="dummy.png")
        self.img = self.img.subsample(4, 4)           
        self.r = tk.Label(self.frame, image=self.img) 
        self.r.bind("<1>", self.OnMouseDown)
        self.r.bind("<B1-Motion>", self.OnMotion)
        self.r.bind("<ButtonRelease-1>", self.OnMouseRelease)
        self.r.pack();
        
        self.filelabel.grid(row=0, column=0)
        self.enter.grid(row=0, column=1)
        self.download.grid(row=1, column=1)
        self.close.grid(row=1, column=1)
        self.lock.grid(row=1, column=2)
        self.unlock.grid(row=1, column=3)
        self.result.grid(row=2, column=1) 
         self.frame.grid(row=4, column=1); 
         self.thread = threading.Thread(target=self.run, args=())
        self.thread.daemon = True                            # Daemonize thread
        self.thread.start() 

        self.thread1 = threading.Thread(target=self.run1, args=())
        self.thread1.daemon = True                            # Daemonize thread
        self.thread1.start()  
 
     def OnMouseDown(self, event):
        #print("frame coordinates: %s/%s" % (event.x*4, event.y*4))
        #print("root coordinates: %s/%s" % (event.x_root, event.y_root))
        cm = "adb shell input tap "+str(event.x*4)+" "+str(event.y*4)   
        #print("Sending key events....");
        sm = subprocess.Popen(cm.split())
        #self.takeScreenShort()

    def say_hi(self):
        print("hi there, everyone!")

    def OnMotion(self, event):
        deltax =  event.x_root - event.x
        deltay =  event.y_root- event.y
        #x = self.winfo_x() + deltax
        #y = self.winfo_y() + deltay
        #self.geometry("+%s+%s" % (x, y))
        self.moving = True
        print("move...%s %s delta %s %s" %(event.x*4, event.y*4, deltax*4, deltay*4));
        self.movecommand = "adb shell input swipe "+ str(event.x*4)+" "+str(event.y*4)+" "+str(deltax*4)+" "+str(deltay*4)
        #print("Locking....");    

    def OnMouseRelease(self, event):
        if(self.moving):
            s = subprocess.Popen(self.movecommand.split())
            self.moving = False  

    def run(self):   
        while True:
            # Do something
            #print('calling #print...')
            obj.screenShot("temp.png") 
     def run1(self):   
        while True:
            # Do something
            try:
                #print('setup image...')
                self.img1 = tk.PhotoImage(file="temp.png")
                self.img1 = self.img1.subsample(4, 4)
                self.r.configure(image = self.img1)
                self.r.image = self.img1
                time.sleep(1)
            except:
                self.error="err";
            #time.sleep(1) 
     def lock_screen(self):
        c = 'adb shell input keyevent 26'       
        #print("Locking....");
        s = subprocess.Popen(c.split())
      
    def unlock_screen(self):
        c1 = 'adb shell input keyevent 82'      
        #print("Un-Locking....");
        s = subprocess.Popen(c1.split()) 
     def takeScreenShort(self):
        #print("Capturing....");
        obj.screenShot(filename.get()+".png")
        #res.set("Saved temp.png successfully");
        self.img1 = tk.PhotoImage(file="temp.png")
        self.img1 = self.img1.subsample(4, 4)
        self.r.configure(image = self.img1)
        self.r.image = self.img1 
 root = tk.Tk()
obj = ADB()
filename = tk.StringVar()
res = tk.StringVar()
app = Application(master=root)
app.master.title("Screen Capture")
app.master.minsize(450, 250)
app.mainloop() 
adb.py
  
class ADB(object):

    def call(self, command):
        command_result = ''
        command_text = 'adb %s' % command
        results = os.popen(command_text, "r")
        while 1:
            line = results.readline()
            if not line: break
            command_result += line
        return command_result

    def devices(self):
        result = self.call("devices")
        devices = result.partition('\n')[2].replace('\n', '').split('\tdevice')
        return [device for device in devices if len(device) > 2]

    def upload(self, fr, to):
        result = self.call("push " + fr + " " + to)
        return result
    
    def get(self, fr, to):
        result = self.call("pull " + fr + " " + to)
        return result

    def install(self, param):
        data = param.split()
        if data.length == 1:
            result = self.call("install " + param[0])
        elif data.length == 2:
            result = self.call("install " + param[0] + " " + param[1])
        return result

    def uninstall(self, package):
        result = self.call("shell pm uninstall " + package)
        return result

    def clearData(self, package):
        result = self.call("shell pm clear " + package)
        return result

    def shell(self, command):
        result = self.call("shell " + command)
        return result
        
    def kill(self, package):
        result = self.call("kill " + package)
        return result

    def start(self, app):
        pack = app.split()
        result = "Nothing to run"
        if pack.length == 1:
            result = self.call("shell am start " + pack[0])    
        elif pack.length == 2:
            result = self.call("shell am start " + pack[0] + "/." + pack[1])
        elif pack.length == 3:
            result = self.call("shell am start " + pack[0] + " " + pack[1] + "/." + pack[2])
        return result

    def screen(self, res):
        result = self.call("am display-size " + res)
        return result

    def dpi(self, dpi):
        result = self.call("am display-density " + dpi)
        return result

    def screenRecord(self, param):
        params = param.split()
        if params.length == 1:
            result = self.call("shell screenrecord " + params[0])
        elif params.length == 2:
            result = self.call("shell screenrecord --time-limit " + params[0] + " " + params[1])
        return result

    def screenShot(self, output):
        self.call("shell screencap -p /sdcard/temp_screen.png")
        self.get("/sdcard/temp_screen.png", output)

        self.call("shell rm /sdcard/temp_screen.png")

And now run your python script.. Happy coding...