我正在尝试设计一个使用AsyncTask实现方法的帮助器类。
public interface ResultCallback
{
public String processResult();
}
public class ServerAdapter
{
// Required processResult to call this method. Kind of lousy but I do not know
// how to throw exception from onPostExcecute in AsyncTask.
public String getResult() throws AirplaneModeException, NoNetworkException
{
// code to get return value from Dowork throw exceptions on errors
}
public void getLicense(ResultCallback licenseCallback)
{
...// Set url, outmessage
new Dowork(url, outMessage, licenseCallback).execute();
}
public void queryServer(int queryId, ArrayList<String> args, ResultCallback queryCallback)
{
...// Set url, outmessage
new Dowork(url, outmessage, queryCallback);
}
private class Dowork extends AsyncTask<Void, Void, String>
{
...
private ResultCallback rc;
public Dowork(String url, String outMessage, ResultCallback rc)
{
// code here
}
protected String doInBackground(Void... params)
{
try
{
// code here
}
catch (AirplaneModeException e)
{
return "AirplaneModeException";
}
catch ...
}
protected void onPostExecute(String result)
{
this.result = result;
cb.processResult();
}
}
}
// Client class
public class myclass extends Activity
{
MyServerAdapter myAdapter;
public void onCreate(Bundle savedInstanceState)
{
...
myAdapter = new ServerAdapter();
myAdapter.getLicence(new MyLicenseCallback);
myAdapter.queryServer(id, args, new MyQueryCallback);
...
}
public class MyLicenseCallback extends ResultCallback implements processResult
{
try
{
String result = myAdapter.getResult;
...
}
catch
...
}
...
}
我是Java和Android的新手,有几个问题:
1-几个ServerAdapter方法调用会导致同步问题吗?例如,当MyLicense回调的代码正在运行时,如果onPostExecute调用MyQueryCallback,我是否必须处理它或Java处理它?</ p>
2-如何在回调中抛出异常,而不是像上面的代码那样解决?
答案 0 :(得分:1)
Android保证您的活动中的方法和AsyncTask.onPostExecute
在相同的主UI线程中运行。
您可以使用与结果相同的方式将异常保存在任务实例变量中(在这种情况下返回,比如说null
)。检查是否存在异常以便处理错误情况。
答案 1 :(得分:0)