[Android General] KP@2016:
Hey Guys, today I will cover about how to create your own android Toolkit in C#. In this tutorial, I will cover some further pieces of stuff to create bit advance Android Tools.

Thanks to QuantumCipher for this amazing guide and RegawMod for his amazing library.:)​

Basics​

You must know the following things before reading this guide

You just need to setup Visual Studio or SharpDevelop in order to create such projects.

You will see in every code, there are comments explaining them. Read them to at least get an idea what's happening. Below is the example of the comments in C#

// This is a Single line comment

/* This is a multiline
* comment in C#
*/

You should have the basic understanding of Toolbox controls and property box in Visual Studio. See the below image for better understanding!

[IMG="Image0"]https://kpstvhub.com/wp-content/uploads/2018/03/Untitled2-1.png[/IMG]

You cannot implicitly convert Integer variable to String in C#, you can do it in python but for C# you have to do following things

int a = 6;
string demo;
demo = a; // Wrong stuff...

// To Fix this do,
demo = a.ToString();
// Or this,
demo = Convert.ToString(a);

Basic Understanding on How to use GitHub :angel:

Please forgive my bad English :o

Understanding

​

You need to first understand how actually this thing works (I assume that you have setup Visual studio before reading this guide). Basically, you first create a button like Reboot, set its function and add some process function to run 'adb reboot' through a console (which you can hide if you set process.StartInfo.CreateNoWindow=false). You see every time we add a function (the feature of adb) call adb explicitly and run a shell process. It simply means if you don't know about adb commands or don't know how to deal with cmd or batch files it will be obviously difficult on creating an Android Toolkit.

Let me show you an example, below is the batch file demonstrating an example of Rebooting to recovery using adb.

@echo off
adb reboot recovery

Using C# we can achieve this by this below code.

Process.Start("cmd.exe", "/c adb reboot recovery");

See, not much difference in C# we pass adb reboot recovery to cmd.exe, of course, this will create a window but if you don't want we need to set some properties for Process like below. Read comments for better understanding.

void run_process(string Commands) // Declaring a function for process
{
var p = new Process(); // Declaring new process

// Defining the process, setting its parameters
p.StartInfo.FileName = "cmd.exe"; // Passing main function to cmd.exe
p.StartInfo.Arguments = "/c " + Commands; // Commands string passed here. /c argument is used to passed parameters explicitly.
p.StartInfo.CreateNoWindow = true; // No displaying a window
p.StartInfo.UseShellExecute = false; // No using cmd.exe to execute shell
p.Start(); // Starting the process
do
{
Application.DoEvents(); // This will prevent application from hang
}while(!p.HasExited); // Will wait until process been released from memory
}

void Button_Click(object sender, EventArgs e) // Use Button to achieve it.
{
run_process("adb reboot recovery"); // Running the command safely.
}

We create a function which passing commands explicitly to cmd.exe with which we can run our adb and other stuff. Beside this, we can prevent Application from hang if suppose a long process being executed.

So you might understand this, in order to create Android Toolkits you need to know pretty basics of the batch language and you know what the main part is? They are very easy to learn like you can do it in a day if you will. :)

Complexity of Process

​

This is the main part, you might actually need to know. You have seen the above example. Writing a simple adb reboot program requires lots of codes down there. For eg, see below

This is the code for detecting android devices using normal Process C#

string run_process(string Commands) // Creating a function
{
var p = new Process(); // Declaring new process

// Defining the process, setting its parameters
p.StartInfo.FileName = "cmd.exe"; // Passing main function to cmd.exe
p.StartInfo.Arguments = "/c " + Commands; // Commands string passed here. /c argument is used to passed parameters explicitly.
p.StartInfo.CreateNoWindow = true; // No displaying a window
p.StartInfo.UseShellExecute = false; // No using cmd.exe to execute shell
p.StartInfo.RedirectStandardOutput = true;
p.Start(); // Starting the process
do
{
Application.DoEvents(); // This will prevent application from hang
}while(!p.HasExited); // Will wait until process been released from memory
return p.StandardOutput.ReadToEnd(); // This will return the output from the process.
}'

