eu.chainfire.libsuperuser.Shell Java Examples

The following examples show how to use eu.chainfire.libsuperuser.Shell. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AddWhiteListReceiver.java    From ForceDoze with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "com.suyashsrijan.forcedoze.ADD_WHITELIST broadcast intent received");
    final String packageName = intent.getStringExtra("packageName");
    Log.i(TAG, "Package name received: " + packageName);
    if (packageName != null) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                List<String> output = Shell.SH.run("dumpsys deviceidle whitelist +" + packageName);
                if (output != null) {
                    for (String s : output) {
                        Log.i(TAG, s);
                    }
                } else {
                    Log.i(TAG, "Error occurred while executing command (" + "dumpsys deviceidle whitelist +packagename" + ")");
                }
            }
        });
    } else {
        Log.i(TAG, "Package name null or empty");
    }
}
 
Example #2
Source File: AppListActivity.java    From Android-PreferencesManager with Apache License 2.0 6 votes vote down vote up
private void checkRoot() {
    AsyncTask<Void, Void, Boolean> checking = new AsyncTask<Void, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(Void... params) {
            return Shell.SU.available();
        }

        @Override
        protected void onPostExecute(Boolean hasRoot) {
            super.onPostExecute(hasRoot);
            isRootAccessGiven = hasRoot;
            if (!hasRoot) {
                Utils.displayNoRoot(getSupportFragmentManager());
            }
        }
    };
    checking.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
}
 
Example #3
Source File: ShadowsocksApplication.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
/**
 * copy assets
 */
public void copyAssets() {
    // ensure executables are killed before writing to them
    crashRecovery();
    copyAssets(System.getABI());
    copyAssets("acl");

    // exec cmds
    String[] cmds = new String[EXECUTABLES.length];
    for (int i = 0; i < cmds.length; i++) {
        cmds[i] = "chmod 755 " + getApplicationInfo().dataDir + File.separator + EXECUTABLES[i];
    }
    Shell.SH.run(cmds);

    // save current version code
    editor.putInt(Constants.Key.currentVersionCode, BuildConfig.VERSION_CODE).apply();
}
 
Example #4
Source File: TcpFastOpen.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
public static String enabled(boolean value) {
    if (sendEnabled() != value) {
        boolean suAvailable = Shell.SU.available();
        if (suAvailable) {
            int valueFlag = value ? 3 : 0;
            String[] cmds = {
                    "if echo " + valueFlag + " > /proc/sys/net/ipv4/tcp_fastopen; then",
                    "  echo Success.",
                    "else",
                    "  echo Failed.",
            };

            List<String> res = Shell.run("su", cmds, null, true);
            if (res != null && !res.isEmpty()) {
                return Utils.makeString(res, "\n");
            }
        }
    }

    return null;
}
 
Example #5
Source File: ShadowsocksApplication.java    From Maying with Apache License 2.0 6 votes vote down vote up
/**
 * arash recovery
 */
public void crashRecovery() {
    ArrayList<String> cmd = new ArrayList<>();

    String[] paramsArray = {"libssr-local.so", "ss-tunnel", "libpdnsd.so", "libredsocks.so", "libtun2socks.so", "proxychains"};
    for (String task : paramsArray) {
        cmd.add(String.format(Locale.ENGLISH, "killall %s", task));
        cmd.add(String.format(Locale.ENGLISH, "rm -f %1$s/%2$s-nat.conf %1$s/%2$s-vpn.conf", getApplicationInfo().dataDir, task));
    }

    // convert to cmd array
    String[] cmds = convertListToStringArray(cmd);
    if (app.isNatEnabled()) {
        cmd.add("iptables -t nat -F OUTPUT");
        cmd.add("echo done");
        List<String> result = Shell.SU.run(cmds);
        if (result != null && !result.isEmpty()) {
            // fallback to SH
            return;
        }
    }

    Shell.SH.run(cmds);
}
 
Example #6
Source File: ShadowsocksApplication.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
/**
 * arash recovery
 */
