-
- All Implemented Interfaces:
-
java.io.Closeable,java.lang.AutoCloseable
public abstract class Shell implements Closeable
A class providing APIs to an interactive Unix shell.
Similar to threads where there is a special "main thread",
{@code libsu}also has the concept of the "main shell". For each process, there is a single globally shared "main shell" that is constructed on-demand and cached.To obtain/create the main shell, use the static
{@code Shell.getShell(...)}methods. Developers can use these high level APIs to access the main shell:
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public abstract classShell.BuilderBuilder class for Shell instances.
Set the default builder for the main shell instance with setDefaultBuilder, or directly use a builder object to create new Shell instances.
Do not subclass this class! Use create to get a new Builder object.
public abstract classShell.ResultThe result of a Job.
public abstract classShell.JobRepresents a shell Job that could later be executed or submitted to background threads.
All operations added in add and add will beexecuted in the order of addition.
public classShell.InitializerThe initializer when a new
{@code Shell}is constructed.This is an advanced feature. If you need to run specific operations when a new
{@code Shell}is constructed, extend this class, add your own implementation, and register it with setInitializers.The concept is similar to{@code .bashrc}: run specific scripts/commands when the shellstarts up. onInit will be called as soon as the shell isconstructed and tested as a valid shell.An initializer will be constructed and the callbacks will be invoked each time a newshell is created.
public interfaceShell.TaskA task that can be executed by a shell with the method execTask.
public interfaceShell.GetShellCallbackThe callback used in getShell.
public interfaceShell.ResultCallbackThe callback to receive a result in submit.
-
Field Summary
Fields Modifier and Type Field Description public final static intUNKNOWNpublic final static intNON_ROOT_SHELLpublic final static intROOT_SHELLpublic final static intFLAG_NON_ROOT_SHELLpublic final static intFLAG_MOUNT_MASTERpublic static ExecutorEXECUTORpublic static booleanenableVerboseLoggingpublic static booleanenableLegacyStderrRedirectionpublic final static intROOT_MOUNT_MASTERpublic final static intFLAG_REDIRECT_STDERR
-
Method Summary
Modifier and Type Method Description static voidsetDefaultBuilder(Shell.Builder builder)Override the default Builder. static ShellgetShell()Get the main shell instance. static voidgetShell(@NonNull() Shell.GetShellCallback callback)Get the main shell instance asynchronously via a callback. static voidgetShell(@Nullable() Executor executor, @NonNull() Shell.GetShellCallback callback)Get the main shell instance asynchronously via a callback. static ShellgetCachedShell()Get the cached main shell. static BooleanisAppGrantedRoot()Whether the application has access to root. static Shell.Jobcmd(@NonNull() Array<String> commands)Create a pending Job of the main shell with commands. static Shell.Jobcmd(@NonNull() InputStream in)Create a pending Job of the main shell with an InputStream. abstract booleanisAlive()Return whether the shell is still alive. abstract voidexecTask(@NonNull() Shell.Task task)Execute a low-level Task using the shell. abstract voidsubmitTask(@NonNull() Shell.Task task)Submits a low-level Task for execution in a queue of the shell. abstract Shell.JobnewJob()Construct a new Job that uses the shell for execution. abstract intgetStatus()Get the status of the shell. booleanisRoot()Return whether the shell has root access. abstract booleanwaitAndClose(long timeout, @NonNull() TimeUnit unit)Wait for any current/pending tasks to finish before closing this shelland release any system resources associated with the shell. voidwaitAndClose()Wait indefinitely for any current/pending tasks to finish before closing this shelland release any system resources associated with the shell. static booleanrootAccess()Whether the application has access to root. -
-
Method Detail
-
setDefaultBuilder
static void setDefaultBuilder(Shell.Builder builder)
Override the default Builder.
This shell builder will be used to construct the main shell.Set this before the main shell is created anywhere in the program.
-
getShell
@NonNull() static Shell getShell()
Get the main shell instance.
If getCachedShell returns null, the default Builder will be used toconstruct a new
{@code Shell}.Unless already cached, this method blocks until the main shell is created.The process could take a very long time (e.g. root permission request prompt),so be extra careful when calling this method from the main thread!
A good practice is to "preheat" the main shell during app initialization(e.g. the splash screen) by either calling this method in a background thread orcalling getShell so subsequent calls to this functionreturns immediately.
-
getShell
static void getShell(@NonNull() Shell.GetShellCallback callback)
Get the main shell instance asynchronously via a callback.
If getCachedShell returns null, the default Builder will be used toconstruct a new
{@code Shell}in a background thread.The cached/created shell instance is returned to the callback on the main thread.- Parameters:
callback- invoked when a shell is acquired.
-
getShell
static void getShell(@Nullable() Executor executor, @NonNull() Shell.GetShellCallback callback)
Get the main shell instance asynchronously via a callback.
If getCachedShell returns null, the default Builder will be used toconstruct a new
{@code Shell}in a background thread.The cached/created shell instance is returned to the callback executed by provided executor.- Parameters:
executor- the executor used to handle the result callback event.callback- invoked when a shell is acquired.
-
getCachedShell
@Nullable() static Shell getCachedShell()
Get the cached main shell.
-
isAppGrantedRoot
@Nullable() static Boolean isAppGrantedRoot()
Whether the application has access to root.
This method returns
{@code null}when it is currently unable to determine whetherroot access has been granted to the application. A non-null value meant that the rootpermission grant state has been accurately determined and finalized. The applicationmust have at least 1 root shell created to have this method return{@code true}.This method will not block the calling thread; results will be returned immediately.
-
cmd
@NonNull() static Shell.Job cmd(@NonNull() Array<String> commands)
Create a pending Job of the main shell with commands.
This method can be treated as functionally equivalent to
{@code Shell.getShell().newJob().add(commands).to(new ArrayList<>())}, but the internalimplementation is specialized for this use case and does not run this exact code.The developer can manually override output destination(s) with either to or to.The main shell will NOT be requested until the developer invokes either exec, enqueue, or
{@code Job.submit(...)}. This makes itpossible to construct Jobs before the program has created any root shell.
-
cmd
@NonNull() static Shell.Job cmd(@NonNull() InputStream in)
Create a pending Job of the main shell with an InputStream.
This method can be treated as functionally equivalent to
{@code Shell.getShell().newJob().add(in).to(new ArrayList<>())}, but the internalimplementation is specialized for this use case and does not run this exact code.The developer can manually override output destination(s) with either to or to.The main shell will NOT be requested until the developer invokes either exec, enqueue, or
{@code Job.submit(...)}. This makes itpossible to construct Jobs before the program has created any root shell.
-
isAlive
abstract boolean isAlive()
Return whether the shell is still alive.
-
execTask
abstract void execTask(@NonNull() Shell.Task task)
Execute a low-level Task using the shell. USE THIS METHOD WITH CAUTION!
This method exposes raw STDIN/STDOUT/STDERR directly to the developer. This is meant forimplementing low-level operations. The shell may stall if the buffer of STDOUT/STDERRis full. It is recommended to use additional threads to consume STDOUT/STDERR in parallel.
STDOUT/STDERR is cleared before executing the task. No output from any previous tasks shouldbe left over. It is the developer's responsibility to make sure all operations are done;the shell should be in idle and waiting for further input when the task returns.
- Parameters:
task- the desired task.
-
submitTask
abstract void submitTask(@NonNull() Shell.Task task)
Submits a low-level Task for execution in a queue of the shell.
- Parameters:
task- the desired task.
-
getStatus
abstract int getStatus()
Get the status of the shell.
-
isRoot
boolean isRoot()
Return whether the shell has root access.
-
waitAndClose
abstract boolean waitAndClose(long timeout, @NonNull() TimeUnit unit)
Wait for any current/pending tasks to finish before closing this shelland release any system resources associated with the shell.
Blocks until all current/pending tasks have completed execution, orthe timeout occurs, or the current thread is interrupted,whichever happens first.
- Parameters:
timeout- the maximum time to waitunit- the time unit of the timeout argument
-
waitAndClose
void waitAndClose()
Wait indefinitely for any current/pending tasks to finish before closing this shelland release any system resources associated with the shell.
-
rootAccess
@Deprecated() static boolean rootAccess()
Whether the application has access to root.
This method would NEVER produce false negatives, but false positives can be returned beforeactually constructing a root shell. A
{@code false}returned is guaranteed to be100% accurate, while{@code true}may be returned if the device is rooted, but the userdid not grant root access to your application. However, after any root shell is constructed,this method will accurately return{@code true}.
-
-
-
-