我参考了 StrictMode.ThreadPolicy.Builder
自安卓文档 StrictMode.ThreadPolicy.Builder。.
我不清楚 StrictMode.ThreadPolicy.Builder
. 当我们要使用这个类 StrictMode.ThreadPolicy.Builder
. 的优势和目的是什么?StrictMode.ThreadPolicy.Builder
. 我想详细解释一下
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
在你的应用程序中定义stictmode策略的好处是迫使你在开发阶段使你的应用程序在它运行的设备中更加乖巧:避免在UI线程上运行IO操作,避免Activity泄漏,等等.当你在代码中定义这些时,如果定义的strictmode策略已经被破坏,你会使你的应用程序崩溃,这使你修复你所做的问题(不乖巧的方法,如UI线程上的网络操作)。
当我开始一个新项目时,我喜欢先做以下工作。
public class MyApplication extends Application {
private static final String TAG = "MyApplication";
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
Log.w(TAG, "======================================================");
Log.w(TAG, "======= APPLICATION IN STRICT MODE - DEBUGGING =======");
Log.w(TAG, "======================================================");
/**
* Doesn't enable anything on the main thread that related
* to resource access.
*/
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyFlashScreen()
.penaltyDeath()
.build());
/**
* Doesn't enable any leakage of the application's components.
*/
final StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
builder.detectLeakedRegistrationObjects();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
builder.detectFileUriExposure();
}
builder.detectLeakedClosableObjects()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath();
StrictMode.setVmPolicy(builder.build());
}
super.onCreate();
}
}
并将AndroidManifest.xml下的application标签设置为以下内容。
android:debugable="true"
我给你看的以下内容只在我的应用程序处于调试模式时才会强制执行Strictmode政策(在你发布之前必须删除manifest中的标志)。
希望对你有所帮助。