public void crashRecovery() {
    ArrayList<String> cmd = new ArrayList<>();

    String[] paramsArray = {"ss-local", "ss-tunnel", "pdnsd", "redsocks", "tun2socks", "proxychains"};
    for (String task : paramsArray) {
        cmd.add(String.format(Locale.ENGLISH, "killall %s", task));
        cmd.add(String.format(Locale.ENGLISH, "rm -f %1$s/%2$s-nat.conf %1$s/%2$s-vpn.conf", getApplicationInfo().dataDir, task));
    }

    // convert to cmd array
    String[] cmds = convertListToStringArray(cmd);
    if (app.isNatEnabled()) {
        cmd.add("iptables -t nat -F OUTPUT");
        cmd.add("echo done");
        List<String> result = Shell.SU.run(cmds);
        if (result != null && !result.isEmpty()) {
            // fallback to SH
            return;
        }
    }

    Shell.SH.run(cmds);
}
 
Example #7
Source File: TcpFastOpen.java    From Maying with Apache License 2.0 6 votes vote down vote up
public static String enabled(boolean value) {
    if (sendEnabled() != value) {
        boolean suAvailable = Shell.SU.available();
        if (suAvailable) {
            int valueFlag = value ? 3 : 0;
            String[] cmds = {
                    "if echo " + valueFlag + " > /proc/sys/net/ipv4/tcp_fastopen; then",
                    "  echo Success.",
                    "else",
                    "  echo Failed.",
            };

            List<String> res = Shell.run("su", cmds, null, true);
            if (res != null && !res.isEmpty()) {
                return Utils.makeString(res, "\n");
            }
        }
    }

    return null;
}
 
Example #8
Source File: ShadowsocksApplication.java    From Maying with Apache License 2.0 6 votes vote down vote up
/**
 * copy assets
 */
public void copyAssets() {
    // ensure executables are killed before writing to them
    crashRecovery();
    copyAssets(System.getABI());
    copyAssets("acl");

    // exec cmds
    String[] cmds = new String[EXECUTABLES.length];
    for (int i = 0; i < cmds.length; i++) {
        cmds[i] = "chmod 755 " + getApplicationInfo().nativeLibraryDir + File.separator + EXECUTABLES[i];
    }
    Shell.SH.run(cmds);

    // save current version code
    editor.putInt(Constants.Key.currentVersionCode, BuildConfig.VERSION_CODE).apply();
}
 
Example #9
Source File: ShadowsocksNatService.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
@Override
public void startRunner(final Profile profile) {
    if (su == null) {
        su = new Shell.Builder().useSU().setWatchdogTimeout(10).open(new Shell.OnShellOpenResultListener() {
            @Override
            public void onOpenResult(boolean success, int reason) {
                if (success) {
                    ShadowsocksNatService.super.startRunner(profile);
                } else {
                    if (su != null) {
                        su.close();
                        su = null;
                    }
                    ShadowsocksNatService.super.stopRunner(true, getString(R.string.nat_no_root));
                }
            }
        });
    }
}
 
