Example usage for android.os StrictMode getVmPolicy

List of usage examples for android.os StrictMode getVmPolicy

Introduction

In this page you can find the example usage for android.os StrictMode getVmPolicy.

Prototype

public static VmPolicy getVmPolicy() 

Source Link

Document

Gets the current VM policy.

Usage

From source file:com.android.strictmodetest.StrictModeActivity.java

/** Called when the activity is first created. */
@Override/* w  w  w. jav  a  2s . co m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    cr = getContentResolver();
    final SQLiteDatabase db = openOrCreateDatabase("foo.db", MODE_PRIVATE, null);

    final Button readButton = (Button) findViewById(R.id.read_button);
    readButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Cursor c = null;
            try {
                c = db.rawQuery("SELECT * FROM foo", null);
            } finally {
                if (c != null)
                    c.close();
            }
        }
    });

    final Button writeButton = (Button) findViewById(R.id.write_button);
    writeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
        }
    });

    final Button writeLoopButton = (Button) findViewById(R.id.write_loop_button);
    writeLoopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            long startTime = SystemClock.uptimeMillis();
            int iters = 1000;
            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
            for (int i = 0; i < iters; ++i) {
                policy.onWriteToDisk();
            }
            long endTime = SystemClock.uptimeMillis();
            Log.d(TAG, "Time for " + iters + ": " + (endTime - startTime) + ", avg="
                    + (endTime - startTime) / (double) iters);
        }
    });

    final Button dnsButton = (Button) findViewById(R.id.dns_button);
    dnsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "Doing DNS lookup for www.l.google.com... " + "(may be cached by InetAddress)");
            try {
                InetAddress[] addrs = InetAddress.getAllByName("www.l.google.com");
                for (int i = 0; i < addrs.length; ++i) {
                    Log.d(TAG, "got: " + addrs[i]);
                }
            } catch (java.net.UnknownHostException e) {
                Log.d(TAG, "DNS error: " + e);
            }
        }
    });

    final Button httpButton = (Button) findViewById(R.id.http_button);
    httpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Note: not using AndroidHttpClient, as that comes with its
                // own pre-StrictMode network-on-Looper thread check.  The
                // intent of this test is that we test the network stack's
                // instrumentation for StrictMode instead.
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse res = httpClient.execute(new HttpGet("http://www.android.com/favicon.ico"));
                Log.d(TAG, "Fetched http response: " + res);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http2Button = (Button) findViewById(R.id.http2_button);
    http2Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Usually this ends up tripping in DNS resolution,
                // so see http3Button below, which connects directly to an IP
                InputStream is = new URL("http://www.android.com/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http3Button = (Button) findViewById(R.id.http3_button);
    http3Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // One of Google's web IPs, as of 2010-06-16....
                InputStream is = new URL("http://74.125.19.14/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button binderLocalButton = (Button) findViewById(R.id.binder_local_button);
    binderLocalButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mLocalServiceConn.stub.doDiskWrite(123 /* dummy */);
                Log.d(TAG, "local writeToDisk returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "local binderButton error: " + e);
            }
        }
    });

    final Button binderRemoteButton = (Button) findViewById(R.id.binder_remote_button);
    binderRemoteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mRemoteServiceConn.stub.doDiskWrite(1);
                Log.d(TAG, "remote writeToDisk #1 returned: " + value);
                value = mRemoteServiceConn.stub.doDiskWrite(2);
                Log.d(TAG, "remote writeToDisk #2 returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderOneWayButton = (Button) findViewById(R.id.binder_oneway_button);
    binderOneWayButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                Log.d(TAG, "doing oneway disk write over Binder.");
                mRemoteServiceConn.stub.doDiskOneWay();
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderCheckButton = (Button) findViewById(R.id.binder_check_button);
    binderCheckButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int policy;
            try {
                policy = mLocalServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "local service policy: " + policy);
                policy = mRemoteServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "remote service policy: " + policy);
            } catch (RemoteException e) {
                Log.d(TAG, "binderCheckButton error: " + e);
            }
        }
    });

    final Button serviceDumpButton = (Button) findViewById(R.id.service_dump);
    serviceDumpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "About to do a service dump...");
            File file = new File("/sdcard/strictmode-service-dump.txt");
            FileOutputStream output = null;
            final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
            try {
                StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
                output = new FileOutputStream(file);
                StrictMode.setThreadPolicy(oldPolicy);
                boolean dumped = Debug.dumpService("cpuinfo", output.getFD(), new String[0]);
                Log.d(TAG, "Dumped = " + dumped);
            } catch (IOException e) {
                Log.e(TAG, "Can't dump service", e);
            } finally {
                StrictMode.setThreadPolicy(oldPolicy);
            }
            Log.d(TAG, "Did service dump.");
        }
    });

    final Button lingerCloseButton = (Button) findViewById(R.id.linger_close_button);
    lingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(true);
        }
    });

    final Button nonlingerCloseButton = (Button) findViewById(R.id.nonlinger_close_button);
    nonlingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(false);
        }
    });

    final Button leakCursorButton = (Button) findViewById(R.id.leak_cursor_button);
    leakCursorButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            final StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
            try {
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                        .penaltyLog().penaltyDropBox().build());
                db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
                Cursor c = db.rawQuery("SELECT * FROM foo", null);
                c = null; // never close it
                Runtime.getRuntime().gc();
            } finally {
                StrictMode.setVmPolicy(oldPolicy);
            }

        }
    });

    final CheckBox checkNoWrite = (CheckBox) findViewById(R.id.policy_no_write);
    final CheckBox checkNoRead = (CheckBox) findViewById(R.id.policy_no_reads);
    final CheckBox checkNoNetwork = (CheckBox) findViewById(R.id.policy_no_network);
    final CheckBox checkPenaltyLog = (CheckBox) findViewById(R.id.policy_penalty_log);
    final CheckBox checkPenaltyDialog = (CheckBox) findViewById(R.id.policy_penalty_dialog);
    final CheckBox checkPenaltyDeath = (CheckBox) findViewById(R.id.policy_penalty_death);
    final CheckBox checkPenaltyDropBox = (CheckBox) findViewById(R.id.policy_penalty_dropbox);

    View.OnClickListener changePolicy = new View.OnClickListener() {
        public void onClick(View v) {
            StrictMode.ThreadPolicy.Builder newPolicy = new StrictMode.ThreadPolicy.Builder();
            if (checkNoWrite.isChecked())
                newPolicy.detectDiskWrites();
            if (checkNoRead.isChecked())
                newPolicy.detectDiskReads();
            if (checkNoNetwork.isChecked())
                newPolicy.detectNetwork();
            if (checkPenaltyLog.isChecked())
                newPolicy.penaltyLog();
            if (checkPenaltyDialog.isChecked())
                newPolicy.penaltyDialog();
            if (checkPenaltyDeath.isChecked())
                newPolicy.penaltyDeath();
            if (checkPenaltyDropBox.isChecked())
                newPolicy.penaltyDropBox();
            StrictMode.ThreadPolicy policy = newPolicy.build();
            Log.v(TAG, "Changing policy to: " + policy);
            StrictMode.setThreadPolicy(policy);
        }
    };
    checkNoWrite.setOnClickListener(changePolicy);
    checkNoRead.setOnClickListener(changePolicy);
    checkNoNetwork.setOnClickListener(changePolicy);
    checkPenaltyLog.setOnClickListener(changePolicy);
    checkPenaltyDialog.setOnClickListener(changePolicy);
    checkPenaltyDeath.setOnClickListener(changePolicy);
    checkPenaltyDropBox.setOnClickListener(changePolicy);
}

