下面列出了怎么用android.os.StrictMode的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Register with Android Sync Manager. This is what causes the "Chrome" option to appear in
* Settings -> Accounts / Sync .
*
* @param account the account to enable Chrome sync on
*/
private void makeSyncable(Account account) {
synchronized (mCachedSettings) {
mCachedSettings.setIsSyncable(account);
}
StrictMode.ThreadPolicy oldPolicy = temporarilyAllowDiskWritesAndDiskReads();
// Disable the syncability of Chrome for all other accounts. Don't use
// our cache as we're touching many accounts that aren't signed in, so this saves
// extra calls to Android sync configuration.
Account[] googleAccounts = AccountManagerHelper.get(mApplicationContext).
getGoogleAccounts();
for (Account accountToSetNotSyncable : googleAccounts) {
if (!accountToSetNotSyncable.equals(account) &&
mSyncContentResolverWrapper.getIsSyncable(
accountToSetNotSyncable, mContractAuthority) > 0) {
mSyncContentResolverWrapper.setIsSyncable(accountToSetNotSyncable,
mContractAuthority, 0);
}
}
StrictMode.setThreadPolicy(oldPolicy);
}
/**
* @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;
}
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
// If using Android-Universal-Image-Loader
// Create global configuration and initialize ImageLoader with default config
// ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
// ImageLoader.getInstance().init(config);
}
@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);
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressWarnings("unused")
@Override
public void onCreate()
{
if (BaseApplication.Config.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
{
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDialog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
}
super.onCreate();
mContext = getApplicationContext();
// 保存文件目录
mVersion = getGVerion();
// XPreferenceManager.putGVersion(mVersion);
// MemoryHelper.loadDefaultVmPolicy();
}
@Override
public void onCreate() {
super.onCreate();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectAll() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
Timber.plant(new Timber.DebugTree());
contributorsService = new ContributorsService();
}
@Override
public int create(Collection<T> paramTs) throws SQLException {
final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
long result = -1;
try {
db.beginTransaction();
for (final T paramT : paramTs) {
result = result + db.insert(mTableName, null, DatabaseUtils.getContentValues(paramT));
}
db.setTransactionSuccessful();
} catch (Exception e) {
throw new SQLException(mTableName, e);
} finally {
db.endTransaction();
}
StrictMode.setThreadPolicy(oldPolicy);
return (int) result;
}
@Override
public void onCreate() {
super.onCreate();
sSharedApplication = this;
Logger.init(TAG)
.logLevel(LogLevel.FULL);
buildComponent();
mComponentApplication.inject(this);
merlin.bind();
final StrictMode.ThreadPolicy loStrictModeThreadPolicy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyDeath()
.build();
StrictMode.setThreadPolicy(loStrictModeThreadPolicy);
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(
new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(
new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
preferences.init(this);
db.open(this);
}
@Override
public Boolean isDaydreamCurrentViewer() {
DaydreamApi daydreamApi = DaydreamApi.create(mContext);
if (daydreamApi == null) return false;
// If this is the first time any app reads the daydream config file, daydream may create its
// config directory... crbug.com/686104
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
int type = GvrApi.ViewerType.CARDBOARD;
try {
type = daydreamApi.getCurrentViewerType();
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
daydreamApi.close();
return type == GvrApi.ViewerType.DAYDREAM;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.detectAll() //for all detectable problems
.penaltyLog()
.penaltyFlashScreen ()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate(savedInstanceState);
Language.setFromPreference(this, "pref_fast_language");
}
@Override
public T queryForId(I paramID, String... columns) throws SQLException {
final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
T obj = null;
try {
final SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
final QueryBuilder queryBuilder = new QueryBuilder(mClazz);
queryBuilder.addQuery(DatabaseUtils.getIdColumnName(mClazz), paramID, "=");
final Cursor cursor = query(db, queryBuilder);
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
obj = DatabaseUtils.cursorToClassObject(mClazz, cursor, columns);
}
cursor.close();
} catch (Exception e) {
throw new SQLException(mTableName, e);
}
StrictMode.setThreadPolicy(oldPolicy);
return obj;
}
public void generateInvoice(OrderEntity orderData) {
ActivityCompat.requestPermissions((BaseActivity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 666);
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
if (Helper.getInstanse().generateInvoice(context, orderData) != null) {
File file = Helper.getInstanse().generateInvoice(context, orderData);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Uri path = Uri.fromFile(file);
Intent pdfOpenIntent = new Intent(Intent.ACTION_VIEW);
pdfOpenIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenIntent.setDataAndType(path, "application/pdf");
try {
context.startActivity(pdfOpenIntent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
ToastHelper.showToast(context,
"No Application Available to View PDF",
Toast.LENGTH_SHORT);
}
} else
ToastHelper.showToast(context,
"ERROR in generating pdf",
Toast.LENGTH_SHORT);
}
}
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;
}
@TargetApi(11)
public static void setStrictMode(boolean enable) {
if (!enable) {
return;
}
StrictMode.ThreadPolicy.Builder threadPolicyBuilder =
new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog();
StrictMode.VmPolicy.Builder vmPolicyBuilder =
new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog();
StrictMode.setThreadPolicy(threadPolicyBuilder.build());
StrictMode.setVmPolicy(vmPolicyBuilder.build());
}
@Override
public int create(T paramT) throws SQLException {
final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
long result = -1;
try {
db.beginTransaction();
result = db.insert(mTableName, null, DatabaseUtils.getContentValues(paramT));
db.setTransactionSuccessful();
} catch (Exception e) {
throw new SQLException(mTableName, e);
} finally {
db.endTransaction();
}
StrictMode.setThreadPolicy(oldPolicy);
return (int) result;
}
@Override
public void onCreate() {
super.onCreate();
AppCompatDelegate.setDefaultNightMode(Preferences.Theme.getAutoDayNightMode(this));
AlgoliaClient.sSortByTime = Preferences.isSortByRecent(this);
mRefWatcher = LeakCanary.install(this);
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyFlashScreen()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
Preferences.migrate(this);
TYPE_FACE = FontCache.getInstance().get(this, Preferences.Theme.getTypeface(this));
AppUtils.registerAccountsUpdatedListener(this);
AdBlocker.init(this, Schedulers.io());
}
private void initStrictMode() {
// Complain loudly of strict mode violations when in debug mode.
if (BuildConfig.DEBUG) {
final StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyFlashScreen()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
final StrictMode.VmPolicy vm_policy = new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setVmPolicy(vm_policy);
logger.info("Strict Mode in effect for the main thread");
}
}
public static void activateStrictMode() {
if (isDebugBuild()) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectAll() // for all detectable problems
.detectDiskReads()
// .detectDiskWrites()
.detectNetwork().penaltyLog()
// .penaltyDialog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.detectActivityLeaks().detectLeakedRegistrationObjects()
// .penaltyDeath()
.build());
}
}
/**
* 设置严苛模式
*/
private void strictMode() {
if (isDebug) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void refresh() {
final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
final Map<String, ?> map = getShared().getAll();
StrictMode.setThreadPolicy(oldPolicy);
mMap.putAll(map);
mCoreApplication.post(new Runnable() {
@Override
public void run() {
mMap.putAll(loadDiskMap());
}
});
}
private static void loadDependencies(
File soFile, int loadFlags, StrictMode.ThreadPolicy threadPolicy) throws IOException {
String[] dependencies = getDependencies(soFile);
Log.d(SoLoader.TAG, "Loading lib dependencies: " + Arrays.toString(dependencies));
for (String dependency : dependencies) {
if (dependency.startsWith("/")) {
continue;
}
SoLoader.loadLibraryBySoName(
dependency, loadFlags | LOAD_FLAG_ALLOW_IMPLICIT_PROVISION, threadPolicy);
}
}
@Override
public boolean isValidPassword() {
StrictMode.noteSlowCall("checking password should only be done in a background thread");
if (!supportVerifyPassword) {
throw new UnsupportedOperationException("support verify password is not enabled");
}
try {
String storedValue = getString(PASSWORD_VALIDATION_KEY, null);
return storedValue != null && Bytes.parseBase64(storedValue).equalsConstantTime(preferencesSalt);
} catch (SecureSharedPreferenceCryptoException e) {
return false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
WoodminSyncAdapter.initializeSyncAdapter(getApplicationContext());
//WoodminSyncAdapter.syncImmediately(getApplicationContext());
//Search
//Intent intentHeader= new Intent(getApplicationContext(), HeadInfoService.class);
//intentHeader.putExtra("search","3339024328");
//startService(intentHeader);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
Log.i("Woodmin", "Permission: " + permissionCheck);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Log.i("Woodmin", "Permission granted");
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
10);
}
}
processIntent(getIntent());
}
/**
* Called by native to check wether the account has an OAuth2 refresh token.
*/
@CalledByNative
public static boolean hasOAuth2RefreshToken(Context context, String accountName) {
// Temporarily allowing disk read while fixing. TODO: http://crbug.com/618096.
// This function is called in RefreshTokenIsAvailable of OAuth2TokenService which is
// expected to be called in the UI thread synchronously.
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
return AccountManagerHelper.get(context).hasAccountForName(accountName);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
@SuppressLint("NewApi")
public static void enableStrictMode() {
if(Utils.hasGingerbread())
{
StrictMode.ThreadPolicy.Builder threadPolicyBuilder =
new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog();
StrictMode.VmPolicy.Builder vmPolicyBuilder =
new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog();
if (Utils.hasHoneycomb()) {
threadPolicyBuilder.penaltyFlashScreen();
vmPolicyBuilder
.setClassInstanceLimit(ImageGridActivity.class, 1);
}
StrictMode.setThreadPolicy(threadPolicyBuilder.build());
StrictMode.setVmPolicy(vmPolicyBuilder.build());
}
}
@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);
}
}
}
@Override
public int loadLibrary(String soName, int loadFlags, StrictMode.ThreadPolicy threadPolicy)
throws IOException {
Object lock = getLibraryLock(soName);
synchronized (lock) {
// Holds a lock on the specific library being loaded to avoid trying to recover it in another
// thread while loading
return loadLibraryFrom(soName, loadFlags, soDirectory, threadPolicy);
}
}
@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);
}
}
}