android.os.StrictMode#setThreadPolicy ( )源码实例Demo

下面列出了android.os.StrictMode#setThreadPolicy ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Android-Bridge-App   文件: BridgeApplication.java
@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());
    }
}
 
源代码2 项目: android-test   文件: AccessibilityChecks.java
@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);
  }
}
 
源代码3 项目: 365browser   文件: AndroidSyncSettings.java
/**
 * 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;
    }
}
 
源代码4 项目: Cangol-appcore   文件: AnalyticsServiceImpl.java
/**
 * 设备参数
 * 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;
}
 
源代码5 项目: odyssey   文件: OdysseyApplication.java
@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.");
}
 
源代码7 项目: upcKeygen   文件: UpcKeygenApplication.java
@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());

            }
        }
    }
}
 
源代码8 项目: Cangol-appcore   文件: AnalyticsServiceImpl.java
/**
 * 公共参数
 * 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;
}
 
源代码9 项目: delion   文件: WebappAuthenticator.java
/**
 * @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());
    }
}
 
源代码11 项目: UTubeTV   文件: DUtils.java
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());
  }
}
 
源代码12 项目: bither-android   文件: BitherApplication.java
@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();
}
 
源代码13 项目: android-chromium   文件: SyncStatusHelper.java
@VisibleForTesting
protected void setIsSyncableInternal(Account account) {
    mIsSyncable = 1;
    StrictMode.ThreadPolicy oldPolicy = temporarilyAllowDiskWritesAndDiskReads();
    mSyncContentResolverWrapper.setIsSyncable(account, mContractAuthority, 1);
    StrictMode.setThreadPolicy(oldPolicy);
    mDidUpdate = true;
}
 
源代码14 项目: AndroidComponentPlugin   文件: ActivityThread.java
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);
    }
}
 
源代码16 项目: cronet   文件: StrictModeContext.java
/**
 * 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);
}
 
源代码17 项目: android-utils   文件: MiscUtils.java
/**
 * 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());
    }
}
 
源代码18 项目: JumpGo   文件: BrowserApp.java
@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);
        }
    });
}
 
源代码19 项目: osmdroid   文件: OsmApplication.java
@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()));

}
 
源代码20 项目: yahnac   文件: StrictModeManager.java
public static void initializeStrictMode(StrictMode.VmPolicy.Builder vmPolicyBuilder, StrictMode.ThreadPolicy.Builder threadPolicyBuilder) {
    StrictMode.setThreadPolicy(threadPolicyBuilder.penaltyDeath().build());
    StrictMode.setVmPolicy(vmPolicyBuilder.penaltyDeath().build());
}