Access to /data/data/com.whatsapp - android

Hy, while building an android application for 2.3.3 I got the following error:
I tried to access the files:
private static final String src_msg = "/data/data/com.whatsapp/databases/msgstore.db";
private static final String src_wa = "/data/data/com.whatsapp/databases/wa.db";
I do su before:
Process process = Runtime.getRuntime().exec("su");
I tried to copy the files to sdcard via cp command -> no success
I tried to check if the files exists via new File(src_msg).exists() -> no success
I use the following permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
what else is missing here? the popup to allow root comes up and has been accepted.

Try that: (Thanks to ramdroid )
private boolean run(boolean runAsRoot, String cmd) {
String shell = runAsRoot ? "su" : "sh";
int exitCode = 255;
Process p;
try {
p = Runtime.getRuntime().exec(shell);
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes(cmd + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
exitCode = p.waitFor();
} catch (IOException e1) {
Log.e("Exception", e1.toString());
} catch (InterruptedException e) {
Log.e("Exception", e.toString());
}
return (exitCode != 255);
}
public boolean copyFile() {
return run(true, "busybox cp /data/FILE TO COPY space DRECTORY TO COPY");
}
Change only YOUR_DIRECTORY and DIRECTORY TO COPYto the needed ones.

Related

How to uninstall system apps programatically after Android O?

I am making an app that can uninstall system apps. After going through all the answers from StackOverFlow, I can say that 99% of them are via ADB and the one which I found useful https://stackoverflow.com/a/34399068/9953518 ,this is now changed from Android O.
According to this article https://medium.com/#quaful/the-changes-of-apk-install-location-since-android-oreo-e646d1b53c4d it is now not possible to navigate to a specific folder of the app and we are bound to use .sourceDir. The problem that I have is after requesting for the root and getting the sourceDir, the .apk file doesn't uninstall and if it does, the complete files are not uninstalled or removed in this case. I am using the code below :
//appsSelected is the array with all the package names of the system apps selected to be uninstalled
case "uninstall":
for (int i = 0; i < appsSelected.size(); ++i) {
final int finalI = i;
Thread worker = new Thread(new Runnable() {
#Override
public void run() {
RootManager.getInstance().obtainPermission();
System.out.println("Public directory is "+ yup(appsSelected.get(finalI)));
runCommand("rm -rf "+ yup(appsSelected.get(finalI)) );
}
});
worker.start();
}
break;
This is the fucntion that returns the filePath:
String yup(String pack){
PackageManager m = getPackageManager();
PackageInfo p = null;
try {
p = m.getPackageInfo(pack, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return p.applicationInfo.sourceDir;
}
Finally the function that runs the commands:
public static void runCommand(String command) {
try {
Process chmod = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(chmod.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
chmod.waitFor();
String outputString = output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
I have the root permission ("su" command) and all the permissions required.
At first, run:
pm uninstall <package_name>
Then,
rm -r <applicationinfo.sourceDir>
Then,
rm -r <applicationinfo.publicSourceDir>
Then reboot the device, and the app should be uninstalled.
N.B: All these command should run as root!

su behaves differently on adb and on program

I have a custom device android 4.3. Problem occurs with some commands, one of an example:
su -c 'pm enable com.android.systemui'
When I run this command over adb it works. However when I run the code programatically using this library it just does not work, no error is shown as well.
Interesting observations:
Shell.SU.available() : false
Shell.SU.isSELinuxEnforcing() : false
Ok so device is rooted. Any reason why you are trying to do that command using that library?
What I am trying to say is why can't you just run the shell command yourself?
runRootCommand method:
static boolean runRootCommand(String command) {
boolean status = true;
DataOutputStream os = null;
try {
Process process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (IOException | InterruptedException e) {
Log.e(TAG, e.toString());
status = false;
} finally {
try {
if (os != null)
os.close();
} catch (IOException e) {
Log.e(TAG, e.toString());
status = false;
}
}
return status;
}
And then call that method like this:
boolean success = runRootCommand("pm enable com.android.systemui");
if(success) {
// command was successful
} else {
// command was NOT successful
}
This will run the command as "su" (superuser).
Hope this helps.

Clear android application user data

Using adb shell we can clear application data.
adb shell pm clear com.android.browser
But when executing that command from the application
String deleteCmd = "pm clear com.android.browser";
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) {
e.printStackTrace();
}
Issue:
It doesn't clear the user data nor give any exception though I have given the following permission.
<uses-permission android:name="android.permission.CLEAR_APP_USER_DATA"/>
Question:
How to clear another app application data using adb shell?
This command worked for me:
adb shell pm clear packageName
Afaik the Browser application data is NOT clearable for other apps, since it is store in private_mode. So executing this command could probalby only work on rooted devices. Otherwise you should try another approach.
The command pm clear com.android.browser requires root permission.
So, run su first.
Here is the sample code:
private static final String CHARSET_NAME = "UTF-8";
String cmd = "pm clear com.android.browser";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).command("su");
Process p = pb.start();
// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(), CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
out.write((cmd + "\n").getBytes(CHARSET_NAME));
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
out.flush();
p.waitFor();
String result = stdoutReader.getResult();
The class StreamReader:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
#Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}
To clear Application Data Please Try this way.
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
To reset/clear application data on Android, you need to check available packages installed on your Android device-
Go to adb shell by running adb shell on terminal
Check available packages by running pm list packages
If package name is available which you want to reset, then run pm clear packageName by replacing packageName with the package name which you want to reset, and same is showing on pm list packages result.
If package name isn't showing, and you will try to reset, you will get Failed status.
On mac you can clear the app data using this command
adb shell pm clear com.example.healitia
To clear the cache for all installed apps:
use adb shell to get into device shell ..
run the following command : cmd package list packages|cut -d":" -f2|while read package ;do pm clear $package;done
// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);
if(sdDir.exists())
deleteRecursive(sdDir);
// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}

How to get error message of a failed shell command on android

On a rooted android device, I tried to run a cat command that read kernel log, as follow:
Process p = Runtime.getRuntime().exec("su");
p = Runtime.getRuntime().exec("/system/bin/cat /proc/kmsg");
The su command was successfully executed but not the cat.
I tried to read the output of the command using getInputStream() but nothing was there, as follow:
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((read = err.read(buffer)) > 0)
{ //read error to buffer
catOutput.append(buffer, 0, read);
}
in.close();
I used the same code with ls command instead of displaying the kernel log, it worked just fine and show me the result.
I wonder if what error I am getting and wantted to see the error message on the shell when executing the cat command. Tried the p.getErrorStream() but it doesn't give me any result.
Could any one help me with this ? Thanks.
Here's a comprehensive example on how to do this - note that I got the idea from this answer:
public void catKmsg() {
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
StringBuilder sbstdOut = new StringBuilder();
StringBuilder sbstdErr = new StringBuilder();
String command="/system/bin/cat /proc/kmsg";
try { // Run Script
proc = runtime.exec("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();
}
sbstdOut.append(ReadBufferedReader(new InputStreamReader
(proc.getInputStream())));
sbstdErr.append(ReadBufferedReader(new InputStreamReader
(proc.getErrorStream())));
if (proc.exitValue() != 0) {
}
}
I finally found the solution for the problem by using RootTools library.
Recently released (few months after my question was asked), RootTools provides a easy-to-use tool set that helps running commands that required root privilege. I created a wrapper to check if root access is available before executing shell command:
void testRootToolsCommand(String command){
if (RootTools.isRootAvailable())
toastMessage("Root is available !!!");
else {
toastMessage("NO ROOT !!! ");
return;
}
int timeOut = 1000;
try {
List<String> output = RootTools.sendShell(command,timeOut);
toastMessage("OUTPUT of the command \n" + output.toString());
} catch (RootToolsException re) {
toastMessage("Funny thing happened with RootTools!!! ");
} catch (TimeoutException te)
{
toastMessage("Timeout exception - Increase timeout !!! !!! ");
}
catch (Exception e) {
toastMessage(e.getMessage().toString());
}
}
An example of a function call is:
testRootToolsCommand("cat /proc/kmsg > /sdcard/jun11_4h51.txt");
Note: The Tool also support running multiple commands at once.

How can we execute a shell script file from my Android Application

Please Tell me it is possible to run a shell script file from My Android application.
and read the data from script file.
If it is possible than how to proceed , Please give me some guideline.
You can use this code snippet (from Aaron C)
void execCommandLine(String command)
{
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
try
{
proc = runtime.exec("su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
osw.flush();
osw.close();
}
catch (IOException ex)
{
Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);
return;
}
finally
{
if (osw != null)
{
try
{
osw.close();
}
catch (IOException e){}
}
}
try
{
proc.waitFor();
}
catch (InterruptedException e){}
if (proc.exitValue() != 0)
{
Log.e("execCommandLine()", "Command returned error: " + command + "\n Exit code: " + proc.exitValue());
}
}
But this requires root access I think.
You could also try to use GScript
I've been using this to run shell scripts in my android app. Only thing I've yet to figure out how to do is direct the output to where I want it. You don't need root for this, which is why I'm posting.
Process process = Runtime.getRuntime().exec("top -n 1");
//Get the output of top so that it can be read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

Categories

Resources