B4A Library SuperUser: Acquiring root permissions, the easy way.

version 2.4
Introduction

We all have seen various apps asking for superuser permissions to do weird things with our devices and many times we wondered how they do it. Well, with SupeUser, accessing a rooted device is as simple as a function call!

Latest package (library files and samples)
https://www.dropbox.com/s/f8gy3levkrtknt8/superuser.zip

Precompiled samples (APK)
Tutorial, KitKat ScreenRecorder with Audio
The ScreenRecorder does not work in the emulator. Use a real device instead.



upload_2014-7-28_22-17-41.png



Getting started
  • Extract the contents of the package anywhere in your hard disk.
  • Copy the superuser.jar and superuser.xml to your B4A libraries folder
  • Open the tutorial project located in the samples folder

The core of the library is the SuShell class. There are 2 ways using it. The simple and the advanced way. Let's take a look at the tutorial project.

The simple way (SuShellSimple sample)

First of all, we add the appropriate permission in our manifest file
B4X:
AddPermission("android.permission.ACCESS_SUPERUSER")

Whenever you need to do something with root permissions, you can just execute a superuser command and wait for the result (without blocking) in a single line of code. Keep in mind that each time you call the SuShell.Execute method, root permissions will be requested.
B4X:
Dim Su As SuShell
Su.Execute("ls").WaitForCompletion

You can also check before executing the command if the device is rooted and proceed accordingly.
B4X:
Dim Su As SuShell
If Su.DeviceRooted Then
    If Su.ExecuteWithEvent("ls", "Su").WaitForCompletion Then
        Msgbox("Done!", "")
    Else
        Msgbox("Permissions error!", "")
    End If
Else
    Msgbox("Device not rooted!", "")
End If

There is also the possibility to receive events by using the SuShell.ExecuteWithEvent method. The raised events are: Start, Command, Stop
B4X:
Sub BtnExecute_Click
    Dim Su As SuShell
    Su.ExecuteWithEvent("ls", "Su").WaitForCompletion
End Sub

Sub Su_Start
    Log("Su: Start")
End Sub

Sub Su_Command(Command As String, Response() As String)
    Dim Lines As String
    For i=0 To Response.Length-1
        Lines = Lines & Response(i) & CRLF
    Next
    Msgbox(Lines.Trim, Command)
End Sub

Sub Su_Stop(Result As Boolean)
    Log("Su: Stop=" & Result)
End Sub


Some examples:
B4X:
'Reboot the device
Su.Execute("reboot")
Su.Execute("reboot recovery")
Su.Execute("reboot bootloader")

'Restart the GUI by executing 2 commands at once, causing a so called fast-reboot
Su.ExecuteMultiple(Array As String("stop", "start"))


The advanced way (SuShellAdvanced sample)

SuShell is driven by a multi-threaded core that allows you to have complete control of the spawned process. A typical example is this:

Declare an SuShell and an SuProcess object in Sub Process_Globals
B4X:
Sub Process_Globals
    Dim Su As SuShell
    Dim Process As SuProcess
End Sub

Acquire root permissions in Sub Activity_Resume and open a command pipe that can be used at any time without requesting permissions again.
B4X:
If Su.DeviceRooted Then
    Process = Su.Acquire("Su")
End If

If Process.Acquired Then
    Log("root access granted")
Else
    Log("root access denied")
End If

Whenever is needed, execute a superuser command using the SuProcess object
B4X:
If Process.Acquired Then
    Process.Execute(EdCmd.Text)
Else
    Msgbox("Permissions error!", "")
End If

You can also use the methods of the SuProcess class to control it.


Additional Classes

The library currently contains few more classes that are utilizing the superuser core system.

1. SuApk

Can be used to silently install/uninstall apks. Once your app gets permanent root permissions, it will be able to silently install/uninstall any apk.

B4X:
Dim Apk As SuApk
Dim Result As Boolean = Apk.Install(File.DirAssets, "tutorial.apk")
B4X:
Dim Apk As SuApk
Dim Result As Boolean = Apk.Uninstall("com.datasteam.b4a.xtraviews.dialogview.tutorial")


2. SuBrowser

Can be used to offer a Root Explorer similar functionality.

Create an SuBrowser object in Sub Globals
B4X:
Sub Globals
    Dim Browser As SuBrowser
End Sub

In Activity_Resume initialize the object
B4X:
Sub Activity_Resume
    Browser.Initialize
End Sub

Call the SuBrowser.ListFolder to get the folder contents. Pass the desired folder name as a parameter. Use "" to get the root contents. The method returns a List object that contains SuBrowserFileInfo objects.
B4X:
Dim Contents as List = Browser.ListFolder(Folder)

Now you can traverse the Contents object.
B4X:
Contents.SortType("Type", True)
For Each FileInfo As SuBrowserFileInfo In Contents
    Dim SubTitle As String
    If FileInfo.IsFolder Then
        SubTitle = "folder"
    Else
        SubTitle = FileInfo.Size & " byte(s)"
    End If
    LvBrowser.AddTwoLines2(FileInfo.Name, SubTitle, FileInfo)
