Android StrictMode 是一个用于检测应用中违反某些代码规范的实用工具
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().build();
StrictMode.setThreadPolicy(policy);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
StrictMode.DiskReadPolicy diskReadPolicy = new StrictMode.DiskReadPolicy.Builder().detectAll().build();
StrictMode.setDiskReadPolicy(diskReadPolicy);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().build();
StrictMode.setThreadPolicy(policy);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().build();
StrictMode.setThreadPolicy(policy);
}
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
// 耗时操作
return null;
}
}.execute();
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.execute(() -> {
// 耗时操作
});
private final MutableLiveData<String> data = new MutableLiveData<>();
public LiveData<String> getData() {
return data;
}
public void fetchData() {
Executors.newSingleThreadExecutor().execute(() -> {
// 耗时操作
String result = "Data";
data.postValue(result);
});
}
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(MyWorker.class)
.build();
WorkManager.getInstance(context).enqueue(request);
总之,Android StrictMode 是一个非常有用的工具,可以帮助你发现和修复应用中的性能问题。通过遵循上述技巧,你可以确保应用在主线程中执行的操作不会影响用户体验。