Example #10
Source File: RootHelper.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Runs the command and stores output in a list. The listener is set on the handler
 * thread {@link ExplorerActivity#handlerThread} thus any code run in callback must be thread safe.
 * Command is run from the root context (u:r:SuperSU0)
 *
 * @param cmd the command
 * @return a list of results. Null only if the command passed is a blocking call or no output is
 * there for the command passed
 * @throws RootNotPermittedException
 */
public static ArrayList<String> runShellCommand(String cmd) throws RootNotPermittedException {
    if (ExplorerActivity.shellInteractive == null || !ExplorerActivity.shellInteractive.isRunning())
        throw new RootNotPermittedException();
    final ArrayList<String> result = new ArrayList<>();

    // callback being called on a background handler thread
    ExplorerActivity.shellInteractive.addCommand(cmd, 0, new Shell.OnCommandResultListener() {
        @Override
        public void onCommandResult(int commandCode, int exitCode, List<String> output) {

            for (String line : output) {
                result.add(line);
            }
        }
    });
    ExplorerActivity.shellInteractive.waitForIdle();
    return result;
}
 
Example #11
Source File: SettingActivity.java    From LocationReportEnabler with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... voids) {
    for (int i = 0; i < MAX_RETRY_TIME; i++) {
        if (isCancelled()) {
            return null;
        }

        mIsRootGranted = Shell.SU.available();

        Log.d("RootCheckTask", "check root permission with res: " + mIsRootGranted);

        if (mIsRootGranted) {
            break;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example #12
Source File: ScreenShiftService.java    From ScreenShift with Apache License 2.0 6 votes vote down vote up
private void saveWidthHeight(){
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            if(PreferencesHelper.getIntPreference(ScreenShiftService.this, KEY_DISPLAY_HEIGHT, -1) == -1
                    || PreferencesHelper.getIntPreference(ScreenShiftService.this, KEY_DISPLAY_WIDTH, -1) == -1) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    if(!Shell.SU.available()) {
                        return null;
                    } else {
                        Shell.SU.run(getResetCommands());
                    }
                } else {
                    Shell.SH.run(getResetCommands());
                }
                DisplaySize displaySize = DisplaySize.getDeviceDisplaySize(ScreenShiftService.this);
                PreferencesHelper.setPreference(ScreenShiftService.this, KEY_DISPLAY_HEIGHT, displaySize.height);
                PreferencesHelper.setPreference(ScreenShiftService.this, KEY_DISPLAY_WIDTH, displaySize.width);
            }
            return null;
        }
    }.execute();
}
 
Example #13
Source File: TexturePacksActivity.java    From MCPELauncher with Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {
	try {
		ApplicationInfo appInfo = getPackageManager().getApplicationInfo(
				"com.mojang.minecraftpe", 0);
		mcpeApkLoc = appInfo.sourceDir;
	} catch (PackageManager.NameNotFoundException impossible) {
	}
	outFile = new File(getExternalFilesDir(null), "minecraft.apk");
	outFile.delete();
	String outPath = outFile.getAbsolutePath().replace(
		Environment.getExternalStorageDirectory().getAbsolutePath(), "/sdcard");
	System.out.println(outPath);
	List<String> suResult = Shell.SU.run("cat \"" + mcpeApkLoc + "\" >\""
			+ outPath + "\"");
	if (suResult == null) {
		hasSu = false;
	}

	ScriptManager.clearTextureOverrides();

	return null;
}
 
Example #14
Source File: RemoveWhiteListReceiver.java    From ForceDoze with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "com.suyashsrijan.forcedoze.REMOVE_WHITELIST broadcast intent received");
    final String packageName = intent.getStringExtra("packageName");
    Log.i(TAG, "Package name received: " + packageName);
    if (packageName != null) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                List<String> output = Shell.SH.run("dumpsys deviceidle whitelist -" + packageName);
                if (output != null) {
                    for (String s : output) {
                        Log.i(TAG, s);
                    }
                } else {
                    Log.i(TAG, "Error occurred while executing command (" + "dumpsys deviceidle whitelist -packagename" + ")");
                }
            }
        });
    } else {
        Log.i(TAG, "Package name null or empty");
    }
}
 
Example #15
Source File: CheckShellTask.java    From YalpStore with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected Boolean doInBackground(String... params) {
    if (!Shell.SU.available()) {
        return false;
    }
    List<String> output = Shell.SU.run(getCommands());
    if (null == output) {
        return false;
    }
    Map<String, Boolean> flags = processOutput(output);
    availableCoreutils = flags.get(COMMAND_MV) && flags.get(COMMAND_RM) && flags.get(COMMAND_MKDIR) && flags.get(COMMAND_CHMOD);
    availableBusybox = flags.get(COMMAND_BUSYBOX);
    Log.i(getClass().getSimpleName(), "Coreutils available " + availableCoreutils);
    Log.i(getClass().getSimpleName(), "Busybox available " + availableBusybox);
    return true;
}
 
