Example usage for android.os Process myUid

List of usage examples for android.os Process myUid

Introduction

In this page you can find the example usage for android.os Process myUid.

Prototype

public static final int myUid() 

Source Link

Document

Returns the identifier of this process's uid.

Usage

From source file:eu.chainfire.opendelta.UpdateService.java

@SuppressLint("SdCardPath")
private void flashUpdate() {
    if (getPackageManager().checkPermission(PERMISSION_ACCESS_CACHE_FILESYSTEM,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_ACCESS_CACHE_FILESYSTEM);
        return;//w  w  w  .  j a  v a 2s  . c o  m
    }

    if (getPackageManager().checkPermission(PERMISSION_REBOOT,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_REBOOT);
        return;
    }

    String flashFilename = prefs.getString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT);
    prefs.edit().putString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT).commit();
    if ((flashFilename == null) || !flashFilename.startsWith(config.getPathBase()))
        return;

    // Remove the path to the storage from the filename, so we get a path
    // relative to the root of the storage
    String path_sd = Environment.getExternalStorageDirectory() + File.separator;
    flashFilename = flashFilename.substring(path_sd.length());

    // Find additional ZIPs to flash, strip path to sd
    List<String> extras = config.getFlashAfterUpdateZIPs();
    for (int i = 0; i < extras.size(); i++) {
        extras.set(i, extras.get(i).substring(path_sd.length()));
    }

    try {
        // TWRP - OpenRecoveryScript - the recovery will find the correct
        // storage root for the ZIPs, life is nice and easy.
        //
        // Optionally, we're injecting our own signature verification keys
        // and verifying against those. We place these keys in /cache
        // where only privileged apps can edit, contrary to the storage
        // location of the ZIP itself - anyone can modify the ZIP.
        // As such, flashing the ZIP without checking the whole-file
        // signature coming from a secure location would be a security
        // risk.
        {
            if (config.getInjectSignatureEnable()) {
                FileOutputStream os = new FileOutputStream("/cache/recovery/keys", false);
                try {
                    writeString(os, config.getInjectSignatureKeys());
                } finally {
                    os.close();
                }
                setPermissions("/cache/recovery/keys", 0644, Process.myUid(), 2001 /* AID_CACHE */);
            }

            FileOutputStream os = new FileOutputStream("/cache/recovery/openrecoveryscript", false);
            try {
                if (config.getInjectSignatureEnable()) {
                    writeString(os, "cmd cat /res/keys > /res/keys_org");
                    writeString(os, "cmd cat /cache/recovery/keys > /res/keys");
                    writeString(os, "set tw_signed_zip_verify 1");
                    writeString(os, String.format("install %s", flashFilename));
                    writeString(os, "set tw_signed_zip_verify 0");
                    writeString(os, "cmd cat /res/keys_org > /res/keys");
                    writeString(os, "cmd rm /res/keys_org");
                } else {
                    writeString(os, "set tw_signed_zip_verify 0");
                    writeString(os, String.format("install %s", flashFilename));
                }

                if (!config.getSecureModeCurrent()) {
                    // any program could have placed these ZIPs, so ignore
                    // them in secure mode
                    for (String file : extras) {
                        writeString(os, String.format("install %s", file));
                    }
                }
                writeString(os, "wipe cache");
            } finally {
                os.close();
            }

            setPermissions("/cache/recovery/openrecoveryscript", 0644, Process.myUid(), 2001 /* AID_CACHE */);
        }

        // CWM - ExtendedCommand - provide paths to both internal and
        // external storage locations, it's nigh impossible to know in
        // practice which will be correct, not just because the internal
        // storage location varies based on the external storage being
        // present, but also because it's not uncommon for community-built
        // versions to have them reversed. It'll give some horrible looking
        // results, but it seems to continue installing even if one ZIP
        // fails and produce the wanted result. Better than nothing ...
        //
        // We don't generate a CWM script in secure mode, because it
        // doesn't support checking our custom signatures
        if (!config.getSecureModeCurrent()) {
            FileOutputStream os = new FileOutputStream("/cache/recovery/extendedcommand", false);
            try {
                writeString(os, String.format("install_zip(\"%s%s\");", "/sdcard/", flashFilename));
                writeString(os, String.format("install_zip(\"%s%s\");", "/emmc/", flashFilename));
                for (String file : extras) {
                    writeString(os, String.format("install_zip(\"%s%s\");", "/sdcard/", file));
                    writeString(os, String.format("install_zip(\"%s%s\");", "/emmc/", file));
                }
                writeString(os, "run_program(\"/sbin/busybox\", \"rm\", \"-rf\", \"/cache/*\");");
            } finally {
                os.close();
            }

            setPermissions("/cache/recovery/extendedcommand", 0644, Process.myUid(), 2001 /* AID_CACHE */);
        } else {
            (new File("/cache/recovery/extendedcommand")).delete();
        }

        ((PowerManager) getSystemService(Context.POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        // We have failed to write something. There's not really anything
        // else to do at
        // at this stage than give up. No reason to crash though.
        Logger.ex(e);
    }
}

From source file:com.horizondigital.delta.UpdateService.java

@SuppressLint("SdCardPath")
private void flashUpdate() {
    if (getPackageManager().checkPermission(PERMISSION_ACCESS_CACHE_FILESYSTEM,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_ACCESS_CACHE_FILESYSTEM);
        return;/*from w w w . j  a  va2s. c o  m*/
    }

    if (getPackageManager().checkPermission(PERMISSION_REBOOT,
            getPackageName()) != PackageManager.PERMISSION_GRANTED) {
        Logger.d("[%s] required beyond this point", PERMISSION_REBOOT);
        return;
    }

    String flashFilename = prefs.getString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT);
    prefs.edit().putString(PREF_READY_FILENAME_NAME, PREF_READY_FILENAME_DEFAULT).commit();
    if ((flashFilename == null) || !flashFilename.startsWith(path_base))
        return;

    // Remove the path to the storage from the filename, so we get a path
    // relative to the root of the storage
    String path_sd = Environment.getExternalStorageDirectory() + File.separator;
    flashFilename = flashFilename.substring(path_sd.length());

    // Find additional ZIPs to flash
    List<String> extras = new ArrayList<String>();
    {
        File[] files = (new File(path_flash_after_update)).listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.getName().toLowerCase(Locale.ENGLISH).endsWith(".zip")) {
                    String filename = f.getAbsolutePath();
                    if (filename.startsWith(path_base)) {
                        extras.add(filename.substring(path_sd.length()));
                    }
                }
            }
        }
        Collections.sort(extras);
    }

    try {
        // We're using TWRP's openrecoveryscript as primary, and CWM's
        // extendedcommand as fallback. Using AOSP's command would
        // break older TWRPs. extendedcommand is broken on 'official'
        // CWM builds, though.

        // TWRP - OpenRecoveryScript - the recovery will find the correct
        // storage root for the ZIPs,
        // life is nice and easy.
        if ((flashFilename != null) && (!flashFilename.equals(""))) {
            FileOutputStream os = new FileOutputStream("/cache/recovery/openrecoveryscript", false);
            try {
                os.write(String.format("install %s\n", flashFilename).getBytes("UTF-8"));
                for (String file : extras) {
                    os.write(String.format("install %s\n", file).getBytes("UTF-8"));
                }
                os.write(("wipe cache\n").getBytes("UTF-8"));
            } finally {
                os.close();
            }
        }
        setPermissions("/cache/recovery/openrecoveryscript", 0644, Process.myUid(), 2001 /* AID_CACHE */);

        // CWM - ExtendedCommand - provide paths to both internal and
        // external storage locations, it's nigh impossible to know in
        // practice which will be correct, not just because the internal
        // storage location varies based on the external storage being
        // present, but also because it's not uncommon for community-built
        // versions to have them reversed. It'll give some horrible looking
        // results, but it seems to continue installing even if one ZIP
        // fails and produce the wanted result. Better than nothing ...
        if ((flashFilename != null) && (!flashFilename.equals(""))) {
            FileOutputStream os = new FileOutputStream("/cache/recovery/extendedcommand", false);
            try {
                os.write(
                        String.format("install_zip(\"%s%s\");\n", "/sdcard/", flashFilename).getBytes("UTF-8"));
                os.write(String.format("install_zip(\"%s%s\");\n", "/emmc/", flashFilename).getBytes("UTF-8"));
                for (String file : extras) {
                    os.write(String.format("install_zip(\"%s%s\");\n", "/sdcard/", file).getBytes("UTF-8"));
                    os.write(String.format("install_zip(\"%s%s\");\n", "/emmc/", file).getBytes("UTF-8"));
                }
                os.write(
                        ("run_program(\"/sbin/busybox\", \"rm\", \"-rf\", \"/cache/*\");\n").getBytes("UTF-8"));
            } finally {
                os.close();
            }
        }
        setPermissions("/cache/recovery/extendedcommand", 0644, Process.myUid(), 2001 /* AID_CACHE */);

        ((PowerManager) getSystemService(Context.POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        // We have failed to write something. There's not really anything else to do at
        // at this stage than give up. No reason to crash though.
        Logger.ex(e);
    }
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

private void optionSwitchTheme() {
    int userId = Util.getUserId(Process.myUid());
    String themeName = PrivacyManager.getSetting(userId, PrivacyManager.cSettingTheme, "");
    themeName = (themeName.equals("Dark") ? "Light" : "Dark");
    PrivacyManager.setSetting(userId, PrivacyManager.cSettingTheme, themeName);
    this.recreate();
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

private void optionTutorial() {
    ((ScrollView) findViewById(R.id.svTutorialHeader)).setVisibility(View.VISIBLE);
    ((ScrollView) findViewById(R.id.svTutorialDetails)).setVisibility(View.VISIBLE);
    int userId = Util.getUserId(Process.myUid());
    PrivacyManager.setSetting(userId, PrivacyManager.cSettingTutorialMain, Boolean.FALSE.toString());

    Dialog dlgUsage = new Dialog(this);
    dlgUsage.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    dlgUsage.setTitle(R.string.title_usage_header);
    dlgUsage.setContentView(R.layout.usage);
    dlgUsage.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));
    dlgUsage.setCancelable(true);//from w w w . java  2s.  c o  m
    dlgUsage.show();
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

private void optionChangelog() {
    WebView webview = new WebView(this);
    webview.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            int userId = Util.getUserId(Process.myUid());
            Version currentVersion = new Version(Util.getSelfVersionName(ActivityMain.this));
            PrivacyManager.setSetting(userId, PrivacyManager.cSettingChangelog, currentVersion.toString());
        }//  ww  w . j  a  v  a2  s  .  c  o m
    });
    webview.loadUrl("https://github.com/M66B/XPrivacy/blob/master/CHANGELOG.md");

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle(R.string.menu_changelog);
    alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
    alertDialogBuilder.setView(webview);
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

