下面列出了android.os.StrictMode#ThreadPolicy ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void init() {
Display.initDisplay();
Graphics3D.initGraphics3D();
File cacheDir = ContextHolder.getCacheDir();
// Some phones return null here
if (cacheDir != null && cacheDir.exists()) {
for (File temp : cacheDir.listFiles()) {
temp.delete();
}
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitNetwork()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
params.load(false);
}
/**
* @return the public downloads directory.
*/
@SuppressWarnings("unused")
@CalledByNative
private static String getDownloadsDirectory() {
// Temporarily allowing disk access while fixing. TODO: http://crbug.com/508615
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
String downloadsPath;
try {
long time = SystemClock.elapsedRealtime();
downloadsPath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath();
RecordHistogram.recordTimesHistogram("Android.StrictMode.DownloadsDir",
SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
return downloadsPath;
}
/**
* @see #getMacForUrl
*
* @param url The URL to validate.
* @param mac The bytes of a previously-calculated MAC.
*
* @return true if the MAC is a valid MAC for the URL, false otherwise.
*/
public static boolean isUrlValid(Context context, String url, byte[] mac) {
byte[] goodMac = null;
// Temporarily allowing disk access while fixing. TODO: http://crbug.com/525785
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
long time = SystemClock.elapsedRealtime();
goodMac = getMacForUrl(context, url);
sWebappValidationTimes.record(SystemClock.elapsedRealtime() - time);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
if (goodMac == null) {
return false;
}
return constantTimeAreArraysEqual(goodMac, mac);
}
@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);
}
}
}
/**
* @return Which flavor of Herb is being tested.
* See {@link ChromeSwitches#HERB_FLAVOR_ELDERBERRY} and its related switches.
*/
public static String getHerbFlavor() {
Context context = ContextUtils.getApplicationContext();
if (isHerbDisallowed(context)) return ChromeSwitches.HERB_FLAVOR_DISABLED;
if (!sIsHerbFlavorCached) {
sCachedHerbFlavor = null;
// Allowing disk access for preferences while prototyping.
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
sCachedHerbFlavor =
ChromePreferenceManager.getInstance(context).getCachedHerbFlavor();
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
sIsHerbFlavorCached = true;
Log.d(TAG, "Retrieved cached Herb flavor: " + sCachedHerbFlavor);
}
return sCachedHerbFlavor;
}
private void checkCaller() {
if (mVerifiedUid == -1) {
String[] packages = getPackageManager().getPackagesForUid(getCallingUid());
// We need to read Preferences. This should only be called on the Binder thread
// which is designed to handle long running, blocking tasks, so disk I/O should be
// OK.
StrictMode.ThreadPolicy policy = StrictMode.allowThreadDiskReads();
try {
String verifiedPackage = getPreferences(TrustedWebActivityService.this)
.getString(PREFS_VERIFIED_PROVIDER, null);
if (Arrays.asList(packages).contains(verifiedPackage)) {
mVerifiedUid = getCallingUid();
return;
}
} finally {
StrictMode.setThreadPolicy(policy);
}
}
if (mVerifiedUid == getCallingUid()) return;
throw new SecurityException("Caller is not verified as Trusted Web Activity provider.");
}
public StateManager(final ConnectionState connectionState, final StateListener stateListener, final int zone)
{
this.deviceList = null;
this.connectionState = connectionState;
this.stateListener = stateListener;
messageChannel = new MessageChannel(connectionState, inputQueue);
state = new MockupState(zone);
useBmpImages = false;
setPlaybackMode(false);
messageScripts = new ArrayList<>();
messageChannel.start();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
}
private static @Nullable Class<?> getClassByName(
ViewHierarchyElementAndroid view, String className) {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
ClassLoader classLoader = view.getClass().getClassLoader();
if (classLoader != null) {
return classLoader.loadClass(className);
} else {
LogUtils.w(TAG, "Unsuccessful attempt to get ClassLoader to load %1$s", className);
}
} catch (ClassNotFoundException e) {
LogUtils.w(TAG, "Unsuccessful attempt to load class %1$s.", className);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
return null;
}
/**
* 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.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);
}
}
/**
* A helper that is used to load preferences from XML resources without causing a
* StrictModeViolation. See http://crbug.com/692125.
*
* @param preferenceFragment A PreferenceFragment.
* @param preferencesResId The id of the XML resource to add to the PreferenceFragment.
*/
public static void addPreferencesFromResource(
PreferenceFragment preferenceFragment, @XmlRes int preferencesResId) {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
preferenceFragment.addPreferencesFromResource(preferencesResId);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
/**
* Figure out how to route the Intent. Because this is on the critical path to startup, please
* avoid making the pathway any more complicated than it already is. Make sure that anything
* you add _absolutely has_ to be here.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
// Third-party code adds disk access to Activity.onCreate. http://crbug.com/619824
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
TraceEvent.begin("ChromeLauncherActivity");
TraceEvent.begin("ChromeLauncherActivity.onCreate");
try {
super.onCreate(savedInstanceState);
doOnCreate(savedInstanceState);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
TraceEvent.end("ChromeLauncherActivity.onCreate");
}
}
/**
* @see InputMethodManager#hideSoftInputFromWindow(IBinder, int, ResultReceiver)
*/
public boolean hideSoftInputFromWindow(IBinder windowToken, int flags,
ResultReceiver resultReceiver) {
if (DEBUG_LOGS) Log.i(TAG, "hideSoftInputFromWindow");
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites(); // crbug.com/616283
try {
return getInputMethodManager().hideSoftInputFromWindow(
windowToken, flags, resultReceiver);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
private boolean createVrShell() {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
StrictMode.allowThreadDiskWrites();
try {
Constructor<?> vrShellConstructor = mVrShellClass.getConstructor(Activity.class);
mVrShell = (VrShell) vrShellConstructor.newInstance(mActivity);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException e) {
Log.e(TAG, "Unable to instantiate VrShell", e);
return false;
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
return true;
}
/**
* Sets a new StrictMode.ThreadPolicy based on the current one, but allows disk reads
* and disk writes.
*
* The return value is the old policy, which must be applied after the disk access is finished,
* by using StrictMode.setThreadPolicy(oldPolicy).
*
* @return the policy before allowing reads and writes.
*/
private static StrictMode.ThreadPolicy temporarilyAllowDiskWritesAndDiskReads() {
StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
StrictMode.ThreadPolicy.Builder newPolicy =
new StrictMode.ThreadPolicy.Builder(oldPolicy);
newPolicy.permitDiskReads();
newPolicy.permitDiskWrites();
StrictMode.setThreadPolicy(newPolicy.build());
return oldPolicy;
}
/**
* Initializes native code loading for this app; this class's other static facilities cannot be
* used until this {@link #init} is called. This method is idempotent: calls after the first are
* ignored.
*
* @param context application context.
* @param flags Zero or more of the SOLOADER_* flags
* @param soFileLoader
*/
public static void init(Context context, int flags, @Nullable SoFileLoader soFileLoader)
throws IOException {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
try {
isSystemApp = checkIfSystemApp(context, flags);
initSoLoader(soFileLoader);
initSoSources(context, flags, soFileLoader);
if (!NativeLoader.isInitialized()) {
NativeLoader.init(new NativeLoaderToSoLoaderDelegate());
}
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
@Override
protected MapView createViewInstance(ThemedReactContext reactContent) {
AMapOptions options = new AMapOptions();
options.zoomControlsEnabled(false);
//options.zoomGesturesEnabled(false);
//options.rotateGesturesEnabled(false);
mapView = new MapView(reactContent, options);
mapView.onCreate(null);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
map = mapView.getMap();
eventDispatcher = reactContent.getNativeModule(UIManagerModule.class).getEventDispatcher();
return mapView;
}
private void updateMasterSyncAutomaticallySetting() {
StrictMode.ThreadPolicy oldPolicy = temporarilyAllowDiskWritesAndDiskReads();
synchronized (mCachedSettings) {
mCachedMasterSyncAutomatically = mSyncContentResolverWrapper
.getMasterSyncAutomatically();
}
StrictMode.setThreadPolicy(oldPolicy);
}
public void enableStrictMode()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/**
* 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 && UrlConstants.CONTENT_SCHEME.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.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);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new LoggingExceptionHandler());
setContentView(R.layout.activity_main);
// App bar
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
int stackTopIndex = getSupportFragmentManager().getBackStackEntryCount() - 1;
if (stackTopIndex >= 0) {
toolbar.setTitle(getSupportFragmentManager().getBackStackEntryAt(stackTopIndex).getName());
} else {
toolbar.setTitle(R.string.app_name);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Disable fullscreen mode
getSupportActionBar().show();
getWindow().getDecorView().setSystemUiVisibility(0);
}
}
});
waltDevice = WaltDevice.getInstance(this);
// Create front page fragment
FrontPageFragment frontPageFragment = new FrontPageFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, frontPageFragment);
transaction.commit();
logger = SimpleLogger.getInstance(this);
broadcastManager = LocalBroadcastManager.getInstance(this);
// Add basic version and device info to the log
logger.log(String.format("WALT v%s (versionCode=%d)",
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE));
logger.log("WALT protocol version " + WaltDevice.PROTOCOL_VERSION);
logger.log("DEVICE INFO:");
logger.log(" " + Build.FINGERPRINT);
logger.log(" Build.SDK_INT=" + Build.VERSION.SDK_INT);
logger.log(" os.version=" + System.getProperty("os.version"));
// Set volume buttons to control media volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
requestSystraceWritePermission();
// Allow network operations on the main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}