簡體   English   中英

Android中的StrictMode類

[英]StrictMode class in Android

我正在android中基於網絡的項目上工作,因此,為了防止由於Can't do network operation on UI Thread而在Android ICS上強制關閉,我必須使用下面的代碼部分,或者嘗試在其他線程上啟動我的網絡操作,但我不想更改基本代碼,因此我應該在Android ICS上使用以下代碼。

static {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

如何使唯一的apk文件在所有android版本(> = 1.6)中運行? android.os.StrictMode可用於更高版本的android,因此,我無法嘗試在我的Android Activity中使用上述代碼的一部分。 因此,哪種解決方案更好:

  1. 使用Reflections在更高版本的API上運行這部分代碼( As oracle docs, reflective operations have slower performance than their non-reflective counterparts
  2. 將我的android構建目標更改為Android 4.1.1(API 16)並嘗試在AndroidManifest.xml上更改android:minSdkVersion

或者,如果您知道任何更好的方法,請告訴我。

提前致謝 :)

您可以使用BUILD.VERSION和Reflection來克服此兼容性問題(已測試)。

    if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9) {
        try {
            // StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
            Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
                    .getContextClassLoader());
            Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread.currentThread()
                    .getContextClassLoader());
            Field laxField = threadPolicyClass.getField("LAX");
            Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);
            setThreadPolicyMethod.invoke(strictModeClass, laxField.get(null));
        } catch (Exception e) {
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM