gpt4 book ai didi

android - StrictMode.ThreadPolicy.Builder 目的和优势?

转载 作者:太空狗 更新时间:2023-10-29 16:40:49 25 4
gpt4 key购买 nike

我从 android 文档中引用了 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 泄漏等在。当您在代码中定义这些策略时,如果定义的严格策略遭到破坏,您的应用程序就会崩溃,这使您可以修复已完成的问题(行为不佳的方法,例如 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();
}

并在 application 标签下设置 AndroidManifest.xml 如下:

android:debuggable="true"

下面我向您展示了仅当我的应用程序处于 Debug模式时才对我的应用程序强制执行 Strictmode 策略(必须在发布它之前删除 list 中的标志)。

希望对您有所帮助。

关于android - StrictMode.ThreadPolicy.Builder 目的和优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18100161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com