在我的Android应用程序中,我有一个MainActivity,我点击一个按钮触发另一个功能:
ImageButton button_1 = (ImageButton) findViewById(R.id.button_trigger);
button_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
webView = (WebView) findViewById(R.id.webViewLayout);
MyClass myCls = new MyClass(getApplicationContext());
myCls.getWebView(authWebView);
}
});
在MyClass类中,我通过以下方式触发AsyncTaks:
RespsonseGetterTask task = new RespsonseGetterTask();
task.execute(parameter);
然后使用postExecute实现:
private class RespsonseGetterTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... args) {
IdTokenResponse response;
try {
response = HttpUtils.request(args);
} catch (IOException e) {
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean wasSuccess) {
if (wasSuccess) {
logger.debug("SUCCESSFULL");
// take actions
} else {
logger.debug("Error");
// take actions on error
}
}
我可以获得一个IdTokenResponse对象,以便我的响应变量具有有效内容。因此响应对象在该尝试范围内,并且我的MainActivity未被注意到最近的结果。
如何向MainActivity发出有关响应(IdTokenResponse)对象的信号?
答案 0 :(得分:1)
返回idTokenResponse而不是布尔值...
private class RespsonseGetterTask extends AsyncTask<String, Void, IdTokenResponse> {
@Override
protected IdTokenResponse doInBackground(String... args) {
IdTokenResponse response = null;
try {
response = HttpUtils.request(args);
} catch (IOException e) {
response = null;
}
return response;
}
...并使用PostExecute根据结果采取行动(在您的UI活动中):
@Override
protected void onPostExecute(IdTokenResponse response) {
if(response != null){
// Take action when your response is not null
}
else{
// Take action when your response is null
}
}
}
答案 1 :(得分:0)
private class RespsonseGetterTask extends AsyncTask<String, Void, IdTokenResponse> {
@Override
protected IdTokenResponse doInBackground(String... args) {
IdTokenResponse response = null;
try {
response = HttpUtils.request(args);
} catch (IOException e) {
response = null;
}
return response;
}
使用上面和按钮调用使用下面的内容:
RespsonseGetterTask task = new RespsonseGetterTask();
task.execute(parameter).get();
if(task!= null){
// Take action when your response is not }else{
// Take action when your response is null}
因此上面的内容允许您将结果返回到单击按钮的类