下面列出了android.os.StrictMode#allowThreadDiskWrites ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** 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);
}
}
@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);
}
}
}
@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);
}
}
}
@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;
}
@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);
}
}
/**
* 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);
}
}
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);
}
}
@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);
}
}
}
@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);
}
}
@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);
}
}
}
private static void ensureFolder() {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
try {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
/**
* 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);
}
}
@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;
}
/**
* 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);
}
}
@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;
}
@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();
}
/**
* 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);
}
/**
* 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);
}
}
/**
* 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: ");
}
}
}
}
/**
* 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);
}