Example #16
Source File: MainActivity.java    From android-packet-capture with MIT License 6 votes vote down vote up
private int loadTcpdumpFromAssets(){
    int retval = 0;
    // updating progress message from other thread causes exception.
    // progressbox.setMessage("Setting up data..");
    String rootDataPath = getApplicationInfo().dataDir + "/files";
    String filePath = rootDataPath + "/tcpdump.bin";
    File file = new File(filePath);
    AssetManager assetManager = getAssets();

    try{
        if (file.exists()) {
            Shell.SH.run("chmod 755 " + filePath);
            return retval;
        }
        new File(rootDataPath).mkdirs();
        retval = copyFileFromAsset(assetManager, "tcpdump.bin", filePath);
        // Mark the binary executable
        Shell.SH.run("chmod 755 " + filePath);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
        retval = -1;
    }
    return retval;
}
 
Example #17
Source File: IslandSetup.java    From island with Apache License 2.0 6 votes vote down vote up
public static void requestProfileOwnerSetupWithRoot(final Activity activity) {
	final ProgressDialog progress = ProgressDialog.show(activity, null, "Setup Island...", true);
	// Phase 1: Create profile		TODO: Skip profile creation or remove existent profile first, if profile is already present (probably left by unsuccessful setup)
	final List<String> commands = Arrays.asList("setprop fw.max_users 10",
			"pm create-user --profileOf " + Users.toId(Process.myUserHandle()) + " --managed Island", "echo END");
	SafeAsyncTask.execute(activity, a -> Shell.SU.run(commands), result -> {
		Users.refreshUsers(activity);
		if (! Users.hasProfile()) {		// Profile creation failed
			if (result == null || result.isEmpty()) return;		// Just root failure
			Analytics.$().event("setup_island_root_failed").withRaw("commands", stream(commands).collect(joining("\n")))
					.withRaw("fw_max_users", String.valueOf(getSysPropMaxUsers()))
					.withRaw("config_multiuserMaximumUsers", String.valueOf(getResConfigMaxUsers()))
					.with(CONTENT, stream(result).collect(joining("\n"))).send();
			dismissProgressAndShowError(activity, progress, 1);
			return;
		}

		installIslandInProfileWithRoot(activity, progress);
	});
}
 
Example #18
Source File: ReadEditHostsFragment.java    From HouSi with Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... voids) {
    suAvailable = Shell.SU.available();
    if (!suAvailable) {
        return null;
    }

    initTempHostFile();

    suResult = Shell.SU.run(new String[]{
            StaticValues.MOUNT_SYSTEM_RW,
            "cp " + getTempHostsFilePath() + " " + StaticValues.SYSTEM_HOSTS_FILE_PATH,
            StaticValues.MOUNT_SYSTEM_RO
    });

    return null;
}
 
Example #19
Source File: BasicFragment.java    From HouSi with Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... voids) {
    suAvailable = Shell.SU.available();
    if (!suAvailable) {
        return null;
    }

    initEmptyHostFile();

    suResult = Shell.SU.run(new String[]{
            StaticValues.MOUNT_SYSTEM_RW,
            "cp " + getEmptyHostPath() + " " + StaticValues.SYSTEM_HOSTS_FILE_PATH,
            StaticValues.MOUNT_SYSTEM_RO
    });

    return null;
}
 
