Java Code Examples for android.os.StrictMode#allowThreadDiskWrites()

The following examples show how to use android.os.StrictMode#allowThreadDiskWrites() . 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: SearchWidgetProvider.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/** Updates the number of consecutive crashes this widget has absorbed. */
@SuppressLint({"ApplySharedPref", "CommitPrefEdits"})
static void updateNumConsecutiveCrashes(int newValue) {
    SharedPreferences prefs = getDelegate().getSharedPreferences();
    if (getNumConsecutiveCrashes(prefs) == newValue) return;

    SharedPreferences.Editor editor = prefs.edit();
    if (newValue == 0) {
        editor.remove(PREF_NUM_CONSECUTIVE_CRASHES);
    } else {
        editor.putInt(PREF_NUM_CONSECUTIVE_CRASHES, newValue);
    }

    // This metric is committed synchronously because it relates to crashes.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        editor.commit();
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 2
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void onUidStateChanged(int uid, int procState, long procStateSeq) throws RemoteException {
    synchronized (this) {
        final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
        try {
            mPw.print(uid);
            mPw.print(" procstate ");
            mPw.print(ProcessList.makeProcStateString(procState));
            mPw.print(" seq ");
            mPw.println(procStateSeq);
            mPw.flush();
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
}
 
Example 3
Source File: WebappDirectoryManager.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the directory for a web app, creating it if necessary.
 * @param webappId ID for the web app.  Used as a subdirectory name.
 * @return File for storing information about the web app.
 */
File getWebappDirectory(Context context, String webappId) {
    // Temporarily allowing disk access while fixing. TODO: http://crbug.com/525781
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        long time = SystemClock.elapsedRealtime();
        File webappDirectory = new File(getBaseWebappDirectory(context), webappId);
        if (!webappDirectory.exists() && !webappDirectory.mkdir()) {
            Log.e(TAG, "Failed to create web app directory.");
        }
        RecordHistogram.recordTimesHistogram("Android.StrictMode.WebappDir",
                SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);
        return webappDirectory;
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 4
Source File: AccessibilityChecks.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
  if (noViewFoundException != null) {
    Log.e(
        TAG,
        String.format(
            "'accessibility checks could not be performed because view '%s' was not"
                + "found.\n",
            noViewFoundException.getViewMatcherDescription()));
    throw noViewFoundException;
  }
  if (view == null) {
    throw new NullPointerException();
  }
  StrictMode.ThreadPolicy originalPolicy = StrictMode.allowThreadDiskWrites();
  try {
    CHECK_EXECUTOR.checkAndReturnResults(view);
  } finally {
    StrictMode.setThreadPolicy(originalPolicy);
  }
}
 
Example 5
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void onUidIdle(int uid, boolean disabled) throws RemoteException {
    synchronized (this) {
        final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
        try {
            mPw.print(uid);
            mPw.print(" idle");
            if (disabled) {
                mPw.print(" disabled");
            }
            mPw.println();
            mPw.flush();
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
}
 
Example 6
Source File: DaoImpl.java    From Cangol-appcore with Apache License 2.0 6 votes vote down vote up
@Override
public T refresh(T paramT, String... columns) throws SQLException {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    T result = null;
    try {
        final SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
        final QueryBuilder queryBuilder = new QueryBuilder(mClazz);
        queryBuilder.addQuery(DatabaseUtils.getIdColumnName(mClazz), DatabaseUtils.getIdValue(paramT), "=");
        final Cursor cursor = query(db, queryBuilder);
        if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            result = DatabaseUtils.cursorToObject(paramT, cursor, columns);
        }
        cursor.close();
    } catch (Exception e) {
        throw new SQLException(mTableName, e);
    }
    StrictMode.setThreadPolicy(oldPolicy);
    return result;
}
 
Example 7
Source File: LauncherShortcutActivity.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String intentAction = getIntent().getAction();

    // Exit early if the original intent action isn't for opening a new tab.
    if (!intentAction.equals(ACTION_OPEN_NEW_TAB)
            && !intentAction.equals(ACTION_OPEN_NEW_INCOGNITO_TAB)) {
        finish();
        return;
    }

    Intent newIntent = new Intent();
    newIntent.setAction(Intent.ACTION_VIEW);
    newIntent.setData(Uri.parse(UrlConstants.NTP_URL));
    newIntent.setClass(this, ChromeLauncherActivity.class);
    newIntent.putExtra(IntentHandler.EXTRA_INVOKED_FROM_SHORTCUT, true);
    newIntent.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true);
    newIntent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
    IntentHandler.addTrustedIntentExtras(newIntent);

    if (intentAction.equals(ACTION_OPEN_NEW_INCOGNITO_TAB)) {
        newIntent.putExtra(IntentHandler.EXTRA_OPEN_NEW_INCOGNITO_TAB, true);
    }

    // This system call is often modified by OEMs and not actionable. http://crbug.com/619646.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        startActivity(newIntent);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    finish();
}
 
Example 8
Source File: DaoImpl.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
@Override
public int update(T paramT, String... columns) throws SQLException {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
    int result = -1;
    try {
        result = db.update(mTableName, DatabaseUtils.getContentValues(paramT, columns), DatabaseUtils.getIdColumnName(mClazz) + "=?", new String[]{"" + DatabaseUtils.getIdValue(paramT)});
    } catch (Exception e) {
        throw new SQLException(mTableName, e);
    }
    StrictMode.setThreadPolicy(oldPolicy);
    return result;
}
 
Example 9
Source File: Locales.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Is only required by locale aware activities, AND  Application. In most cases you should be
 * using LocaleAwareAppCompatActivity or friends.
 * @param context
 */
public static void initializeLocale(Context context) {
    final LocaleManager localeManager = LocaleManager.getInstance();
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        localeManager.getAndApplyPersistedLocale(context);
    } finally {
        StrictMode.setThreadPolicy(savedPolicy);
    }
}
 
Example 10
Source File: DaoImpl.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
@Override
public int updateById(T paramT, I paramID, String... columns) throws SQLException {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();

    final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
    int result = -1;
    try {
        result = db.update(mTableName, DatabaseUtils.getContentValues(paramT, columns), DatabaseUtils.getIdColumnName(mClazz) + "=?", new String[]{"" + paramID});
    } catch (Exception e) {
        throw new SQLException(mTableName, e);
    }
    StrictMode.setThreadPolicy(oldPolicy);
    return result;
}
 
Example 11
Source File: Locales.java    From firefox-echo-show with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Is only required by locale aware activities, AND  Application. In most cases you should be
 * using LocaleAwareAppCompatActivity or friends.
 * @param context
 */
public static void initializeLocale(Context context) {
    final LocaleManager localeManager = LocaleManager.getInstance();
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        localeManager.getAndApplyPersistedLocale(context);
    } finally {
        StrictMode.setThreadPolicy(savedPolicy);
    }
}
 
