【发布时间】:2014-09-28 09:37:39
【问题描述】:
我有一个任务正在运行,如果它失败了,我想再次运行它最多 3 次。问题是 Android 会因为我试图在它自己内部运行一个任务而生气。解决此问题的最佳方法是什么?
代码(查看底部task.callback):
final GenericAsyncTask task = new GenericAsyncTask();
task.background = new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(GCMIntentService.this.host);
String addremove = "add";
if(register == false) addremove = "remove";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("cmd", addremove));
nameValuePairs.add(new BasicNameValuePair("subscription_key", SUBSCRIPTION_KEY)); // unique per app
nameValuePairs.add(new BasicNameValuePair("token", str));
nameValuePairs.add(new BasicNameValuePair("os_family", "android"));
if(addremove.equals("remove")) nameValuePairs.add(new BasicNameValuePair("hard", "" + hard));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(entity);
Log.i(LCHApplication.TAG, "Name Value Pairs: " + nameValuePairs.toString());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
task.result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
};
task.callback = new Runnable() {
public void run() {
try {
Log.i(LCHApplication.TAG, "registration response: " + task.result.toString());
} catch(Exception e) {
if(attempts++ < ATTEMPTS_LIMIT) {
// try to register the device again
task.execute();
} else {
Crashlytics.logException(e);
}
}
}
};
task.execute();
【问题讨论】:
标签: java android android-asynctask illegalstateexception