如何在 AsyncTask 中调用方法?在我的 asynctask 中,这是我的 java 文件“xyz”中的一个内部类,当用户单击一个按钮时,它应该调用“xyz”中的一个方法,该方法也恰好是一个 alertDialog,我知道它会调用它,但是当它到达该方法时,应用程序崩溃并给出运行时异常,提示“无法在未调用 Looper.prepare() 的线程内创建处理程序”。我在这里查找了示例,但它引发了相同的运行时异常。我怎样才能让它工作?从 asynctask 中调用外部方法不是可能的吗?这是调用该方法的片段:
private class DownloadFilesTask extends AsyncTask<Void,Void,Void> {
private LoginActivity loginActivity;
public DownloadFilesTask(LoginActivity loginActivity){
this.loginActivity=loginActivity;
}
@Override
protected Void doInBackground(Void... voids) {
long start=System.currentTimeMillis();
in=null;
try {
website=new URI(URL);
request.setURI(website);
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpPost httpPost=new HttpPost(URL);
List<NameValuePair>nameValuePairs=new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pwd",pwd));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
response=httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
try {
in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
try {
String line=in.readLine();
long end=System.currentTimeMillis();
long times=end-start;
String time=String.valueOf(times);
System.out.println(name);
System.out.println(NAME_PATTERN);
System.out.println(pwd);
System.out.println(PWD_PATTERN);
if (name.equals(NAME_PATTERN) && (pwd.equals(PWD_PATTERN))) {
bloggedIn=true;
System.out.println("Youre right");
}else
{
bloggedIn=false;
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void onPostExecute(String line, String time) {
if(bloggedIn=true){
navigateToMainActivity(time);
}else{ if (bloggedIn=false){
newp(line,time);
}
}
}
}
这就是所谓的方法:
public void navigateToMainActivity(String timetoo) {
al=new AlertDialog.Builder(LoginActivity.this);
al.setTitle("Welcome");
al.setMessage("Hey there");
al.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(LoginActivity.this, Main.class));
}
});
al.show();
}