Example #20
Source File: BackupFragment.java    From TwrpBuilder with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
@Override
protected Void doInBackground(Void... params) {
    ShellExecuter.mkdir("TwrpBuilder");
    new FWriter("build.prop", Config.buildProp());
    try {
        ShellExecuter.cp("/system/build.prop", Sdcard + "TwrpBuilder/build.prop");
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (isOldMtk) {
        Shell.SU.run("dd if=" + recoveryPath + " bs=20000000 count=1 of=" + Sdcard + "TwrpBuilder/recovery.img ; cat /proc/dumchar > " + Sdcard + "TwrpBuilder/mounts ; cd " + Sdcard + "TwrpBuilder && tar -c recovery.img build.prop mounts > " + Sdcard + "TwrpBuilder/TwrpBuilderRecoveryBackup.tar ");
    } else {
        Shell.SU.run("dd if=" + recoveryPath + " of=" + Sdcard + "TwrpBuilder/recovery.img ; ls -la `find /dev/block/platform/ -type d -name \"by-name\"` > " + Sdcard + "TwrpBuilder/mounts ; cd " + Sdcard + "TwrpBuilder && tar -c recovery.img build.prop mounts > " + Sdcard + "TwrpBuilder/TwrpBuilderRecoveryBackup.tar ");
    }
    compressGzipFile(Sdcard + "/TwrpBuilder/TwrpBuilderRecoveryBackup.tar", backupFile);
    return null;
}
 
Example #21
Source File: Utils.java    From Android-PreferencesManager with Apache License 2.0 6 votes vote down vote up
/**
 * Put User id and Group id back to the corresponding app with this cmd: `chown uid.gid filename`
 *
 * @param ctx         Context
 * @param file        The file to fix
 * @param packageName The packageName of the app
 * @return true if success
 */
private static boolean fixUserAndGroupId(Context ctx, String file, String packageName) {
    Log.d(TAG, String.format("fixUserAndGroupId(%s, %s)", file, packageName));
    String uid;
    PackageManager pm = ctx.getPackageManager();
    if (pm == null) {
        return false;
    }
    try {
        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0);
        uid = String.valueOf(appInfo.uid);
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "error while getting uid", e);
        return false;
    }

    if (TextUtils.isEmpty(uid)) {
        Log.d(TAG, "uid is undefined");
        return false;
    }

    Shell.SU.run(String.format(CMD_CHOWN, uid, uid, file));
    return true;
}
 
Example #22
Source File: ExplorerActivity.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initializes an interactive shell, which will stay throughout the app lifecycle
 * The shell is associated with a handler thread which maintain the message queue from the
 * callbacks of shell as we certainly cannot allow the callbacks to run on same thread because
 * of possible deadlock situation and the asynchronous behaviour of LibSuperSU
 */
private void initializeInteractiveShell() {
    // only one looper can be associated to a thread. So we're making sure not to create new
    // handler threads every time the code relaunch.
    if (rootMode) {
        handlerThread = new HandlerThread("handler");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());
        shellInteractive = (new Shell.Builder()).useSU().setHandler(handler).open();

        // TODO: check for busybox
        /*try {
if (!RootUtils.isBusyboxAvailable()) {
Toast.makeText(this, getString(R.string.error_busybox), Toast.LENGTH_LONG).show();
closeInteractiveShell();
sharedPref.edit().putBoolean(PreferenceUtils.KEY_ROOT, false).apply();
}
} catch (RootNotPermittedException e) {
e.printStackTrace();
sharedPref.edit().putBoolean(PreferenceUtils.KEY_ROOT, false).apply();
}*/
    }
}
 
Example #23
Source File: Utils.java    From Android-PreferencesManager with Apache License 2.0 5 votes vote down vote up
public static boolean backupFile(String backup, String fileName, Context ctx) {
    Log.d(TAG, String.format("backupFile(%s, %s)", backup, fileName));
    File destination = new File(ctx.getFilesDir(), backup);
    Shell.SU.run(String.format(CMD_CP, fileName, destination.getAbsolutePath()));
    Log.d(TAG, String.format("backupFile --> " + destination));
    return true;
}
 
Example #24
Source File: DozeManager.java    From always-on-amoled with GNU General Public License v3.0 5 votes vote down vote up
public static void executeCommand(final String command) {
    AsyncTask.execute(() -> {
        List<String> output = Shell.SH.run(command);
        if (output == null)
            Utils.logInfo(DOZE_MANAGER, "Error occurred while executing command (" + command + ")");
    });
}
 
