private void Update() { try { this.prop.Clear(); if (this.device.State != DeviceState.ONLINE) { return; } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, false, "getprop"); string prop = Adb.ExecuteAdbCommand(adbCmd); string[] lines = prop.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < lines.Length; i++) { string[] entry = lines[i].Split(new string[] { "[", "]: [", "]" }, StringSplitOptions.RemoveEmptyEntries); if (entry.Length == 2) { this.prop.Add(entry[0], entry[1]); } } } catch (Exception ex) { Logger.WriteLog(ex.Message, "Using: getprop in BuildProp.cs", ex.StackTrace); } }
private void GetSuData() { if (this.device.State != DeviceState.ONLINE) { this.version = null; this.exists = false; return; } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, false, "su", "-v"); using (StringReader r = new StringReader(Adb.ExecuteAdbCommand(adbCmd))) { string line = r.ReadLine(); if (line.Contains("not found") || line.Contains("permission denied")) { this.version = "-1"; this.exists = false; } else { this.version = line; this.exists = true; } } }
private void Update() { try { this.prop.Clear(); if (this.device.State != DeviceState.ONLINE) { return; } string[] splitPropLine; AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, false, "getprop"); string prop = Adb.ExecuteAdbCommand(adbCmd); using (StringReader s = new StringReader(prop)) { while (s.Peek() != -1) { string temp = s.ReadLine(); if (temp.Trim().Length.Equals(0) || temp.StartsWith("*")) { continue; } splitPropLine = temp.Split(':'); //In case there is a line with ':' in the value, combine it if (splitPropLine.Length > 2) { for (int i = 2; i < splitPropLine.Length; i++) { splitPropLine[1] += ":" + splitPropLine[i]; } } for (int i = 0; i < 2; i++) { if (i == 0) { splitPropLine[i] = splitPropLine[i].Replace("[", ""); } else { splitPropLine[i] = splitPropLine[i].Replace(" [", ""); } splitPropLine[i] = splitPropLine[i].Replace("]", ""); } this.prop.Add(splitPropLine[0], splitPropLine[1]); } } } catch (Exception ex) { Logger.WriteLog(ex.Message, "Using: getprop in BuildProp.cs", ex.StackTrace); } }
/// <summary> /// Sets a build property value /// </summary> /// <remarks>If <paramref name="key"/> does not exist or device does not have root, returns false, and does not set any values</remarks> /// <param name="key">Build property key to set</param> /// <param name="newValue">Value you wish to set <paramref name="key"/> to</param> /// <returns>True if new value set, false if not</returns> public bool SetProp(string key, string newValue) { string before; if (!this.prop.TryGetValue(key, out before)) { return(false); } if (!this.device.HasRoot) { return(false); } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, true, "setprop", key, newValue); Adb.ExecuteAdbCommandNoReturn(adbCmd); Update(); string after; if (!this.prop.TryGetValue(key, out after)) { return(false); } if (newValue == after) { return(true); } return(false); }
/// <summary> /// Gets a Dictionary containing all the files and folders in the directory added as a parameter. /// </summary> /// <param name="location"> /// The directory you'd like to list the files and folders from. /// E.G.: /system/bin/ /// </param> /// <returns>See Dictionary</returns> public Dictionary <string, ListingType> GetFilesAndDirectories(string location) { if (location == null || string.IsNullOrEmpty(location) || Regex.IsMatch(location, @"\s")) { throw new ArgumentException("rootDir must not be null or empty!"); } Dictionary <string, ListingType> filesAndDirs = new Dictionary <string, ListingType>(); AdbCommand cmd = null; if (device.BusyBox.IsInstalled) { cmd = Adb.FormAdbShellCommand(device, true, "busybox", "ls", "-a", "-p", "-l", location); } else { cmd = Adb.FormAdbShellCommand(device, true, "ls", "-a", "-p", "-l", location); } using (StringReader reader = new StringReader(Adb.ExecuteAdbCommand(cmd))) { string line = null; while (reader.Peek() != -1) { line = reader.ReadLine(); if (!string.IsNullOrEmpty(line) && !Regex.IsMatch(line, @"\s")) { filesAndDirs.Add(line, line.EndsWith("/") ? ListingType.DIRECTORY : ListingType.FILE); } } } return(filesAndDirs); }
/// <summary> /// Updates Internal Device List /// </summary> /// <remarks>Call this before checking for Devices, or setting a new Device, for most updated results</remarks> public void UpdateDeviceList() { string deviceList = ""; this.connectedDevices.Clear(); deviceList = Adb.Devices(); if (deviceList.Length > 29) { using (StringReader s = new StringReader(deviceList)) { string line; while (s.Peek() != -1) { line = s.ReadLine(); if (line.StartsWith("List") || line.StartsWith("\r\n") || line.Trim() == "") { continue; } if (line.IndexOf('\t') != -1) { line = line.Substring(0, line.IndexOf('\t')); this.connectedDevices.Add(line); } } } } }
private DeviceState SetState() { string state = null; using (StringReader r = new StringReader(Adb.Devices())) { string line; while (r.Peek() != -1) { line = r.ReadLine(); if (line.Contains(this.serialNumber)) { state = line.Substring(line.IndexOf('\t') + 1); } } } if (state == null) { using (StringReader r = new StringReader(Fastboot.Devices())) { string line; while (r.Peek() != -1) { line = r.ReadLine(); if (line.Contains(this.serialNumber)) { state = line.Substring(line.IndexOf('\t') + 1); } } } } switch (state) { case "device": return(DeviceState.ONLINE); case "recovery": return(DeviceState.RECOVERY); case "fastboot": return(DeviceState.FASTBOOT); case "sideload": return(DeviceState.SIDELOAD); case "unauthorized": return(DeviceState.UNAUTHORIZED); default: return(DeviceState.UNKNOWN); } }
/// <summary> /// Releases all resources used by <see cref="AndroidController"/> /// </summary> /// <remarks>Needs to be called when application has finished using <see cref="AndroidController"/></remarks> public void Dispose() { if (Adb.ServerRunning) { Adb.KillServer(); Thread.Sleep(1000); } AndroidController.instance = null; }
private void UpdateMountPoints() { if (this.device.State != DeviceState.ONLINE) { this.systemMount = new MountInfo(null, null, MountType.NONE); return; } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, false, "mount"); using (StringReader r = new StringReader(Adb.ExecuteAdbCommand(adbCmd))) { string line; string[] splitLine; string dir, mount; MountType type; while (r.Peek() != -1) { line = r.ReadLine(); splitLine = line.Split(' '); try { if (line.Contains(" on /system ")) { dir = splitLine[2]; mount = splitLine[0]; type = (MountType)Enum.Parse(typeof(MountType), splitLine[5].Substring(1, 2).ToUpper()); this.systemMount = new MountInfo(dir, mount, type); return; } if (line.Contains(" /system ")) { dir = splitLine[1]; mount = splitLine[0]; type = (MountType)Enum.Parse(typeof(MountType), splitLine[3].Substring(0, 2).ToUpper()); this.systemMount = new MountInfo(dir, mount, type); return; } } catch { dir = "/system"; mount = "ERROR"; type = MountType.NONE; this.systemMount = new MountInfo(dir, mount, type); } } } }
/// <summary> /// Creates the resource directories. /// </summary> private void CreateResourceDirectories() { try { if (!Adb.ExecuteAdbCommand(new AdbCommand("version")).Contains(Adb.ADB_VERSION)) { Adb.KillServer(); Thread.Sleep(1000); ResourceFolderManager.Unregister(ANDROID_CONTROLLER_TMP_FOLDER); Extract_Resources = true; } } catch (Exception) { Extract_Resources = true; } ResourceFolderManager.Register(ANDROID_CONTROLLER_TMP_FOLDER); }
/// <summary> /// Forwards a port that remains until the current <see cref="AndroidController"/> instance is Disposed, or the device is unplugged /// </summary> /// <remarks>Only supports tcp: forward spec for now</remarks> /// <param name="device">Instance of <see cref="Device"/> to apply port forwarding to</param> /// <param name="localPort">Local port number</param> /// <param name="remotePort">Remote port number</param> /// <returns>True if successful, false if unsuccessful</returns> public static bool PortForward(Device device, int localPort, int remotePort) { bool success = false; AdbCommand adbCmd = Adb.FormAdbCommand(device, "forward", "tcp:" + localPort, "tcp:" + remotePort); using (StringReader r = new StringReader(ExecuteAdbCommand(adbCmd))) { if (r.ReadToEnd().Trim() == "") { success = true; } } return(success); }
/// <summary> /// Updates the instance of busybox /// </summary> /// <remarks>Generally called only if busybox may have changed on the device</remarks> public void Update() { this.commands.Clear(); if (!this.device.HasRoot || this.device.State != DeviceState.ONLINE) { SetNoBusybox(); return; } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, false, EXECUTABLE); using (StringReader s = new StringReader(Adb.ExecuteAdbCommand(adbCmd))) { string check = s.ReadLine(); if (check.Contains(string.Format("{0}: not found", EXECUTABLE))) { SetNoBusybox(); return; } this.isInstalled = true; this.version = check.Split(' ')[1].Substring(1); while (s.Peek() != -1 && s.ReadLine() != "Currently defined functions:") { } string[] cmds = s.ReadToEnd().Replace(" ", "").Replace("\r\r\n\t", "").Trim('\t', '\r', '\n').Split(','); if (cmds.Length.Equals(0)) { SetNoBusybox(); } else { foreach (string cmd in cmds) { this.commands.Add(cmd); } } } }
/// <summary> /// Gets a <see cref="ListingType"/> indicating is the requested location is a File or Directory /// </summary> /// <param name="location">Path of requested location on device</param> /// <returns>See <see cref="ListingType"/></returns> /// <remarks><para>Requires a device containing BusyBox for now, returns ListingType.ERROR if not installed.</para> /// <para>Returns ListingType.NONE if file/Directory does not exist</para></remarks> public ListingType FileOrDirectory(string location) { // if (!this.device.BusyBox.IsInstalled) // return ListingType.ERROR; AdbCommand isFile = Adb.FormAdbShellCommand(this.device, false, string.Format(IS_FILE, location)); AdbCommand isDir = Adb.FormAdbShellCommand(this.device, false, string.Format(IS_DIRECTORY, location)); if (Adb.ExecuteAdbCommand(isFile).Contains("1")) { return(ListingType.FILE); } else if (Adb.ExecuteAdbCommand(isDir).Contains("1")) { return(ListingType.DIRECTORY); } return(ListingType.NONE); }
//void PushFile(); //void PullFile(); /// <summary> /// Mounts connected Android device's file system as specified /// </summary> /// <param name="type">The desired <see cref="MountType"/> (RW or RO)</param> /// <returns>True if remount is successful, False if remount is unsuccessful</returns> /// <example>The following example shows how you can mount the file system as Read-Writable or Read-Only /// <code> /// // This example demonstrates mounting the Android device's file system as Read-Writable /// using System; /// using RegawMOD.Android; /// /// class Program /// { /// static void Main(string[] args) /// { /// AndroidController android = AndroidController.Instance; /// Device device; /// /// Console.WriteLine("Waiting For Device..."); /// android.WaitForDevice(); //This will wait until a device is connected to the computer /// device = android.ConnectedDevices[0]; //Sets device to the first Device in the collection /// /// Console.WriteLine("Connected Device - {0}", device.SerialNumber); /// /// Console.WriteLine("Mounting System as RW..."); /// Console.WriteLine("Mount success? - {0}", device.RemountSystem(MountType.RW)); /// } /// } /// /// // The example displays the following output (if mounting is successful): /// // Waiting For Device... /// // Connected Device - {serial # here} /// // Mounting System as RW... /// // Mount success? - true /// </code> /// </example> public bool RemountSystem(MountType type) { if (!this.device.HasRoot) { return(false); } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, true, "mount", string.Format("-o remount,{0} -t yaffs2 {1} /system", type.ToString().ToLower(), this.systemMount.Block)); Adb.ExecuteAdbCommandNoReturn(adbCmd); UpdateMountPoints(); if (this.systemMount.MountType == type) { return(true); } return(false); }
/// <summary> /// Pulls a full directory recursively from the device /// </summary> /// <param name="location">Path to folder to pull from device</param> /// <param name="destination">Directory on local computer to pull file to</param> /// <param name="timeout">The timeout for this operation in milliseconds (Default = -1)</param> /// <returns>True if directory is pulled, false if pull failed</returns> public bool PullDirectory(string location, string destination, int timeout = Command.DEFAULT_TIMEOUT) { AdbCommand adbCmd = Adb.FormAdbCommand(this, "pull", "\"" + (location.EndsWith("/") ? location : location + "/") + "\"", "\"" + destination + "\""); return(Adb.ExecuteAdbCommandReturnExitCode(adbCmd.WithTimeout(timeout)) == 0); }
/// <summary> /// Pushes a file to the device /// </summary> /// <param name="filePath">The path to the file on the computer you want to push</param> /// <param name="destinationFilePath">The desired full path of the file after pushing to the device (including file name and extension)</param> /// <param name="timeout">The timeout for this operation in milliseconds (Default = -1)</param> /// <returns>If the push was successful</returns> public bool PushFile(string filePath, string destinationFilePath, int timeout = Command.DEFAULT_TIMEOUT) { AdbCommand adbCmd = Adb.FormAdbCommand(this, "push", "\"" + filePath + "\"", "\"" + destinationFilePath + "\""); return(Adb.ExecuteAdbCommandReturnExitCode(adbCmd.WithTimeout(timeout)) == 0); }
/// <summary> /// Pulls a file from the device /// </summary> /// <param name="fileOnDevice">Path to file to pull from device</param> /// <param name="destinationDirectory">Directory on local computer to pull file to</param> /// /// <param name="timeout">The timeout for this operation in milliseconds (Default = -1)</param> /// <returns>True if file is pulled, false if pull failed</returns> public bool PullFile(string fileOnDevice, string destinationDirectory, int timeout = Command.DEFAULT_TIMEOUT) { AdbCommand adbCmd = Adb.FormAdbCommand(this, "pull", "\"" + fileOnDevice + "\"", "\"" + destinationDirectory + "\""); return(Adb.ExecuteAdbCommandReturnExitCode(adbCmd.WithTimeout(timeout)) == 0); }
private void RebootBootloaderThread() { Adb.ExecuteAdbCommandNoReturn(Adb.FormAdbCommand(this, "reboot", "bootloader")); }
private void RebootRecoveryThread() { Adb.ExecuteAdbCommandNoReturn(Adb.FormAdbCommand(this, "reboot", "recovery")); }
public void Delete(string path) { AdbCommand mkDir = Adb.FormAdbShellCommand(this.device, false, "rm", "-rf", "\"" + path + "\""); Adb.ExecuteAdbCommand(mkDir); }
internal static string Devices() { return(ExecuteAdbCommand(Adb.FormAdbCommand("devices"))); }
public bool MakeDirectory(string directory) { AdbCommand mkDir = Adb.FormAdbShellCommand(this.device, false, "mkdir", "\"" + directory + "\""); return(!Adb.ExecuteAdbCommand(mkDir).Contains("File exists")); }
internal static void KillServer() { ExecuteAdbCommandNoReturn(Adb.FormAdbCommand("kill-server")); }
/// <summary> /// Pulls a full directory recursively from the device /// </summary> /// <param name="location">Path to folder to pull from device</param> /// <param name="destination">Directory on local computer to pull file to</param> /// <returns>True if directory is pulled, false if pull failed</returns> public bool PullDirectory(string location, string destination) { AdbCommand adbCmd = Adb.FormAdbCommand(this, "pull", "\"" + (location.EndsWith("/") ? location : location + "/") + "\"", "\"" + destination + "\""); return(Adb.ExecuteAdbCommandReturnExitCode(adbCmd) == 0); }
/// <summary> /// Installs an application from the local computer to the Android device /// </summary> /// <param name="location">Full path of apk on computer</param> /// <returns>True if install is successful, False if install fails for any reason</returns> public bool InstallApk(string location) { return(!Adb.ExecuteAdbCommand(Adb.FormAdbCommand(this, "install", "\"" + location + "\""), true).Contains("Failure")); }
/// <summary> /// Pushes a file to the device /// </summary> /// <param name="filePath">The path to the file on the computer you want to push</param> /// <param name="destinationFilePath">The desired full path of the file after pushing to the device (including file name and extension)</param> /// <returns>If the push was successful</returns> public bool PushFile(string filePath, string destinationFilePath) { AdbCommand adbCmd = Adb.FormAdbCommand(this, "push", "\"" + filePath + "\"", "\"" + destinationFilePath + "\""); return(Adb.ExecuteAdbCommandReturnExitCode(adbCmd) == 0); }
/// <summary> /// Installs an application from the local computer to the Android device /// </summary> /// <param name="location">Full path of apk on computer</param> /// <param name="timeout">The timeout for this operation in milliseconds (Default = -1)</param> /// <returns>True if install is successful, False if install fails for any reason</returns> public bool InstallApk(string location, int timeout = Command.DEFAULT_TIMEOUT) { return(!Adb.ExecuteAdbCommand(Adb.FormAdbCommand(this, "install", "\"" + location + "\"").WithTimeout(timeout), true).Contains("Failure")); }
private void Update() { if (this.device.State != DeviceState.ONLINE) { this.acPower = false; this.dump = null; this.health = -1; this.level = -1; this.present = false; this.scale = -1; this.status = -1; this.technology = null; this.temperature = -1; this.usbPower = false; this.voltage = -1; this.wirelessPower = false; this.outString = "Device Not Online"; return; } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, false, "dumpsys", "battery"); this.dump = Adb.ExecuteAdbCommand(adbCmd); using (StringReader r = new StringReader(this.dump)) { string line; while (true) { line = r.ReadLine(); if (!line.Contains("Current Battery Service state")) { continue; } else { this.dump = line + r.ReadToEnd(); break; } } } using (StringReader r = new StringReader(this.dump)) { string line = ""; while (r.Peek() != -1) { line = r.ReadLine(); if (line == "") { continue; } else if (line.Contains("AC ")) { bool.TryParse(line.Substring(14), out this.acPower); } else if (line.Contains("USB")) { bool.TryParse(line.Substring(15), out this.usbPower); } else if (line.Contains("Wireless")) { bool.TryParse(line.Substring(20), out this.wirelessPower); } else if (line.Contains("status")) { int.TryParse(line.Substring(10), out this.status); } else if (line.Contains("health")) { int.TryParse(line.Substring(10), out this.health); } else if (line.Contains("present")) { bool.TryParse(line.Substring(11), out this.present); } else if (line.Contains("level")) { int.TryParse(line.Substring(9), out this.level); } else if (line.Contains("scale")) { int.TryParse(line.Substring(9), out this.scale); } else if (line.Contains("voltage")) { int.TryParse(line.Substring(10), out this.voltage); } else if (line.Contains("temp")) { int.TryParse(line.Substring(15), out this.temperature); } else if (line.Contains("tech")) { this.technology = line.Substring(14); } } } this.outString = this.dump.Replace("Service state", "State For Device " + this.device.SerialNumber); }
internal static void StartServer() { ExecuteAdbCommandNoReturn(Adb.FormAdbCommand("start-server")); }
/// <summary> /// Gets raw data about the device's battery and parses said data to then update all the data in this instance. /// </summary> private void Update() { if (this.device.State != DeviceState.ONLINE) { this.ACPower = false; this.dump = null; this.Health = "-1"; this.Level = -1; this.Present = false; this.Scale = -1; this.Status = "-1"; this.Technology = null; this.Temperature = -1; this.USBPower = false; this.Voltage = -1; this.WirelessPower = false; this.outString = "Device Not Online"; return; } AdbCommand adbCmd = Adb.FormAdbShellCommand(this.device, false, "dumpsys", "battery"); this.dump = Adb.ExecuteAdbCommand(adbCmd); using (StringReader r = new StringReader(this.dump)) { string line; while (true) { line = r.ReadLine(); if (!line.Contains("Current Battery Service state")) { continue; } else { this.dump = line + r.ReadToEnd(); break; } } } using (StringReader r = new StringReader(this.dump)) { string line = ""; while (r.Peek() != -1) { line = r.ReadLine(); if (line == "") { continue; } else if (line.Contains("AC ")) { if (bool.TryParse(line.Substring(14), out this.acPower)) { ACPower = acPower; } else if (line.Contains("USB")) { if (bool.TryParse(line.Substring(15), out this.usbPower)) { USBPower = usbPower; } else if (line.Contains("Wireless")) { if (bool.TryParse(line.Substring(20), out this.wirelessPower)) { WirelessPower = wirelessPower; } else if (line.Contains("status")) { if (int.TryParse(line.Substring(10), out this.status)) { Status = status.ToString(); } else if (line.Contains("health")) { if (int.TryParse(line.Substring(10), out this.health)) { Health = health.ToString(); } else if (line.Contains("present")) { if (bool.TryParse(line.Substring(11), out this.present)) { Present = present; } else if (line.Contains("level")) { if (int.TryParse(line.Substring(9), out this.level)) { Level = level; } else if (line.Contains("scale")) { if (int.TryParse(line.Substring(9), out this.scale)) { Scale = scale; } else if (line.Contains("voltage")) { if (int.TryParse(line.Substring(10), out this.voltage)) { Voltage = voltage; } else if (line.Contains("temp")) { var substring = line.Substring(15); var lastChar = line[line.Length - 1]; var trimmedString = line.Remove(line.Length - 1); var newString = string.Concat(trimmedString, ".", lastChar).ToLower().Contains("temperature") ? Regex.Split(string.Concat(trimmedString, ".", lastChar), ":\\s")[1] : string.Concat(trimmedString, ".", lastChar); if (double.TryParse(newString, out this.temperature)) { Temperature = temperature; } } else if (line.Contains("tech")) { this.Technology = line.Substring(14); } } } } } } } } } } } } this.outString = this.dump.Replace("Service state", "State For Device " + this.device.SerialNumber); }