Man*_*ser 12 android android-strictmode
我已经开始使用Android StrictMode,并发现在开发期间始终运行它并不仅仅是我在git中创建的特殊分支上会很棒.我这样做的原因是我的应用程序要求以1.6及更高版本运行.
我在Android开发者博客上看到你可以设置它,以便通过反射激活它.我只是想知道它实际上是什么样的,如果有可能在这里(或其他地方)记录这些,而不是让所有想要使用它的人自己解决.
我已经阅读了Manfred的博文,但如果您将目标平台版本设置为低于2.3,则该StrictMode.enableDefaults();方法无效,因为方法不可用.
这是我的解决方案,完全依赖于反射,不会产生编译错误:
try {
Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
.getContextClassLoader());
Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread
.currentThread().getContextClassLoader());
Class<?> threadPolicyBuilderClass = Class.forName("android.os.StrictMode$ThreadPolicy$Builder", true,
Thread.currentThread().getContextClassLoader());
Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);
Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
Method buildMethod = threadPolicyBuilderClass.getMethod("build");
Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();
Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);
obj = penaltyMethod.invoke(obj);
Object threadPolicyObject = buildMethod.invoke(obj);
setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);
} catch (Exception ex) {
Log.w(TAG, ex);
}
Run Code Online (Sandbox Code Playgroud)
我看到了你的博文.由于您只想在每个Java文件中最多设置一次StrictMode,因此如何简化代码以调用以下设置是否有意义?
这是一个备用的StrictModeWrapper:
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.StrictMode;
public class StrictModeWrapper {
public static void init(Context context) {
// check if android:debuggable is set to true
int applicationFlags = context.getApplicationInfo().flags;
if ((applicationFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
}
}
Run Code Online (Sandbox Code Playgroud)
从您的代码中,您只需要执行以下操作:
try {
StrictModeWrapper.init(this);
}
catch(Throwable throwable) {
Log.v("StrictMode", "... is not available. Punting...");
}
Run Code Online (Sandbox Code Playgroud)
其中,这是当地的环境,比如你的活动或应用程序或什么的.这似乎适用于2.3之前的Android,并且还使您能够使用Builder类的其他方法完全按照您的意愿配置StrictMode.
| 归档时间: |
|
| 查看次数: |
8265 次 |
| 最近记录: |