我知道带有线程的 ProgressDialog 问题已被问过很多次,但似乎没有一个解决方案适合我的项目。基本上我想做的是这样的:
1)当用户单击按钮时,活动向服务器发送身份验证请求
2) 执行此操作时会显示 ProgressDialog
3)当响应到来时,我想关闭 ProgressDialog 和由 Activity 读取和解释的返回对象
如果我:
1)设置线程用响应更新Application字段,下一个方法(在线程之外)在访问该字段时抛出NPE
2)如果我在线程中包含下一个方法,第二个方法会抛出“java.lang.RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序”
抱歉,文字很长,但我完全失去了它......我的代码是这样的:
public class XXX extends Activity implements OnClickListener {
// (...)
private SoapObject returnObject;
private String response;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// (...)
authProgressDialog = ProgressDialog.show(XXX.this, "", "Authenticating...", true, false);
new Thread(new Runnable() {
@Override
public void run() {
authenticate(); // method that calls the API via SOAP
authenticateReal(); // method that handles the response
}
}).start();
mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 10:
authProgressDialog.dismiss();
break;
}
}
};
}
}
public void authenticate() {
// API stuff (...)
AndroidHttpTransport aht = new AndroidHttpTransport(URL);
try {
aht.call(SOAP_ACTION, soapEnvelope);
returnObject = (SoapObject) soapEnvelope.getResponse();
response = returnObject.getProperty("ResponseStatus").toString();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
mHandler.sendEmptyMessage(10);
}
}
// Method that needs to access returnObject and reponse objects and
// it is here where the NPE's or other exceptions are thrown
public void authenticateReal() {
// (...)
}
你最好用AsyncTask(这是Android方式):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new TheTask().execute();
}
private class TheTask extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
authProgressDialog = ProgressDialog.show(XXX.this, "", "Authenticating...", true, false);
}
@Override
protected Void doInBackground(Void... params) {
authenticate(); // method that calls the API via SOAP
authenticateReal(); // method that handles the response
return null;
}
@Override
protected void onPostExecute(Void result) {
authProgressDialog.dismiss();
}
}
顺便说一下......我发现这个演示文稿非常有用(它讨论了 REST 应用程序,但您可以将相同的概念应用于不同类型的应用程序):开发 Android REST 客户端应用程序
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)