bool isConnected() // Function for detecting Connected Devices
{
var check = run_process("adb.exe get-serialno"); // Will check for connected devices and set it to a string
if (check.Contains("unknown")) // If string Contains 'unknown' means no device connected
{
// If Not Connected
pictureBox1.BackColor = Color.Red; // Change Color of Picture Box
label1.Text = "Device Not Connected!";
status.Text = "---";
return false; // Returning boolean value
}
else
{
// If Connected, we will also check its status
pictureBox1.BackColor = Color.Green;
label1.Text = "Device Connected!";
status.Text = run_process("adb.exe get-state"); // This will check status of device i.e Android, Recovery, Sideload, etc
return true; // Returning boolean value
}
}

void Button_Click(object sender, EventArgs e) // A button click to run connected device function
{
if (isConnected())
{
// TODO: It is Connected, do your stuff in this loop
}
}

See the complexity and length of the code, Now what! Let's rewrite same procedure using a library. For instance, I will be showing usage of AndroidLib created by Recognised XDA Developer, RegawMod. I will teach you later how to use this for now look the code below.

void Button_Click(object sender, EventArgs e) // A button click to Check connected device
{
AndroidController android=null;// Declaring some variables
android = AndroidController.Instance; // Setting Android instance
if (android.HasConnectedDevices) // Check for connected devices
{
// TODO : That's it, Device is connected. You can run something here.
}
}

What Actually Happened? By using some wrappers we have actually breakdown big code to a short code which only has one function to check connected device.

What I mean by this? I am sure you have understood what you need to do. Using the normal process for running typical adb process we have increased the size and complexity of the code too much, but a wrapper like AndroidLib made our day by decreasing the size and seriously you have to typically remember some few things in this dll and you're done. A cut-down of a big adb process can be done with this wrapper.

So, let us start using the wrapper for creating your own C# Advance Toolkit

Using Actual Code​

Let's start creating new Project in Visual Studio or you may use SharpDevelop to Achieve this.​

Click on File > New Project > Visual C# > Windows Form Application. Name any solution and OK. Now download AndroidLib from the bottom of the post.

Click on Project > Add Reference > Browse for AndroidLib.dll and 'OKWe gonna create a project like this.

We gonna create a project like this. You can find this project in my sample at the bottom of this page.

[IMG="Image1"]https://kpstvhub.com/wp-content/uploads/2018/03/Untitled.png[/IMG]​

What Does this do? It will first detect our device in ADB Mode, show status and model number indicated by changing the back color of pictureBox to Green

Now Add the controls like above we have '1 label' saying that you need to add reference,, bla bla bla... '2 GroupBoxes' with Text=" ". '1 label' with Text=" " and Name=statuslabel , '1 Button' with Text="Check Device using AndroidLib" , '1 TextBox' at the center , '1 Button again' with Text="Go" and finally '1 ComboBox' containing items as 'Normal Reboot, Reboot to Recovery, Reboot to Bootloader' also Set its DropDownStyle=DropDownList from property box.

Coding Stuff​

Now Click on View > Code to see the code of the Form, here we will add the codes for the form.

Declare some imports at the top of the .cs

using RegawMOD.Android; // Android lib imports
using System.IO; // If dealing with file reading and writing, not necessary for this guide.

Declare some variables just after 'public partial class'

Device device; AndroidController android=null; string serial;

Add Few lines of code in your Form Constructor, for me my form name is MainForm so my form constructor is MainForm. You have to add codes below InitializeComponents(); Your Final code be like this

public MainForm()
{
InitializeComponent();
android = AndroidController.Instance; // Setting Android instance
comboBox1.SelectedIndex = 0; // First option will be selected in comboBox which is Normal Reboot, If you don't do this you will get a comboBox with no selection may generate an error if button is clicked.
groupBox2.Enabled = false; // Disabling group box at the start which contains reboot options
}

You may see I have disabled second groupBox, this is because if device is not connected and still it is shown user might try to use it and may generate an exception. That's why disabling it at start and after 'no device connected' for device prevents exceptions

Now Create a Function for checking connected device, same as we did above.

