I have an android tablet installed on a robot, which has separate accumulator, and I need to power off tablet when that accumulator is discharged.
Is there any way to do it from android application?
I can root the device if needed.
UPD - tablet - Acer Iconia A100, ICS.
UPD2
here is working code
try {
Process process = new ProcessBuilder()
.command("/system/bin/su")
.start();
OutputStream o =process.getOutputStream();
o.write("/system/bin/reboot -p\n".getBytes());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "fail!", Toast.LENGTH_LONG).show();
}
How about something like that (That would work only on rooted devices):
try {
// it's possible you'd have to provide full path to rebot here (ex. '/system/bin/reboot -p' ??)
Runtime.getRuntime().exec("reboot -p");
} catch( Exception e ) { // pokemon catching
}
Full working example (update):
try {
// if that's not working use '/system/bin/su' instead
Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});
} catch( Exception e ) { }
Related
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.
Please help me to find out solution for this, I Know there are so many questions and duplicates about this same but here i describe whole things which i tried.
I have one android device where its installed 4.0 version of android.
I want to shutdown this device using my one demo application.
1) Demo application is signed by platform keys which are used in built in file system.
2) Device is already rooted as its development board and i have all permissions on this.
Application contains Following things
1) Application is system application
2) Application signed by platform keys which are used in built in file system.
For make automation easier, I did import the key/cert pair into my java keystore file, with the this keytool-importkeypair and use eclipse for signing.
Used command is mentioned below.
Commad : keytool-importkeypair -k ~/Desktop/myown.keystore -p android -pk8 platform.pk8 -cert platform.x509.pem -alias platform
I used following code for reboot but i never make success in this .I read So many questions and answers on stackoverflow but they all said you require
1) root access of device
2) signed apk with any one keys which are available on `build/target/product/security/`
3) Given Proper permission in AndroidManifest.xml file.
Am i right in alomg points?
Application code :
First Try
public static void shutdown2() {
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
String command = "/system/bin/reboot -p";
try { // Run Script
proc = runtime.exec("/system/xbin/su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
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();
}
if (proc.exitValue() != 0) {
}
}
Second Try :
private void shutdown3() {
try {
String[] cmd = { "/system/bin/sh","su","reboot -p"};
Process proc = Runtime.getRuntime().exec(cmd);
proc.waitFor();
} catch (Exception ex) {
Log.i("TAG", "Could not reboot 3 ", ex);
}
}
3rd Try :
private void shutdown() {
try {
Process proc = Runtime.getRuntime().exec(
new String[] { "/system/bin/su", "-c",
"/system/bin/reboot -p" });
proc.waitFor();
} catch (Exception ex) {
Log.i("TAG", "Could not reboot 1 ", ex);
}
}
In 3rd method I also tried with "/system/bin/su"
The below code worked for me
Process process = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "busybox poweroff -f"});
process.waitFor();
A much better solution is to run:
su -c am start -a android.intent.action.ACTION_REQUEST_SHUTDOWN
You can use a Process for this.
I'd like to print an image from my sd card with a Zebra EM220. I tried to use
GraphicsUtil.printImage("image path", 0, 0)
but all my attempts failed and I'm just able to print a list of characters.
In a first time, I tried to use that :
ZebraPrinter zp = ZebraPrinterFactory.getInstance(printerCo);
zp.getGraphicsUtil().printImage(path, 0, 0);
But the result was a ZebraLanguageUnknownException.
So I followed this solution : https://km.zebra.com/kb/index?page=content&id=SO8239&actp=LIST_RECENT but just a list of characters was printed.
I have no idea how to solve the problem so if someone succeeded to print an image with the Zebra EM 220 and can share the code, it should help me.
My code :
public void print(){
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myimage.jpg";
ZebraPrinterConnection printerCo = new BluetoothPrinterConnection(printerMacAdress);
try {
printerCo.open();
if (printerCo.isConnected()){
ZebraPrinter zp = new ZebraPrinterCpcl(printerCo);
zp.getGraphicsUtil().printImage(path, 0, 0);
Thread.sleep(500);
}
} catch (ZebraPrinterConnectionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try{
// Close the connection to release resources.
printerCo.close();
} catch (ZebraPrinterConnectionException e) {
e.printStackTrace();
}
}
}
}
Are you using the ZebraLink SDK? If so, it does not support the EM220. The ZebraLink SDK is designed for use with CPCL and ZPL printers. You can see the list of supported printers here: (click the compatible printers link in the middle): http://www.zebra.com/us/en/products-services/software/adapt-software/zebralink-sdk-android.html#mainpartabscontainer_71ac=downloads.
For the EM 220, you should instead use Zebra's EM 220 SDK for Android (bottom link): http://www.zebra.com/us/en/support-downloads/mobile/em-220.html.
And here is a quick piece of sample code (from Zebra's knowledgebase) explaining one method of printing through this SDK to an EM 220: https://km.zebra.com/kb/index?page=answeropen&type=open&searchid=1363808738897&answerid=16777216&iqaction=5&url=https%3A%2F%2Fkm.zebra.com%2Fkb%2Findex%3Fpage%3Dcontent%26id%3DSA316%26actp%3Dsearch%26viewlocale%3Den_US&highlightinfo=4194576,157,181#.
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.
I've got it wrapped in a try catch, but the exception still trips that ugly screen.
URL u = null;
try {
u = new URL(txturl.getText().toString());
}
catch (MalformedURLException e) {
ReportError(e,"Unable to connect to "+u);
}
calls this:
private void ReportError(Exception e, String message){
Display(message+" - "+ e.getMessage().toString());
System.out.println(">>>>>>>>>>>>>>>>>>>>> "+message+" - "+e.getMessage().toString());printStackTrace();
}
Any way around this. It happens on the Android 2.2 emulator with Eclipse and on my Sprint Hero.
Do I have to validate the form?
Thanks.
I just needed to return after these exceptions. duh. sorry.