gpt4 book ai didi

java - Android中无法使用线程

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

我想从我的 onCreateView 方法启动另一个线程,如下所示:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
public void run(){
checkRoot();
}
}).start();
}

但我在 logcat 中收到此错误:

06-16 12:52:37.088: E/AndroidRuntime(9707): FATAL EXCEPTION: Thread-804
06-16 12:52:37.088: E/AndroidRuntime(9707): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我知道我可以使用AsyncTask,但我想使用上述方法只是出于好奇。

这是checkRoot方法:

private void checkRoot(){
Process p;
try{
// Preform su to get root privledges
p = Runtime.getRuntime().exec("su");

// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("mount -o rw,remount -t yaffs2 /dev/block/mtdblock0 /system\n");
os.writeBytes("echo \"Do I have root?\" >/system/etc/temporary.txt\n");

// Close the terminal
os.writeBytes("exit\n");
os.flush();

try{
p.waitFor();
if(p.exitValue() != 225){
showToast("ROOTED !");
} else {
showToast("not root");
setContentView(R.layout.no_root);
}
} catch(InterruptedException e){
showToast("not root");
setContentView(R.layout.no_root);
}
} catch(IOException e){
showToast("not root");
setContentView(R.layout.no_root);
}
}

最佳答案

您无法从后台线程更新 ui。您应该从 ui 线程更新 ui。

    showToast("not root");
setContentView(R.layout.no_root);

使用runonUithread

      runOnUiThread(new Runnable() //run on ui threa
{
public void run()
{

}
});

对于同一个 Activity 两次使用 setContentView 也不是一个好的设计。重新思考您的设计。

您还可以使用处理程序

关于java - Android中无法使用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17131103/

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