我正在开发一个 Android 应用程序。现在我想使用 AsyncTask。它在 android 4.1 中完美运行,但 doInBackground 方法在 android 2.3.3 中无法运行。 logcat 中没有错误..
我有一个扩展 vom AsyncTask 的类。所以我从 new Class().execute() 开始。构造函数始终有效。
你知道如何解决 android 2.3.3 中的问题吗?
编辑: 我的代码:
private class TopicList extends AsyncTask<String, Integer, String> {
private TopicList(){
Log.e("Constructor","Works");
}
@Override
protected String doInBackground(String... arg0) {
Log.e("InBackground","Works");
new Thread(new Runnable() {
public void run() {
// Network processes
}
}).start();
return null;
}
}
我有目标版本 17 和 minSdkVersion 7。您还需要更多信息吗?我使用以下代码执行它:
new TopicList().execute();
logcat中的错误日志仅显示构造函数有效。
最佳答案
异步任务 API: http://developer.android.com/reference/android/os/AsyncTask.html
阅读上面的文档后,很明显 AsyncTask 在 2.3.3 版本中应该可以正常工作(它是在 API 3 = Android 1.5 中添加的)。
您确定传递的参数正确吗?这是一个异步任务的简单示例,它调用 WebService 并在 Activity 的 TextView 中显示结果,我希望这可以帮助您走上正轨:
private class AsyncTaskWebServiceCaller extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
dialog.setMessage("Connecting to Web Service...");
dialog.show();
}
@Override
protected String doInBackground(Void...voids) {
//create the envelope for the message
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = false;
//get the card (SOAPObject) that will be put into the envelope
SoapObject soapObject = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
envelope.setOutputSoapObject(soapObject);
//put something on the card
PropertyInfo propertyInfo = new PropertyInfo();
propertyInfo.setType(PropertyInfo.STRING_CLASS);
propertyInfo.setName("macAddress");
propertyInfo.setValue(macAddress);
soapObject.addProperty(propertyInfo);
//call WebService
try {
HttpTransportSE httpTransportSE = new HttpTransportSE(SOAP_ADDRESS);
httpTransportSE.debug = true;
httpTransportSE.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
return response.toString();
} catch (Exception e) {
String text = "Oops!! App has crashed with exception: "+e.getMessage() + "\n" + "Stack trace below:\n";
StackTraceElement[] stackTrace = e.getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
text += stackTraceElement.toString() + "\n";
}
return text;
}
}
@Override
protected void onPostExecute(String result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText(result);
}
}
要调用 AsyncTask,只需执行以下操作:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskWebServiceCaller().execute();
}
关于android - 异步任务在 2.3.3 中未运行 doInBackground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15661505/