bool isConnected()
{
bool i=false; // Initialize variable as false
groupBox2.Enabled = false; // Disabling group box so what if there is no connected device, we may not want user to click on reboot button to prevent error
android.UpdateDeviceList(); // Update connected device list
if (android.HasConnectedDevices) // Check for connected devices
{
serial = android.ConnectedDevices[0]; // Get first connected device's serial '0' means first
device = android.GetConnectedDevice(serial); // Use device serial to get device
i=true; // It is connected
groupBox2.Enabled = true; // Enabling groupBox as we know device is connected
}
else
i=false; // It is not connected
return i; // Return as function says
}

Now Go back to designer from View, and double click on button with text 'Check Device using AndroidLib' , this will automatically generate an method for button.

Now add the code for the button in the field, so that finally it looks like this

void Button1Click(object sender, EventArgs e)
{
if (isConnected())
{
pictureBox1.BackColor = Color.Green; // Setting color to green
statuslabel.Text = device.BuildProp.GetProp("ro.product.device") + ", " + device.State; // Show device name in status label as connected with its state

// Get some Additional details and show in textbox
textBox1.Text="-------Device Connected-------" + Environment.NewLine;
textBox1.AppendText("Product Model: " + device.BuildProp.GetProp("ro.product.model") + Environment.NewLine); // Show device's model, you can use other prop commands to, you will find it in basic device info project
textBox1.AppendText("Battery Status: " + device.Battery.Level.ToString() + Environment.NewLine); // Show battery percentage as string
textBox1.AppendText("Battery Temperature: "+ device.Battery.Temperature + Environment.NewLine); // Show battery temperature
textBox1.AppendText("Encryption: "+ device.BuildProp.GetProp("ro.crypto.state") + Environment.NewLine); // Show encryption state
textBox1.AppendText("Is Rooted: "+ device.HasRoot + Environment.NewLine); // Show if device rooted
textBox1.AppendText("Su Version: " + device.Su.Version + Environment.NewLine); // Show the SU Version installed
textBox1.AppendText("BusyBox: "+device.BusyBox.IsInstalled + ", " + device.BusyBox.Version + Environment.NewLine); // Checks if busybox installed and its version
}
else
{
textBox1.Text = "-------Error No Device Connected--------";
pictureBox1.BackColor = Color.Red; // Setting color to Red as not connected
statuslabel.Text = "---";
}
}

What we just did? In button code, you will see that we used isConnected Function to check if the device is connected or not. If it's connected we will change the status label text and color of picture box to green along with some general information shown in the textBox. If not i.e else we will change color or PictureBox to red.

Now-Again go back to Designer and Double click on Button with the text 'Go' to generate a method for it.

Add the following code to it. This will set reboot Option code for it. Remeber ComboxBox index 0 means the first element and 1 means second element and so on... Its same as an array as it starts from 0.

void Button2Click(object sender, EventArgs e)
{
switch(comboBox1.SelectedIndex) // Checking which option been selected in comboxBox using integers
{
case 0: // First element been selected
device.Reboot();
break;
case 1: // Second element been selected
device.RebootRecovery();
break;
case 2: // Third element been selected
device.RebootBootloader();
break;
}
}

We have used Switch case loop in this case, to check which one is actually selected and according to it codes have been added.

For instance here is my full code of Main Form

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using RegawMOD.Android; // Android lib imports

namespace UsageOfAndroidLib
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
// Declaring some variables
Device device; AndroidController android=null; string serial;

public MainForm()
{
InitializeComponent();
android = AndroidController.Instance; // Setting Android instance
comboBox1.SelectedIndex = 0; // First option will be selected in comboBox which is Normal Reboot
groupBox2.Enabled = false; // Disabling group box at the start which contains reboot options
}

/// <summary>
/// This will check if device is connected or not
/// </summary>
/// <returns>bool</returns>
bool isConnected()
{
bool i=false; // Initialize variable as false
groupBox2.Enabled = false; // Disabling group box so what if there is no connected device, we may not want user to click on reboot button to prevent error
android.UpdateDeviceList(); // Update connected device list
if (android.HasConnectedDevices) // Check for connected devices
{
serial = android.ConnectedDevices[0]; // Get first connected device's serial '0' means first
device = android.GetConnectedDevice(serial); // Use device serial to get device
i=true; // It is connected
groupBox2.Enabled = true; // Enabling groupBox as we know device is connected
}
else
i=false; // It is not connected
return i; // Return as function says
}