Next


3. SuRecorder

This class can be used to create a fully functional screen recorder with audio.
A separate tutorial is on its way


Please test it with your devices and post your feedback!

--

That's all for now folks! :D

Version history

2.4
  • Correctly detecting if the device is rooted
2.1

  • Stream optimizations and various bugfixes
2.0
  • Complete refactoring and package renamed to SuperUser
1.2
  • Added: InstallApk and UninstallApk methods. Can be used to silently install/uninstall apks
1.1
  • Added: KeepAlive property. If set to true, the first command will keep the connection with superuser process open without the need of asking for permissions again until the app process is killed or KeepAlive property is set back to false.
1.0
  • Initial version
 
Last edited:

Silv

Member
Licensed User
I tryed to install tutorial apk. It grants SU and install apk without problems . But when the installation finish , android kills the procces and i get following error in log.

java.lang.IllegalThreadStateException: Process has not yet terminated: 581
at java.lang.ProcessManager$ProcessImpl.exitValue(ProcessManager.java:275)
at com.datasteam.b4a.system.superuser.Su$1.run(Su.java:192)
at java.lang.Thread.run(Thread.java:818)

How to fix that?
Thanks.
 

peacemaker

Expert
Licensed User
java.lang.IllegalThreadStateException: Process has not yet terminated

The same issue, with
B4X:
Sub Get_Scr As Bitmap
' Take a screenshot.
Dim su As SuShell
su.Execute("/system/bin/screencap -p " & File.DirRootExternal & "/img.png").WaitForCompletion

Dim bmp As Bitmap
bmp.Initialize(File.DirRootExternal, "img.png")
Return bmp
End Sub

Problem is only if to shoot not my app activity.
But http://www.basic4ppc.com/forum/basi...nning-shell-commands-superuser.html#post39820 this SU script - works OK !
 
Last edited:

koaunglay

Member
Licensed User
Thanks a lot friends! But it is not OK screen recorder for me. I also installed your test recorder apk. It also not OK for me. It always show can't play this video. And I can't find recorded video file in folder. Thank any way. Sorry for my English .
rec3.png
rec2.png
 
Last edited:

BarryW

Active Member
Licensed User
Can we use this library to turn on gps. Because erel said that it needs to root a device so we can turn on gps programically.

Tnx...
 

Horst Leistner

Member
Licensed User
Please could you tell me how to use the SuperUser Library to solve my following simple Problem.
I have a picture in /sdcard/DCIM/Camera an want to copy it to my external SD Card /storage/7831-5E32.
I get a Permission Denied Error despite I have rooted my Galaxy S7.
There are no problems in the case of copying in the opposite direction.

Greetings
Horst Leistner


Manifest:

AddPermission("android.permission.WRITE_SETTINGS")
AddPermission("android.permission.ACCESS_SUPERUSER")


Sub Activity_Create(FirstTime As Boolean)
'Do not forget to load the layout file created with the visual designer. For example:
Activity.LoadLayout("Test")
Dim source,dest,filename As String
source = "/sdcard/DCIM/Camera"
dest = "/storage/7831-5E32"
filename = "2016.12.13_16.21.51.jpg"
End Sub

ERROR
java.io.FileNotFoundException: /storage/7831-5E32/2016.12.13_16.21.51.jpg: open failed: EACCES (Permission denied)
 

Horst Leistner

Member
Licensed User
Inserting "android.permission.write_external_storage" makes no difference, maybe because "/storage/7831-5E32" is not the same as "external storage"
DirRootExternal = /storage/emulated/0
DirDefaultExternal = /storage/emulated/0/Android/data/lei.TstCopy2/files
 

clarionero

Active Member
Licensed User
Inserting "android.permission.write_external_storage" makes no difference, maybe because "/storage/7831-5E32" is not the same as "external storage"
DirRootExternal = /storage/emulated/0
DirDefaultExternal = /storage/emulated/0/Android/data/lei.TstCopy2/files

Hi. I think in Samsung devices you must change the XML file with the access permisions to write the SD Card. It's not only give Root permisions to your app with this library. Look at XDA web for XML file name to change.

https://forum.xda-developers.com/showthread.php?t=2671916
http://help.locusmap.eu/topic/fix-for-external-sd-card-on-marshmallow

Rubén
 

walmo

Active Member
Licensed User
I tryed to install tutorial apk. It grants SU and install apk without problems . But when the installation finish , android kills the procces and i get following error in log.

java.lang.IllegalThreadStateException: Process has not yet terminated: 581
at java.lang.ProcessManager$ProcessImpl.exitValue(ProcessManager.java:275)
at com.datasteam.b4a.system.superuser.Su$1.run(Su.java:192)
at java.lang.Thread.run(Thread.java:818)

How to fix that?
Thanks.

I know this is a old thread but was struggling with this for a long time also.
For me the fix was to put ' & exit ' at the end of the command string
Thx
 
Top