gpt4 book ai didi

java - 如何重新运行任务

转载 作者:行者123 更新时间:2023-12-01 22:47:20 25 4
gpt4 key购买 nike

我有一个任务正在运行,如果失败,我想再次运行它最多三次。问题是 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();

最佳答案

The issue is that Android gets mad that I'm trying to run a task inside of it's self

除此之外,AsyncTask 是一次性对象。您无法重新execute() AsyncTask 实例。

What's the best way to get around this?

创建 AsyncTask 的新实例。例如,您可以实现一个复制构造函数,用于从先前执行的实例克隆一个新实例。

或者,不要使用AsyncTask

我不能说这些与任何 GenericAsyncTask 的配合效果如何,因为 Android SDK 中没有 GenericAsyncTask

关于java - 如何重新运行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25143657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com