@SuppressLint("DefaultLocale")
private void optionAbout() {
    // About//w  ww.  ja v a2 s.  c  om
    Dialog dlgAbout = new Dialog(this);
    dlgAbout.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    dlgAbout.setTitle(R.string.menu_about);
    dlgAbout.setContentView(R.layout.about);
    dlgAbout.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));

    // Show version
    try {
        int userId = Util.getUserId(Process.myUid());
        Version currentVersion = new Version(Util.getSelfVersionName(this));
        Version storedVersion = new Version(
                PrivacyManager.getSetting(userId, PrivacyManager.cSettingVersion, "0.0"));
        boolean migrated = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingMigrated, false);
        String versionName = currentVersion.toString();
        if (currentVersion.compareTo(storedVersion) != 0)
            versionName += "/" + storedVersion.toString();
        if (!migrated)
            versionName += "!";
        int versionCode = Util.getSelfVersionCode(this);
        TextView tvVersion = (TextView) dlgAbout.findViewById(R.id.tvVersion);
        tvVersion.setText(String.format(getString(R.string.app_version), versionName, versionCode));
    } catch (Throwable ex) {
        Util.bug(null, ex);
    }

    if (!PrivacyManager.cVersion3 || Hook.isAOSP(19))
        ((TextView) dlgAbout.findViewById(R.id.tvCompatibility)).setVisibility(View.GONE);

    // Show license
    String licensed = Util.hasProLicense(this);
    TextView tvLicensed1 = (TextView) dlgAbout.findViewById(R.id.tvLicensed);
    TextView tvLicensed2 = (TextView) dlgAbout.findViewById(R.id.tvLicensedAlt);
    if (licensed == null) {
        tvLicensed1.setText(Environment.getExternalStorageDirectory().getAbsolutePath());
        tvLicensed2.setText(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getAbsolutePath());
    } else {
        tvLicensed1.setText(String.format(getString(R.string.app_licensed), licensed));
        tvLicensed2.setVisibility(View.GONE);
    }

    // Show some build properties
    String android = String.format("%s (%d)", Build.VERSION.RELEASE, Build.VERSION.SDK_INT);
    ((TextView) dlgAbout.findViewById(R.id.tvAndroid)).setText(android);
    ((TextView) dlgAbout.findViewById(R.id.build_brand)).setText(Build.BRAND);
    ((TextView) dlgAbout.findViewById(R.id.build_manufacturer)).setText(Build.MANUFACTURER);
    ((TextView) dlgAbout.findViewById(R.id.build_model)).setText(Build.MODEL);
    ((TextView) dlgAbout.findViewById(R.id.build_product)).setText(Build.PRODUCT);
    ((TextView) dlgAbout.findViewById(R.id.build_device)).setText(Build.DEVICE);
    ((TextView) dlgAbout.findViewById(R.id.build_host)).setText(Build.HOST);
    ((TextView) dlgAbout.findViewById(R.id.build_display)).setText(Build.DISPLAY);
    ((TextView) dlgAbout.findViewById(R.id.build_id)).setText(Build.ID);

    dlgAbout.setCancelable(true);

    final int userId = Util.getUserId(Process.myUid());
    if (PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFirstRun, true))
        dlgAbout.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                Dialog dlgUsage = new Dialog(ActivityMain.this);
                dlgUsage.requestWindowFeature(Window.FEATURE_LEFT_ICON);
                dlgUsage.setTitle(R.string.app_name);
                dlgUsage.setContentView(R.layout.usage);
                dlgUsage.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));
                dlgUsage.setCancelable(true);
                dlgUsage.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        PrivacyManager.setSetting(userId, PrivacyManager.cSettingFirstRun,
                                Boolean.FALSE.toString());
                        optionLegend();
                    }
                });
                dlgUsage.show();
            }
        });

    dlgAbout.show();
}