/// <summary>
/// Main click of the button1, you know what it does;
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Button1Click(object sender, EventArgs e)
{
if (isConnected())
{
pictureBox1.BackColor = Color.Green; // Setting color to green
statuslabel.Text = device.BuildProp.GetProp("ro.product.device") + ", " + device.State; // Show device name in status label as connected with its state

// Get some Additional details and show in textbox
textBox1.Text="-------Device Connected-------" + Environment.NewLine;
textBox1.AppendText("Product Model: " + device.BuildProp.GetProp("ro.product.model") + Environment.NewLine); // Show device's model, you can use other prop commands to, you will find it in basic device info project
textBox1.AppendText("Battery Status: " + device.Battery.Level.ToString() + Environment.NewLine); // Show battery percentage as string
textBox1.AppendText("Battery Temperature: "+ device.Battery.Temperature + Environment.NewLine); // Show battery temperature
textBox1.AppendText("Encryption: "+ device.BuildProp.GetProp("ro.crypto.state") + Environment.NewLine); // Show encryption state
textBox1.AppendText("Is Rooted: "+ device.HasRoot + Environment.NewLine); // Show if device rooted
textBox1.AppendText("Su Version: " + device.Su.Version + Environment.NewLine); // Show the SU Version installed
textBox1.AppendText("BusyBox: "+device.BusyBox.IsInstalled + ", " + device.BusyBox.Version + Environment.NewLine); // Checks if busybox installed and its version

}
else
{
textBox1.Text = "-------Error No Device Connected--------";
pictureBox1.BackColor = Color.Red; // Setting color to Red as not connected
statuslabel.Text = "---";
}
}
void Button2Click(object sender, EventArgs e)
{
switch(comboBox1.SelectedIndex) // Checking which option been selected in comboxBox using integers
{
case 0: // First element been selected
device.Reboot();
break;
case 1: // Second element been selected
device.RebootRecovery();
break;
case 2: // Third element been selected
device.RebootBootloader();
break;
}
}
}
}

That's it, go to Build > Build {your Project} and run it from the button which looks like play (green one)

Some Tips and Helps​

My Idea behind the post was to spread the creativity about the Coding you can do. It's not just the project like above one. You have to think constantly about new ideas and find ways to implement it. Ask peoples, search on Google, XDA, StackOverflow these are some best sites for your doubt

clarification but don't just copy and paste code learn from it. Understand what it says, coding and making Tools it not only adding the feature and publish it onto the web, you need to think out of the box and add such thing which is practically hard doing in the normal way. Always remember toolkit make the process easier, don't make them too complex that user may not understand it:)

Here is below code on how you access Adb and Fastboot shells through the Library

Adb.ExecuteAdbCommand(Adb.FormAdbCommand("your command")); // Normal Adb Command
Adb.ExecuteAdbCommand(Adb.FormAdbShellCommand(device,false,"your command")); // ADB Shell command, by setting false to true you can access root shell
Fastboot.ExecuteFastbootCommand(Fastboot.FormFastbootCommand("your command")); // Use Fastboot commands

Whenever you fall into a trouble like you don't know what you can do further with this Library or any other in future, always remember a phrase "The Dot Operator tells you everything". Seems pretty funny but this is the truth like I don't know what this "device" (variable I've declared in above code demonstration) does? To find out, write it and add a dot

[IMG="Image2"]https://kpstvhub.com/wp-content/uploads/2018/03/Untitled1.png[/IMG]​

See it creates a context strip along with some tooltip text which tells me what is it for, from which I can figure out what I've to do. :cowboy:

AndroidLib: https://xdaforums.com/showthread.php?t=1512685

Some other wrappers: AndroidCtrl, Madb

Sample Projects: https://github.com/KaustubhPatange/AdbSamples

Check my samples on github which contains some other demonstration on how to create Android Toolkit very easily. Read Comments in the code and figure out what is it trying to say ;)

Have a Question ask in this websites: XDA,

StackOverFlow, CodeProject

So I think this is the end of the tutorial, I cannot explain everything on how to use this or that. Sometimes it is hard to code for an easy function but there is nothing wrong with asking people for your doubts, create QnA forums, asking in StackOverFlow. We learn from our mistakes, that's how the world works ;)

So Thank you for reading this guide, if you want you can share it with your friends and if you have any doubt comment below :laugh:

​