[英]java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
[英]Async Task: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我收到以下java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
尝试获取classObject .getNewInstance()的新实例时java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
。
我读过的所有内容都涉及更改UI线程。 是这样吗? 如果是这样,如何解决该异常?
代码( 使用示例 ):
public class MainActivityAsyncClass extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
postData(params[0]);
return null;
}
public void postData(String methodToRun) {
Class[] noParams = {};
try {
Class mainActivityClass = Class.forName("com.MainActivity");
Method asyncRun = mainActivityClass.getDeclaredMethod(methodToRun, noParams);
Object obj = mainActivityClass.newInstance(); //<-- Error is thrown here
asyncRun.invoke(obj, null);
} catch(Exception e){
Util.appendLog("Error in async task. Exception: " + e.getMessage() + " " + e.getStackTrace());
}
}
}
在AsyncTask中:
doInBackground-在后台线程上调用,用于执行后台计算。
onPostExecute-后台计算完成后在UI线程上调用。所有UI更新/启动新活动必须在AsyncTask的onPostExecute函数上完成。
请参阅以下文档
将以下内容添加到您的AsyncTask中以使其工作:
protected void onPostExecute(Long result) {
postData(methodToRun);
}
methodToRun可以是成员变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.