下面列出了android.os.StrictMode#setThreadPolicy ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.BUILD_TYPE != "debug") {
Fabric.with(this, new Crashlytics());
}
DJILogger.init();
instance = this;
//registerActivityLifecycleCallbacks(this);
if (BuildConfig.DEBUG) {
// Detect UI-Thread blockage
//BlockCanary.install(this, new AppBlockCanaryContext()).start();
//// Detect memory leakage
//if (!LeakCanary.isInAnalyzerProcess(this)) {
// LeakCanary.install(this);
//}
// Detect thread violation
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDropBox().penaltyLog().build());
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll()
.penaltyDropBox()
.penaltyLog()
.build());
}
}
@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);
}
}
/**
* Update the three cached settings from the content resolver.
*
* @return Whether either chromeSyncEnabled or masterSyncEnabled changed.
*/
private boolean updateCachedSettings() {
synchronized (mLock) {
boolean oldChromeSyncEnabled = mChromeSyncEnabled;
boolean oldMasterSyncEnabled = mMasterSyncEnabled;
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
if (mAccount != null) {
mIsSyncable =
mSyncContentResolverDelegate.getIsSyncable(mAccount, mContractAuthority)
== 1;
mChromeSyncEnabled = mSyncContentResolverDelegate.getSyncAutomatically(
mAccount, mContractAuthority);
} else {
mIsSyncable = false;
mChromeSyncEnabled = false;
}
mMasterSyncEnabled = mSyncContentResolverDelegate.getMasterSyncAutomatically();
StrictMode.setThreadPolicy(oldPolicy);
return oldChromeSyncEnabled != mChromeSyncEnabled
|| oldMasterSyncEnabled != mMasterSyncEnabled;
}
}
/**
* 设备参数
* os API版本号 版本控制使用
* osVersion 操作系统版本号 4.2.2
* model 设备类型 Note2
* brand 设备制造商 Samsung
* carrier 设备制造商
* screenSize 屏幕物理尺寸
* density density
* densityDpi DPI
* resolution 设备分辨率 800*480
* locale locale
* language 设备语言 Zh
* country 设备国家 Cn
* charset 设备字符集 (utf-8|gbk...)
* ip 设备网络地址 (8.8.8.8)
* mac mac地址
* cpuInfo cpuInfo
* cpuAbi cpuAbi
* mem 内存大小
*
* @return
*/
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public Map<String, String> initDeviceParams() {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
Map<String, String> params = new HashMap<>();
params.put("os", DeviceInfo.getOS());
params.put("osVersion", DeviceInfo.getOSVersion());
params.put("model", DeviceInfo.getDeviceModel());
params.put("brand", DeviceInfo.getDeviceBrand());
params.put("carrier", DeviceInfo.getNetworkOperator(mContext));
params.put("screenSize", DeviceInfo.getScreenSize(mContext));
params.put("density", "" + DeviceInfo.getDensity(mContext));
params.put("densityDpi", DeviceInfo.getDensityDpiStr(mContext));
params.put("resolution", DeviceInfo.getResolution(mContext));
params.put("locale", DeviceInfo.getLocale());
params.put("country", DeviceInfo.getCountry());
params.put("language", DeviceInfo.getLanguage());
params.put("charset", DeviceInfo.getCharset());
params.put("ip", DeviceInfo.getIpStr(mContext));
params.put("mac", DeviceInfo.getMacAddress(mContext));
params.put("cpuABI", DeviceInfo.getCPUABI());
params.put("cpuInfo", DeviceInfo.getCPUInfo());
params.put("memSize", ""+DeviceInfo.getMemTotalSize());
StrictMode.setThreadPolicy(oldPolicy);
return params;
}
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.build());
}
super.onCreate();
}
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.");
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
StrictMode
.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
} else {
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().penaltyLog().build());
}
}
}
}
/**
* 公共参数
* osVersion 操作系统版本号 4.2.2
* deviceId 设备唯一ID Android|IOS均为open-uuid
* platform 平台 平台控制使用IOS|Android
* channelId 渠道 渠道控制使用(Google|baidu|91|appstore…)
* appId AppID
* appVersion App版本号 1.1.0
* sdkVersion 统计SDK版本号
*
* @return
*/
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
protected Map<String, String> initCommonParams() {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
Map<String, String> params = new HashMap<>();
params.put("osVersion", DeviceInfo.getOSVersion());
params.put("deviceId", getDeviceId(mContext));
params.put("platform", DeviceInfo.getOS());
params.put("channelId", getChannelID(mContext));
params.put("appId", getAppID(mContext));
params.put("appVersion", DeviceInfo.getAppVersion(mContext));
params.put("sdkVersion", BuildConfig.VERSION_NAME);
params.put("timestamp", TimeUtils.getCurrentTime());
StrictMode.setThreadPolicy(oldPolicy);
return params;
}
/**
* @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 onCreate() {
super.onCreate();
InjectorHelper.initializeApplicationComponent(this);
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build());
}
}
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());
}
}
@Override
public void onCreate() {
new LinuxSecureRandom();
super.onCreate();
mContext = getApplicationContext();
ueHandler = new UEHandler();
Thread.setDefaultUncaughtExceptionHandler(ueHandler);
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
mAddressDbHelper = new AddressDatabaseHelper(mContext);
mTxDbHelper = new TxDatabaseHelper(mContext);
AndroidDbImpl androidDb = new AndroidDbImpl();
androidDb.construct();
AndroidImplAbstractApp appAndroid = new AndroidImplAbstractApp();
appAndroid.construct();
AbstractApp.notificationService.removeAddressLoadCompleteState();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll()
.permitDiskReads().permitDiskWrites().penaltyLog().build());
Threading.throwOnLockCycles();
initApp();
mBitherApplication = this;
upgrade();
}
@VisibleForTesting
protected void setIsSyncableInternal(Account account) {
mIsSyncable = 1;
StrictMode.ThreadPolicy oldPolicy = temporarilyAllowDiskWritesAndDiskReads();
mSyncContentResolverWrapper.setIsSyncable(account, mContractAuthority, 1);
StrictMode.setThreadPolicy(oldPolicy);
mDidUpdate = true;
}
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);
}
}
private void initFabricLax() {
StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
try {
initFabric();
}
finally {
StrictMode.setThreadPolicy(old);
}
}
/**
* Convenience method for disabling StrictMode for slow calls with try-with-resources.
*/
public static StrictModeContext allowSlowCalls() {
StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(
new StrictMode.ThreadPolicy.Builder(oldPolicy).permitCustomSlowCalls().build());
return new StrictModeContext(oldPolicy);
}
/**
* Enable strict mode.
*
* @param enable the enable flag
*/
public static void enableStrictMode(boolean enable) {
if (enable) {
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());
}
}
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, @NonNull Throwable ex) {
if (BuildConfig.DEBUG) {
FileUtils.writeCrashToStorage(ex);
}
if (defaultHandler != null) {
defaultHandler.uncaughtException(thread, ex);
} else {
System.exit(2);
}
}
});
sAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
sAppComponent.inject(this);
Schedulers.worker().execute(new Runnable() {
@Override
public void run() {
List<HistoryItem> oldBookmarks = LegacyBookmarkManager.destructiveGetBookmarks(BrowserApp.this);
if (!oldBookmarks.isEmpty()) {
// If there are old bookmarks, import them
mBookmarkModel.addBookmarkList(oldBookmarks).subscribeOn(Schedulers.io()).subscribe();
} else if (mBookmarkModel.count() == 0) {
// If the database is empty, fill it from the assets list
List<HistoryItem> assetsBookmarks = BookmarkExporter.importBookmarksFromAssets(BrowserApp.this);
mBookmarkModel.addBookmarkList(assetsBookmarks).subscribeOn(Schedulers.io()).subscribe();
}
}
});
if (mPreferenceManager.getUseLeakCanary() && !isRelease()) {
LeakCanary.install(this);
}
if (!isRelease() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
registerActivityLifecycleCallbacks(new MemoryLeakUtils.LifecycleAdapter() {
@Override
public void onActivityDestroyed(Activity activity) {
Log.d(TAG, "Cleaning up after the Android framework");
MemoryLeakUtils.clearNextServedView(activity, BrowserApp.this);
}
});
}
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
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());
}
Thread.currentThread().setUncaughtExceptionHandler(new OsmUncaughtExceptionHandler());
//https://github.com/osmdroid/osmdroid/issues/366
//super important. Many tile servers, including open street maps, will BAN applications by user
//agent. Do not use the sample application's user agent for your app! Use your own setting, such
//as the app id.
Configuration.getInstance().setUserAgentValue(getPackageName());
BingMapTileSource.retrieveBingKey(this);
final BingMapTileSource source = new BingMapTileSource(null);
new Thread(new Runnable() {
@Override
public void run() {
source.initMetaData();
}
}).start();
source.setStyle(BingMapTileSource.IMAGERYSET_AERIALWITHLABELS);
TileSourceFactory.addTileSource(source);
final BingMapTileSource source2 = new BingMapTileSource(null);
new Thread(new Runnable() {
@Override
public void run() {
source2.initMetaData();
}
}).start();
source2.setStyle(BingMapTileSource.IMAGERYSET_ROAD);
TileSourceFactory.addTileSource(source2);
//FIXME need a key for this TileSourceFactory.addTileSource(TileSourceFactory.CLOUDMADESMALLTILES);
//FIXME need a key for this TileSourceFactory.addTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES);
//the sample app a few additional tile sources that we have api keys for, so add them here
//this will automatically show up in the tile source list
//FIXME this key is expired TileSourceFactory.addTileSource(new HEREWeGoTileSource(getApplicationContext()));
TileSourceFactory.addTileSource(new MapBoxTileSource(getApplicationContext()));
TileSourceFactory.addTileSource(new MapQuestTileSource(getApplicationContext()));
}
public static void initializeStrictMode(StrictMode.VmPolicy.Builder vmPolicyBuilder, StrictMode.ThreadPolicy.Builder threadPolicyBuilder) {
StrictMode.setThreadPolicy(threadPolicyBuilder.penaltyDeath().build());
StrictMode.setVmPolicy(vmPolicyBuilder.penaltyDeath().build());
}