From source file:xyz.klinker.blur.launcher3.Launcher.java

private boolean startActivity(View v, Intent intent, Object tag) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {//from   ww w .j ava 2 s. co  m
        // Only launch using the new animation if the shortcut has not opted out (this is a
        // private contract between launcher and may be ignored in the future).
        boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
        LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
        UserManagerCompat userManager = UserManagerCompat.getInstance(this);

        UserHandleCompat user = null;
        if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) {
            long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1);
            user = userManager.getUserForSerialNumber(serialNumber);
        }

        Bundle optsBundle = null;
        if (useLaunchAnimation) {
            ActivityOptions opts = null;
            if (Utilities.ATLEAST_MARSHMALLOW) {
                int left = 0, top = 0;
                int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
                if (v instanceof TextView) {
                    // Launch from center of icon, not entire view
                    Drawable icon = Workspace.getTextViewIcon((TextView) v);
                    if (icon != null) {
                        Rect bounds = icon.getBounds();
                        left = (width - bounds.width()) / 2;
                        top = v.getPaddingTop();
                        width = bounds.width();
                        height = bounds.height();
                    }
                }
                opts = ActivityOptions.makeClipRevealAnimation(v, left, top, width, height);
            } else if (!Utilities.ATLEAST_LOLLIPOP) {
                // Below L, we use a scale up animation
                opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(),
                        v.getMeasuredHeight());
            } else if (Utilities.ATLEAST_LOLLIPOP_MR1) {
                // On L devices, we use the device default slide-up transition.
                // On L MR1 devices, we a custom version of the slide-up transition which
                // doesn't have the delay present in the device default.
                opts = ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim);
            }
            optsBundle = opts != null ? opts.toBundle() : null;
        }

        if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
            StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
            try {
                // Temporarily disable deathPenalty on all default checks. For eg, shortcuts
                // containing file Uris would cause a crash as penaltyDeathOnFileUriExposure
                // is enabled by default on NYC.
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
                // Could be launching some bookkeeping activity
                startActivity(intent, optsBundle);
            } finally {
                StrictMode.setVmPolicy(oldPolicy);
            }
        } else {
            // TODO Component can be null when shortcuts are supported for secondary user
            launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(),
                    optsBundle);
        }
        return true;
    } catch (SecurityException e) {
        if (Utilities.ATLEAST_MARSHMALLOW && tag instanceof ItemInfo) {
            // Due to legacy reasons, direct call shortcuts require Launchers to have the
            // corresponding permission. Show the appropriate permission prompt if that
            // is the case.
            if (intent.getComponent() == null && Intent.ACTION_CALL.equals(intent.getAction())
                    && checkSelfPermission(
                            Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Rename sPendingAddItem to a generic name.
                sPendingAddItem = preparePendingAddArgs(REQUEST_PERMISSION_CALL_PHONE, intent, 0,
                        (ItemInfo) tag);
                requestPermissions(new String[] { Manifest.permission.CALL_PHONE },
                        REQUEST_PERMISSION_CALL_PHONE);
                return false;
            }
        }
        Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Launcher does not have the permission to launch " + intent
                + ". Make sure to create a MAIN intent-filter for the corresponding activity "
                + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e);
    }
    return false;
}