Example 12
Source File: MainActivity.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static void ensureFolder() {
  StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
  try {
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
  } finally {
    StrictMode.setThreadPolicy(oldPolicy);
  }
}
 
Example 13
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void onOomAdjMessage(String msg) {
    synchronized (this) {
        final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
        try {
            mPw.print("# ");
            mPw.println(msg);
            mPw.flush();
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
}
 
Example 14
Source File: BookmarkWidgetService.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@SuppressLint("DefaultLocale")
static SharedPreferences getWidgetState(Context context, int widgetId) {
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        return context.getSharedPreferences(
                String.format("widgetState-%d", widgetId),
                Context.MODE_PRIVATE);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 15
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void onUidActive(int uid) throws RemoteException {
    synchronized (this) {
        final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
        try {
            mPw.print(uid);
            mPw.println(" active");
            mPw.flush();
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
}
 
Example 16
Source File: ActivityThread.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private void handleDumpProvider(DumpComponentInfo info) {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        ProviderClientRecord r = mLocalProviders.get(info.token);
        if (r != null && r.mLocalProvider != null) {
            PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
            r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
            pw.flush();
        }
    } finally {
        IoUtils.closeQuietly(info.fd);
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 17
Source File: QueuedWork.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Trigger queued work to be processed immediately. The queued work is processed on a separate
 * thread asynchronous. While doing that run and process all finishers on this thread. The
 * finishers can be implemented in a way to check weather the queued work is finished.
 *
 * Is called from the Activity base class's onPause(), after BroadcastReceiver's onReceive,
 * after Service command handling, etc. (so async work is never lost)
 */
public static void waitToFinish() {
    long startTime = System.currentTimeMillis();
    boolean hadMessages = false;

    Handler handler = getHandler();

    synchronized (sLock) {
        if (handler.hasMessages(QueuedWorkHandler.MSG_RUN)) {
            // Delayed work will be processed at processPendingWork() below
            handler.removeMessages(QueuedWorkHandler.MSG_RUN);

            if (DEBUG) {
                hadMessages = true;
                Log.d(LOG_TAG, "waiting");
            }
        }

        // We should not delay any work as this might delay the finishers
        sCanDelay = false;
    }

    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        processPendingWork();
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    try {
        while (true) {
            Runnable finisher;

            synchronized (sLock) {
                finisher = sFinishers.poll();
            }

            if (finisher == null) {
                break;
            }

            finisher.run();
        }
    } finally {
        sCanDelay = true;
    }

    synchronized (sLock) {
        long waitTime = System.currentTimeMillis() - startTime;

        if (waitTime > 0 || hadMessages) {
            mWaitTimes.add(Long.valueOf(waitTime).intValue());
            mNumWaits++;

            if (DEBUG || mNumWaits % 1024 == 0 || waitTime > MAX_WAIT_TIME_MILLIS) {
                mWaitTimes.log(LOG_TAG, "waited: ");
            }
        }
    }
}
 
Example 18
Source File: StrictModeContext.java    From cronet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Convenience method for disabling StrictMode for disk-writes with try-with-resources.
 */
public static StrictModeContext allowDiskWrites() {
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    return new StrictModeContext(oldPolicy);
}
 
Example 19
Source File: ChromeLauncherActivity.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Handles launching a {@link ChromeTabbedActivity}.
 * @param skipFre Whether skip the First Run Experience in ChromeTabbedActivity.
 */
@SuppressLint("InlinedApi")
private void launchTabbedMode(boolean skipFre) {
    maybePrefetchDnsInBackground();

    Intent newIntent = new Intent(getIntent());
    String className = MultiWindowUtils.getInstance().getTabbedActivityForIntent(
            newIntent, this).getName();
    newIntent.setClassName(getApplicationContext().getPackageName(), className);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        newIntent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
    }
    Uri uri = newIntent.getData();
    boolean isContentScheme = false;
    if (uri != null && "content".equals(uri.getScheme())) {
        isContentScheme = true;
        newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
    if (mIsInLegacyMultiInstanceMode) {
        MultiWindowUtils.getInstance().makeLegacyMultiInstanceIntent(this, newIntent);
    }
    if (skipFre) {
        newIntent.putExtra(FirstRunFlowSequencer.SKIP_FIRST_RUN_EXPERIENCE, true);
    }

    // This system call is often modified by OEMs and not actionable. http://crbug.com/619646.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        startActivity(newIntent);
    } catch (SecurityException ex) {
        if (isContentScheme) {
            Toast.makeText(
                    this, R.string.external_app_restricted_access_error,
                    Toast.LENGTH_LONG).show();
        } else {
            throw ex;
        }
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 20
Source File: ChromeActivity.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * This function builds the {@link CompositorViewHolder}.  Subclasses *must* call
 * super.setContentView() before using {@link #getTabModelSelector()} or
 * {@link #getCompositorViewHolder()}.
 */
@Override
protected final void setContentView() {
    final long begin = SystemClock.elapsedRealtime();
    TraceEvent.begin("onCreate->setContentView()");

    enableHardwareAcceleration();
    setLowEndTheme();
    int controlContainerLayoutId = getControlContainerLayoutId();
    WarmupManager warmupManager = WarmupManager.getInstance();
    if (warmupManager.hasViewHierarchyWithToolbar(controlContainerLayoutId)) {
        View placeHolderView = new View(this);
        setContentView(placeHolderView);
        ViewGroup contentParent = (ViewGroup) placeHolderView.getParent();
        warmupManager.transferViewHierarchyTo(contentParent);
        contentParent.removeView(placeHolderView);
    } else {
        warmupManager.clearViewHierarchy();

        // Allow disk access for the content view and toolbar container setup.
        // On certain android devices this setup sequence results in disk writes outside
        // of our control, so we have to disable StrictMode to work. See crbug.com/639352.
        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
        try {
            setContentView(R.layout.main);
            if (controlContainerLayoutId != NO_CONTROL_CONTAINER) {
                ViewStub toolbarContainerStub =
                        ((ViewStub) findViewById(R.id.control_container_stub));

                toolbarContainerStub.setLayoutResource(controlContainerLayoutId);
                View container = toolbarContainerStub.inflate();
            }

            // It cannot be assumed that the result of toolbarContainerStub.inflate() will be
            // the control container since it may be wrapped in another view.
            ControlContainer controlContainer =
                    (ControlContainer) findViewById(R.id.control_container);

            // Inflate the correct toolbar layout for the device.
            int toolbarLayoutId = getToolbarLayoutId();
            if (toolbarLayoutId != NO_TOOLBAR_LAYOUT && controlContainer != null) {
                controlContainer.initWithToolbar(toolbarLayoutId);
            }

            // Get a handle to the bottom sheet if using the bottom control container.
            if (controlContainerLayoutId == R.layout.bottom_control_container) {
                View coordinator = findViewById(R.id.coordinator);
                mBottomSheet = (BottomSheet) findViewById(R.id.bottom_sheet);
                mBottomSheet.init(coordinator, controlContainer.getView(), this);
            }
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
    TraceEvent.end("onCreate->setContentView()");
    mInflateInitialLayoutDurationMs = SystemClock.elapsedRealtime() - begin;

    // Set the status bar color to black by default. This is an optimization for
    // Chrome not to draw under status and navigation bars when we use the default
    // black status bar
    setStatusBarColor(null, Color.BLACK);

    ViewGroup rootView = (ViewGroup) getWindow().getDecorView().getRootView();
    mCompositorViewHolder = (CompositorViewHolder) findViewById(R.id.compositor_view_holder);
    mCompositorViewHolder.setRootView(rootView);

    // Setting fitsSystemWindows to false ensures that the root view doesn't consume the insets.
    rootView.setFitsSystemWindows(false);

    // Add a custom view right after the root view that stores the insets to access later.
    // ContentViewCore needs the insets to determine the portion of the screen obscured by
    // non-content displaying things such as the OSK.
    mInsetObserverView = InsetObserverView.create(this);
    rootView.addView(mInsetObserverView, 0);
}