From source file:android.app.Activity.java

/**
 * Called as part of the activity lifecycle when an activity is going into
 * the background, but has not (yet) been killed.  The counterpart to
 * {@link #onResume}./*from  ww w  . j a v a2  s  .  c o m*/
 *
 * <p>When activity B is launched in front of activity A, this callback will
 * be invoked on A.  B will not be created until A's {@link #onPause} returns,
 * so be sure to not do anything lengthy here.
 *
 * <p>This callback is mostly used for saving any persistent state the
 * activity is editing, to present a "edit in place" model to the user and
 * making sure nothing is lost if there are not enough resources to start
 * the new activity without first killing this one.  This is also a good
 * place to do things like stop animations and other things that consume a
 * noticeable amount of CPU in order to make the switch to the next activity
 * as fast as possible, or to close resources that are exclusive access
 * such as the camera.
 * 
 * <p>In situations where the system needs more memory it may kill paused
 * processes to reclaim resources.  Because of this, you should be sure
 * that all of your state is saved by the time you return from
 * this function.  In general {@link #onSaveInstanceState} is used to save
 * per-instance state in the activity and this method is used to store
 * global persistent data (in content providers, files, etc.)
 * 
 * <p>After receiving this call you will usually receive a following call
 * to {@link #onStop} (after the next activity has been resumed and
 * displayed), however in some cases there will be a direct call back to
 * {@link #onResume} without going through the stopped state.
 * 
 * <p><em>Derived classes must call through to the super class's
 * implementation of this method.  If they do not, an exception will be
 * thrown.</em></p>
 * 
 * @see #onResume
 * @see #onSaveInstanceState
 * @see #onStop
 */
protected void onPause() {
    if (DEBUG_LIFECYCLE)
        Slog.v(TAG, "onPause " + this);
    getApplication().dispatchActivityPaused(this);
    mCalled = true;

    /* remove the migration notification */
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(Process.myUid());

    /* set Bundle for migration */
    if (isAvailable()) {
        Bundle tmpBundle = new Bundle();
        performSaveInstanceState(tmpBundle);
        systemMigrate(tmpBundle);
    }
}

From source file:androidx.media.MediaController2.java

private void sendCommand(String command, Bundle args, ResultReceiver receiver) {
    if (args == null) {
        args = new Bundle();
    }/*from www.j a  v a  2  s  .c o  m*/
    MediaControllerCompat controller;
    ControllerCompatCallback callback;
    synchronized (mLock) {
        controller = mControllerCompat;
        callback = mControllerCompatCallback;
    }
    args.putBinder(ARGUMENT_ICONTROLLER_CALLBACK, callback.getIControllerCallback().asBinder());
    args.putString(ARGUMENT_PACKAGE_NAME, mContext.getPackageName());
    args.putInt(ARGUMENT_UID, Process.myUid());
    args.putInt(ARGUMENT_PID, Process.myPid());
    controller.sendCommand(command, args, receiver);
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.hasExtra(EXTRA_COMMAND)
            && intent.getSerializableExtra(EXTRA_COMMAND) == Command.set) {
        set(intent);/*w ww.j  a va  2s .  c  o  m*/
        return START_STICKY;
    }

    // Keep awake
    getLock(this).acquire();

    // Handle service restart
    if (intent == null) {
        Log.i(TAG, "Restart");

        // Get enabled
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        boolean enabled = prefs.getBoolean("enabled", false);

        // Recreate intent
        intent = new Intent(this, ServiceSinkhole.class);
        intent.putExtra(EXTRA_COMMAND, enabled ? Command.start : Command.stop);
    }

    if (ACTION_HOUSE_HOLDING.equals(intent.getAction()))
        intent.putExtra(EXTRA_COMMAND, Command.householding);

    Command cmd = (Command) intent.getSerializableExtra(EXTRA_COMMAND);
    String reason = intent.getStringExtra(EXTRA_REASON);
    Log.i(TAG, "Start intent=" + intent + " command=" + cmd + " reason=" + reason + " vpn=" + (vpn != null)
            + " user=" + (Process.myUid() / 100000));

    commandHandler.queue(intent);
    return START_STICKY;
}

From source file:org.thoughtland.xlocation.ActivityShare.java

@SuppressLint("InflateParams")
public static boolean registerDevice(final ActivityBase context) {
    int userId = Util.getUserId(Process.myUid());
    if (Util.hasProLicense(context) == null
            && !PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingRegistered, false)) {
        // Get accounts
        String email = null;/*  w  w  w  . jav  a  2  s .  c  o m*/
        for (Account account : AccountManager.get(context).getAccounts())
            if ("com.google".equals(account.type)) {
                email = account.name;
                break;
            }

        LayoutInflater LayoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = LayoutInflater.inflate(R.layout.register, null);
        final EditText input = (EditText) view.findViewById(R.id.etEmail);
        if (email != null)
            input.setText(email);

        // Build dialog
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle(R.string.msg_register);
        alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher));
        alertDialogBuilder.setView(view);
        alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String email = input.getText().toString();
                        if (Patterns.EMAIL_ADDRESS.matcher(email).matches())
                            new RegisterTask(context).executeOnExecutor(mExecutor, email);
                    }
                });
        alertDialogBuilder.setNegativeButton(context.getString(android.R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Do nothing
                    }
                });

        // Show dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

        return false;
    }
    return true;
}