From source file:com.android.launcher3.Launcher.java

private void startShortcutIntentSafely(Intent intent, Bundle optsBundle, ItemInfo info) {
    try {/*from ww w. j  a  v  a  2  s. c  o  m*/
        StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
        try {
            // Temporarily disable deathPenalty on all default checks. For eg, shortcuts
            // containing file Uri's would cause a crash as penaltyDeathOnFileUriExposure
            // is enabled by default on NYC.
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());

            if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
                String id = ((ShortcutInfo) info).getDeepShortcutId();
                String packageName = intent.getPackage();
                LauncherAppState.getInstance().getShortcutManager().startShortcut(packageName, id,
                        intent.getSourceBounds(), optsBundle, info.user);
            } else {
                // Could be launching some bookkeeping activity
                startActivity(intent, optsBundle);
            }
        } finally {
            StrictMode.setVmPolicy(oldPolicy);
        }
    } catch (SecurityException e) {
        // Due to legacy reasons, direct call shortcuts require Launchers to have the
        // corresponding permission. Show the appropriate permission prompt if that
        // is the case.
        if (intent.getComponent() == null && Intent.ACTION_CALL.equals(intent.getAction())
                && checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

            setWaitingForResult(PendingRequestArgs.forIntent(REQUEST_PERMISSION_CALL_PHONE, intent, info));
            requestPermissions(new String[] { Manifest.permission.CALL_PHONE }, REQUEST_PERMISSION_CALL_PHONE);
        } else {
            // No idea why this was thrown.
            throw e;
        }
    }
}