gpt4 book ai didi

java - 在我的类(class)中实现 Thread Android?

转载 作者:行者123 更新时间:2023-12-01 06:25:29 25 4
gpt4 key购买 nike

我想知道如何在这个类中实现一个线程,以使其免受ANR(应用程序无响应)问题

public class myClass {


private static String LOG_TAG = Root.class.getName();

public boolean isDeviceRooted() throws IOException {

if (checkRootMethod1()){return true;}
if (checkRootMethod2()){return true;}
if (checkRootMethod3()){return true;}
return false;

}
public boolean checkRootMethod1(){
String buildTags = android.os.Build.TAGS;

if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}

public boolean checkRootMethod2(){
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
else {

return false;
}
} catch (Exception e) {

}

return false;
}

public boolean checkRootMethod3() {
if (new ExecShell().executeCommand(SHELL_CMD.check_su_binary) != null){
return true;
}else{
return false;
}
}


}

例如,如果当我按下按钮时执行此代码,如果我多次按下此按钮,我的应用程序就会出现 ANR。

最佳答案

您不想使用 Thread ,但是 AsyncTask 。方法如下:

根据以下内容,确定您的应用需要什么:AsyncTask<TypeOfVarArgParams, ProgressValue, ResultValue>

一些灵感:

public class MyClass {
//Something

public MyClass() {
new BackgroundTask().execute("Hello World");
}
}

private class BackgroundTask extends AsyncTask<String, Void, String> {

@Override
protected void onPreExecute() {
// Prepare your background task. This will be executed before doInBackground
}

@Override
protected String doInBackground(String... params) {
// Your main code goes here

String iAmAString = "I have done something very heavy now...";
return iAmAString;
}

@Override
protected void onPostExecute(String result) {
// Whatever should happen after the background task has completed goes here
}



@Override
protected void onProgressUpdate(Void... values) {
// In here, you can send updates to you UI thread, for example if you're downloading a very large file.
}
}

关于java - 在我的类(class)中实现 Thread Android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19057700/

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