Example #25
Source File: TcpdumpPacketCapture.java    From android-packet-capture with MIT License 5 votes vote down vote up
public static int stopTcpdumpCapture(Activity _activity){
    if(isInitialised == false) {
        //Uncommenting creates problem with sometimes main_tv output wrong. Not really required right now.
        //initialiseCapture(_activity);
    }
    if(rootTcpdumpShell == null)    {
        //Not really required right now.
        //throw new RuntimeException("rootTcpdumpShell is null in: stopTcpdumpCapture.");
    }
    // Bug: Showing progress dialogue here (with above two ifs uncommented obviously) causes app to crash on "progressBox.show();"
    //if(!progressBox.isShowing())
    //    progressBox.show();

    int retVal = 0;
    //progressBox.setMessage("Killing tcpdump process.");

    try{
        List<String> out = Shell.SH.run("ps | grep tcpdump.bin");
        for(String x : out) {
            String[] temp = x.split("\\s+");
            Integer pid =  Integer.valueOf(temp[1]);
            List<String> exitOutput =  Shell.SU.run("kill -9 " + pid.toString());
        }
    }
    catch(Exception ex) {
        ex.printStackTrace();
        //retVal = -1;
        throw ex;
    }
    //progressBox.dismiss();
    return retVal;

}
 
Example #26
Source File: TcpdumpPacketCapture.java    From android-packet-capture with MIT License 5 votes vote down vote up
private static void startTcpdumpCapture() {
    try{
        List<String> out = Shell.SH.run("ps | grep tcpdump.bin");
        if(out.size() > 0){
            //One process already running. Don't start another.
            ((TextView)activity.findViewById(R.id.main_tv)).setText("Tcpdump "+out.size()+" process already running at pid: " + (out.get(0).split("\\s+"))[1] );
            return;
        }
        rootTcpdumpShell.addCommand(activity.getApplicationInfo().dataDir + "/files/tcpdump.bin -w /mnt/sdcard/0001.pcap", 0, new Shell.OnCommandLineListener() {
            @Override
            public void onCommandResult(int commandVal, int exitVal) {
                if (exitVal < 0) {
                    if(progressBox.isShowing()) {
                        progressBox.setMessage("Error returned by shell command...");
                    }
                }
            }
            @Override
            public void onLine(String line) {
                appendOutput(line);
            }
        });
    }
    catch(Exception ex) {
        ex.printStackTrace();
        throw ex;
    }
    ((TextView)activity.findViewById(R.id.main_tv)).setText("Packet capture started..");
}
 
Example #27
Source File: TcpdumpPacketCapture.java    From android-packet-capture with MIT License 5 votes vote down vote up
public static void initialiseCapture(Activity _activity) {
    activity = _activity;
    progressBox = new ProgressDialog(activity);
    progressBox.setTitle("Initialising Capture");
    progressBox.setMessage("Please wait while packet capture is initialised...");
    progressBox.setIndeterminate(true);
    progressBox.setCancelable(false);
    progressBox.show();
    if (rootTcpdumpShell != null) {
        if(!isInitialised)
            throw new RuntimeException("rootTcpdump shell: not null, initialized:false");
        startTcpdumpCapture();
        progressBox.dismiss();
    }
    else {
        rootTcpdumpShell = new Shell.Builder().
            useSU().
            setWantSTDERR(false).
            setMinimalLogging(true).
            open(new Shell.OnCommandResultListener() {
                @Override
                public void onCommandResult(int commandVal, int exitVal, List<String> out) {
                    //Callback checking successful shell start.
                    if (exitVal == Shell.OnCommandResultListener.SHELL_RUNNING) {
                        isInitialised = true;
                        progressBox.setMessage("Starting packet capture..");
                        startTcpdumpCapture();
                        progressBox.dismiss();
                    }
                    else {
                        progressBox.setMessage("There was an error starting root shell. Please grant root permissions or try again.");
                    }
                }
            });
    }
}
 
