I'm developing an application that execute multiple shell command in different time.
I'm using the following method:
public void RunAsRoot(String[] cmds){
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd+"\n");
}
os.writeBytes("exit\n");
os.flush();
}
This method works fine but it always open a new shell every time I need to call it, so that it display the annoying toast "Application has been granted for root permission".
I think this is becouse it always open and close a new shell with SU access. My question is: is there any way to leave a SU shell always open so that I can run my commands when needed without receive the SU toast?
So this might be a bit late, but in case you are still searching for a solution: Just declare
private Process p = Runtime.getRuntime().exec("su");
globally in your class. This should fit your needs.
You can actually spawn the process in onResume() and destroy() it again in onPause().
#Override
onResume() {
if(//check for root) {
try {
this.p = Runtime.getRuntime().exec("su");
}
catch(IOException e) {
// Exception handling goes here
}
}
//set up everything else
}
#Override
onPause() {
this.p.destroy();
}
BTW: I see a serious memory leak in the above method: You open a variety of SU processes but never destroy() them again. Depending on how often you call this method there will be more and more SU processes lying around in RAM until your app is closed.
So
public void runAsRoot(String[] cmds){
try {
Process p = Runtime.getRuntime().exec("su");
}
catch(IOException e) {
// Exception handling goes here
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd+"\n");
}
os.writeBytes("exit\n");
os.flush();
p.destroy();
}
would be good here. I'm also asking myself if you can compile your approach. Usually Runtime.getRuntime().exec(); has to be surrounded by try/catch.
Related
I'm creating an app that needs to change the data connection.
I found a solution: using su commands, but the problem is that Toast Warning shows every time when I execute the command....
Is possible using these commands without toast warning ?
Or
Is there a way to toggle the data connection enabled with TelephonyManager using reflections? I tried it, but it didn't works.
My code is below:
public static void setMobileDataState(boolean mMobileDataEnabled){
try{
if(mMobileDataEnabled)
Shell.runAsRoot(new String[]{"svc data enable"});
else
Shell.runAsRoot(new String[]{"svc data disable"});
}
catch (Exception ex){
Utilities.log(ex.toString());
}
}
public class Shell {
public static void runAsRoot(String[] mCommands){
try {
Process mProcess = Runtime.getRuntime().exec("su");
DataOutputStream mOS = new DataOutputStream(mProcess.getOutputStream());
for (String mCommand : mCommands) {
mOS.writeBytes(mCommand + "\n");
}
mOS.writeBytes("exit\n");
mOS.flush();
}catch (Exception o){
Utilities.log(o.toString());
}
}
}
I found the solution.....
I did the following:
I rooted my device
I installed my app as system app, it's simple, just copy your apk into /system/priv-app/myApk.apk and set chmod 644 permissions. If you have a doubt, check this post (If i set my android app to a system app, after a factory reset, will it be removed from the phone?).
I just removed the /system/app/SuperSU folder
I did a factory reset on device, and that is it ..... =D
I'm developing an application that is installed on the system partition and I would like to know if it's possible to get a screenshot of the current foreground application from a service. Of course, the application being any third party app.
I'm not interested in security issues or anything related to that matter. I only want to get a snapshot of the current foreground third party app.
Note: I'm aware of the /system/bin/screencap solution but I'm looking for a more elegant alternative that does everything programmatically.
The method that I'm going to describe below will let you to programmatically take screen shots of whatever app it's in the foreground from a background process.
I am assuming that you have a rooted device.
I this case you can use the uiautomator framework to get the job done.
This framework has a been created to automate black box testing of apps on android, but it will suite this purpose as well.
We are going to use the method
takeScreenshot(File storePath, float scale, int quality)
This goes in the service class:
File f = new File(context.getApplicationInfo().dataDir, "test.jar");
//this command will start uiautomator
String cmd = String.format("uiautomator runtest %s -c com.mypacket.Test", f.getAbsoluteFile());
Process p = doCmds(cmd);
if(null != p)
{
p.waitFor();
}
else
{
Log.e(TAG, "starting the test FAILED");
}
private Process doCmds(String cmds)
{
try
{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(su.getOutputStream());
os.writeBytes(cmds + "\n");
os.writeBytes("exit\n");
os.flush();
os.close();
return su;
}
catch(Exception e)
{
e.printStackTrace();
Log.e(TAG, "doCmds FAILED");
return null;
}
}
This is the class for uiautomator:
public class Test extends UiAutomatorTestCase
{
public void testDemo()
{
UiDevice dev = UiDevice.getInstance();
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
dev.takeScreenshot(f, 1.0, 100);
}
}
It's best if you create a background thread in which uiautomator will run, that way it will not run onto the ui thread. (the Service runs on the ui thread).
uiatuomator doesn't know about or have a android context.
Once uiautomator gets the control you will be able to call inside it android methods that do not take a context parameter or belong to the context class.
If you need to communicate between uiautomator and the service (or other android components) you can use LocalSocket.
This will allow communication in both ways.
Months have passed since I asked this question but just now had the time to add this feature. The way to do this is simply by calling screencap -p <file_name_absolute_path> and then grabbing the file. Next is the code I used:
private class WorkerTask extends AsyncTask<String, String, File> {
#Override
protected File doInBackground(String... params) {
File screenshotFile = new File(Environment.getExternalStorageDirectory().getPath(), SCREENSHOT_FILE_NAME);
try {
Process screencap = Runtime.getRuntime().exec("screencap -p " + screenshotFile.getAbsolutePath());
screencap.waitFor();
return screenshotFile;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(File screenshot_file) {
// Do something with the file.
}
}
Remember to add the <uses-permission android:name="android.permission.READ_FRAME_BUFFER" /> permission to the manifest. Otherwise screenshot.png will be blank.
This is much simpler than what Goran stated and is what I finally used.
Note: It only worked for me when the app is installed on the system partition.
UPDATE There are a number of other posts asking how to get a Screenshot in android but none seemed to have a full answer of how to do so. Originally I posted this as a question due to a particular issue I was running into while attempting to open a stream to the Frame Buffer. Now I've swapped over to dumping the Frame Buffer to a file so I've updated my post to show how I got there. For reference (and acknowledgement), I found the command to send the FrameBuffer to a file from this post (unfortunately he didn't provide how he got to that point). I'm just missing how to turn the raw data I pulled from the Frame Buffer into an actual image file.
My intention was to take a full dump of the actual screen on an Android Device. The only way I could find to do so without using the adb bridge was to directly access the Frame Buffer of the system. Obviously this approach will require root privileges on the device and for the app running it! Fortunately for my purposes I have control over how the Device is set up and having the device rooted with root privileges provided to my application is feasible. My testing is currently being done on an old Droid running 2.2.3.
I found my first hints of how to approach it from https://stackoverflow.com/a/6970338/1446554. After a bit more research I found another article that describes how to properly run shell commands as root. They were using it to execute a reboot, I use it to send the current frame buffer to an actual file. My current testing has only gotten as far as doing this via ADB and in a basic Activity (each being provided root). I will be doing further testing from a Service running in the background, updates to come! Here is my entire test activity that can export the current screen to a file:
public class ScreenshotterActivity extends Activity {
public static final String TAG = "ScreenShotter";
private Button _SSButton;
private PullScreenAsyncTask _Puller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_SSButton = (Button)findViewById(R.id.main_screenshotButton);
_SSButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (_Puller != null)
return;
//TODO: Verify that external storage is available! Could always use internal instead...
_Puller = new PullScreenAsyncTask();
_Puller.execute((Void[])null);
}
});
}
private void runSuShellCommand(String cmd) {
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
StringBuilder sbstdOut = new StringBuilder();
StringBuilder sbstdErr = new StringBuilder();
try { // Run Script
proc = runtime.exec("su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(cmd);
osw.flush();
osw.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
if (proc != null)
proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
sbstdOut.append(readBufferedReader(new InputStreamReader(proc.getInputStream())));
sbstdErr.append(readBufferedReader(new InputStreamReader(proc.getErrorStream())));
}
private String readBufferedReader(InputStreamReader input) {
BufferedReader reader = new BufferedReader(input);
StringBuilder found = new StringBuilder();
String currLine = null;
String sep = System.getProperty("line.separator");
try {
// Read it all in, line by line.
while ((currLine = reader.readLine()) != null) {
found.append(currLine);
found.append(sep);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
class PullScreenAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
File ssDir = new File(Environment.getExternalStorageDirectory(), "/screenshots");
if (ssDir.exists() == false) {
Log.i(TAG, "Screenshot directory doesn't already exist, creating...");
if (ssDir.mkdirs() == false) {
//TODO: We're kinda screwed... what can be done?
Log.w(TAG, "Failed to create directory structure necessary to work with screenshots!");
return null;
}
}
File ss = new File(ssDir, "ss.raw");
if (ss.exists() == true) {
ss.delete();
Log.i(TAG, "Deleted old Screenshot file.");
}
String cmd = "/system/bin/cat /dev/graphics/fb0 > "+ ss.getAbsolutePath();
runSuShellCommand(cmd);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
_Puller = null;
}
}
}
This also requires adding the android.permission.WRITE_EXTERNAL_STORAGE permission to the Manifest. As suggested in this post. Otherwise it runs, doesn't complain, doesn't create the directories nor the file.
Originally I couldn't get usable data from the Frame Buffer due to not understanding how to properly run shell commands. Now that I've swapped to using the streams for executing commands I can use '>' to send the Frame Buffer's current data to an actual file...
Programmatically you can run "adb shell /system/bin/screencap -p /sdcard/img.png" as below :
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
An easy solution for ICS devices is to use the following from the command line
adb shell /system/bin/screencap -p /sdcard/screenshot.png
adb pull /sdcard/screenshot.png screenshot.png
This'll save the screenshot.png file in the current directory.
Tested on a Samsung Galaxy SII running 4.0.3.
That would be different for different phones. It depends on the underlying graphics format of your device. You can poll what the graphics format is using system calls. If you are only going to run this on devices that you know the graphics format of you can write a converter that turns it into a known format.
You can have a look at the following project: http://code.google.com/p/android-fb2png/
If you look at the source code for fb2png.c you can see that they poll FBIOGET_VSCREENINFO which contains info about how the device stores the screen image in memory. Once you know that, you should be able to convert it into a format you can use.
I hope this helps.
I am trying to run these shell commands via java but no success.Code executes perfectly but .so file do not exectue. while i use these commands in adb everything work perfeclty.
private void submit() {
System.out.println("doooooooooo");
try {
String[] commands = {"cd /data/data/com.dailydeals.usethisnow/lib",
"./libdeals.so" };
Process p = Runtime.getRuntime().exec("/system/bin/sh -");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : commands) {
os.writeBytes(tmpCmd+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("doneooooooooo");
}
Executing shell commands in Android Applications (Android Programming)
I would like to know if there is a way to reboot the device through code. Ive tried:
Intent i = new Intent(Intent.ACTION_REBOOT);
i.putExtra("nowait", 1);
i.putExtra("interval", 1);
i.putExtra("window", 0);
sendBroadcast(i);
And added permissions for REBOOT but it still doesnt work.
Thanks
This seemed to work for me:
try {
Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", "reboot" });
proc.waitFor();
} catch (Exception ex) {
Log.i(TAG, "Could not reboot", ex);
}
Still for rooted devices, but in case you want safer (process.waitFor() is conditioned, in separate try-catch, we have proper exception handling, "now" added in command after reboot, which is necessary for some devices, etc.) and maybe cleaner code, take a look at this:
Process rebootProcess = null;
try
{
rebootProcess = Runtime.getRuntime().exec("su -c reboot now");
}
catch (IOException e)
{
// Handle I/O exception.
}
// We waitFor only if we've got the process.
if (rebootProcess != null)
{
try
{
rebootProcess.waitFor();
}
catch (InterruptedException e)
{
// Now handle this exception.
}
}
You could possibly use the PowerManager to make it reboot (this does not guarantee that it'll reboot - OS may cancel it):
links
link #2
I am using Xamarin. For me the solution is:
Java.Lang.Runtime.GetRuntime().Exec(new String[] { "/system/xbin/su", "-c", "reboot now" });
Here is a solution. Remember, the device must be rooted.
try{
Process p = Runtime.getRuntime().exec("su");
OutputStream os = p.getOutputStream();
os.write("reboot\n\r".getBytes());
os.flush();
}catch(IOException )
If the phone is rooted, it's actually very simple:
try {
Runtime.getRuntime().exec("su");
Runtime.getRuntime().exec("reboot");
} catch (IOException e) {
}
The first command will ask for superuser permission. The second, will reboot the phone.
There is no need for extra permissions in the manifest file since the actual rebooting is handled by the executed comamand, not the app.