Quite some time ago, someone posted a script with which you can execute a root command.

Quite some time ago, someone posted a script with which you can execute a root command. I’ve been developing this function further while working on my Auto setup long tap freeze script (http://www.lightninglauncher.com/wiki/doku.php?id=script_autosetupappfreeze) and i thought i would post it here again if someone wants to use it. If people are interested it might also be added to this new lightning launcher script/template collection thing Pierre posted about a few weeks ago, but i’ve lost the url.

The code also contains helpers for multithreading, which might deserve their own little spotlight as well.

Although i’ve learnt a lot about Javascript, I certainly don’t think i’m an expert yet, so if you have any suggestions for improvements or questions, please put them in the comments

Anyways here it is:

bindClass(‘java.lang.Runtime’);

bindClass(‘java.io.BufferedReader’);

bindClass(‘java.io.InputStreamReader’);

bindClass(‘java.io.DataOutputStream’);

bindClass(“java.lang.Thread”);

bindClass(“android.os.Handler”);

bindClass(“android.os.Looper”);

// initalize some global variables

var threads = []

, GUIHandler = new Handler();

/**

* This callback will be called when the executing of the command(s) is finished

*

* @callback finishedCallback

* @param {string[]} An array of the lines the command(s) returned

*/

/**

* This callback will be called when a command is executed.

*

* @callback executedCallback

*/

/**

* Runs a command in the terminal

* @param cmds {string|string[]} – The command or array of commmands to be executed.

* @param [asRoot=false] {boolean} – If the command(s) should be executed as root or not.

* @param [newThread=true] {boolean} – If the executing of commands should happen in a new thread or not. (useful for root commands)

* @param [callback] {finishedCallback} – The callback that handles the output.

* @param [onExecuted] {executedCallback} – A callback that will be called when a command is executed. useful for multiple commands that take some time)

* @returns {string[]||string[][]} – (only if asRoot == false && newThread == false) Returns an array of the lines written in the terminal or an array of arrays if multiple commands were executed.

*/

function runCmd(cmds, asRoot, newThread, callback, onExecuted){

var handler = getHandler()

, output, process, reader, writer;

// set optional arguments

if(asRoot == null)

asRoot = false;

if(newThread == null)

newThread = true;

/**

* Helper function for executing the command(s). Gets its parameters from the parent function.

* @returns {string[]||string[][]} – (only if asRoot == false && newThread == false) Returns an array of the lines written in the terminal or an array of arrays if multiple commands were executed.

*/

function execCmd(){

/**

* Checks if the command is a string and if not alerts the user.

* @param cmd {string}

* @returns {boolean}

*/

function checkCmd(cmd){

if(typeof(cmd) === “string”){

return true;

}else

handleGUIEdit(function(){

alert(cmd + ” is not a string!”);

});

return false;

}

/**

* Actually executes command.

* @param cmd {string}

* @param writer {DataOutputStream} – The writer to write the command to.

* @returns {boolean} If the command was actually written or not.

*/

function exec(cmd, writer){

if(checkCmd(cmd)){

writer.writeBytes(cmd + “\n”);

writer.flush();

return true;

}

return false;

}

/**

* Read the output from the reader.

* @param reader {BufferedReader}

* @returns {Array} An array of lines that were outputted by the

*/

function readOutput(reader){

var tmp, output = [];

while((tmp = reader.readLine()) != null)

output.push(tmp);

return output.length == 1 ? output[0] : output;

}

/**

* Executes the callback and if the callback is not a function alerts the user.

* @param callback

* @param output {Array} – The argument that is passed to the callback

*/

function handleCallback(callback, output){

if(typeof callback == “function”){

handler.post(function(){

callback(output);

});

}else if(callback){

handleGUIEdit(function(){

alert(callback + ” is not a function!”);

});

}

}

try{

if(asRoot){

process = Runtime.getRuntime().exec(“su”);

reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

writer = new DataOutputStream(process.getOutputStream());

if(isArray(cmds)){

output = [];

cmds.forEach(function(cmd){

if(exec(cmd, writer)){

handleCallback(onExecuted);

}

});

exec(“exit”, writer);

writer.close();

output = readOutput(reader);

handleCallback(callback, output);

}else{

var succes = exec(cmds, writer);

exec(“exit”, writer);

writer.close();

if(succes){

output = readOutput(reader);

handleCallback(onExecuted);

handleCallback(callback, output);

}

}

reader.close();

process.waitFor();

}else{

if(isArray(cmds)){

var outputs = [];

cmds.forEach(function(cmd){

if(checkCmd(cmd)){

process = Runtime.getRuntime().exec(cmd);

reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

output = readOutput(reader);

reader.close();

outputs.push(output);

handleCallback(onExecuted);

handleCallback(callback, output);

}

});

process.waitFor();

return outputs;

}else{

process = Runtime.getRuntime().exec(cmds);

reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

output = readOutput(reader);

reader.close();

process.waitFor();

handleCallback(onExecuted);

handleCallback(callback, output);

return output;

}

}

}catch(err){

handleGUIEdit(function(){

alert(“At line ” + err.lineNumber + “: ” + err);

});

}

}

if(asRoot && isArray(callback))

throw new Error(“Multiple callbacks are not possible in su mode. Use onExecuteds instead.”);

if(newThread){

startNewBackgroundThread(function(){

execCmd();

});

}else{

return execCmd();

}

}

/**

* Checks if an object is an array.

* @param object

* @returns {boolean}

*/

function isArray(object){

return Object.prototype.toString.call(object) == ‘[object Array]’;

}

/**

* If this function is executed in a thread that is the main GUI thread, execute func, or else execute func in the main GUI thread. (Android doesn’t like it when you change the GUI outside of the main GUI thread)

* @param func {function}

*/

function handleGUIEdit(func){

if(Looper.getMainLooper().getThread() == Thread.currentThread()){

func();

}else{

GUIHandler.post(func);

}

}

/**

* Starts a new background thread with func.

* @param func {function} – The function the thread executes.

*/

function startNewBackgroundThread(func){

var thread = new Thread(function(){

func();

// if a looper was initialized in func, make sure the thread can die by stopping the thread when the Looper idles.

if(threads[Thread.currentThread().getId()].prepared == true){

Looper.myLooper().getQueue().addIdleHandler(function(){

Looper.myLooper().quitSafely();

});

Looper.loop();

}

});

thread.setUncaughtExceptionHandler(function(th, ex){

handleGUIEdit(function(){

alert(ex.getMessage());

})

});

threads[thread.getId()] = {};

thread.start();

}

/**

* Gets a handler for the current thread and initializes a looper if necessary.

* @returns {Handler}

*/

function getHandler(){

if(Looper.getMainLooper().getThread() == Thread.currentThread()){

return GUIHandler;

}else{

var threadId = Thread.currentThread().getId();

if(threads[threadId].prepared != true){

Looper.prepare();

threads[threadId].prepared = true;

}

return new Handler();

}

}

http://www.lightninglauncher.com/wiki/doku.php?id=script_autosetupappfreeze
]]>

Leave a Reply

Your email address will not be published. Required fields are marked *