Example #28
Source File: WhitelistAppsActivity.java    From ForceDoze with GNU General Public License v3.0 5 votes vote down vote up
public void executeCommand(final String command) {
    if (Utils.isDeviceRunningOnN() && isSuAvailable) {
        Shell.SU.run(command);
    } else {
        Shell.SH.run(command);
    }
}
 
Example #29
Source File: PreferencesActivity.java    From always-on-amoled with GNU General Public License v3.0 5 votes vote down vote up
public static void uninstall(Context context, Prefs prefs) {
    try {
        ComponentName devAdminReceiver = new ComponentName(context, DAReceiver.class);
        DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        dpm.removeActiveAdmin(devAdminReceiver);
        if (prefs.proximityToLock && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && !Shell.SU.available())
            prefs.setBool(Prefs.KEYS.PROXIMITY_TO_LOCK.toString(), false);
    } catch (Exception ignored) {
    }
    Uri packageUri = Uri.parse("package:" + context.getPackageName());
    Intent uninstallIntent =
            new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri);
    uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(uninstallIntent);
}
 
Example #30
Source File: IslandSetup.java    From island with Apache License 2.0 5 votes vote down vote up
private static void activateDeviceOwnerOrShowSetupGuide(final Fragment fragment, final int request_code) {
	final Activity activity = fragment.getActivity();
	if (activity == null) return;
	String content = "<?xml version='1.0' encoding='utf-8' standalone='yes' ?><device-owner package=\"" + Modules.MODULE_ENGINE + "\" />";
	final Optional<Boolean> is_profile_owner;
	final String admin_component = DeviceAdmins.getComponentName(activity).flattenToString();
	if (Users.profile != null && (is_profile_owner = DevicePolicies.isProfileOwner(activity, Users.profile)) != null && is_profile_owner.orElse(false))
		content += "<profile-owner package=\"" + Modules.MODULE_ENGINE + "\" name=\"Island\" userId=\"" + Users.toId(Users.profile)
				+ "\" component=\"" + admin_component + "\" />";
	content = content.replace("\"", "\\\"").replace("'", "\\'")
			.replace("<", "\\<").replace(">", "\\>");

	final String file = new File(getDataSystemDirectory(), "device_owner.xml").getAbsolutePath();
	final StringBuilder command = new StringBuilder("echo ").append(content).append(" > ").append(file)
			.append(" && chmod 600 ").append(file).append(" && chown system:system ").append(file);
	if (SDK_INT >= LOLLIPOP_MR1) command.append(" && dpm set-active-admin ").append(admin_component).append(" ; echo DONE");
	else command.append(" && echo DONE");

	SafeAsyncTask.execute(activity, a -> Shell.SU.run(command.toString()), output -> {
		if (activity.isDestroyed() || activity.isFinishing()) return;
		if (output == null || output.isEmpty()) {
			Toast.makeText(activity, R.string.toast_setup_mainland_non_root, Toast.LENGTH_LONG).show();
			WebContent.view(activity, Uri.parse(Config.URL_SETUP.get()));
			return;
		}
		if (! "DONE".equals(output.get(output.size() - 1))) {
			Analytics.$().event("setup_mainland_root").with(CONTENT, stream(output).collect(joining("\n"))).send();
			Toast.makeText(activity, R.string.toast_setup_mainland_root_failed, Toast.LENGTH_LONG).show();
			return;
		}
		Analytics.$().event("setup_mainland_root").with(CONTENT, output.size() == 1/* DONE */? null : stream(output).collect(joining("\n"))).send();
		// Start the device-admin activation UI (no-op if already activated with root above), since "dpm set-active-admin" is not supported on Android 5.0.
		fragment.startActivityForResult(new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
				.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, DeviceAdmins.getComponentName(activity))
				.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, activity.getString(R.string.dialog_mainland_device_admin)), request_code);
		// Procedure is followed in onAddAdminResult().
	});
}