我正在使用异步任务从菜单活动中获取字符串并加载一些stuff..but,我无法以正确的方式使用它,我是否正确地传递了参数?请参阅代码片段。谢谢
private class Setup extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
if (!(getIntent().getExtras().isEmpty())) {
Bundle gotid = getIntent().getExtras();
identifier = gotid.getString("key");
}
} catch (Exception e) {
e.getStackTrace();
} finally {
if (identifier.matches("abc")) {
publishProgress(0);
db.insert_fri();
} else if ((identifier.matches("xyz"))) {
publishProgress(1);
db.insert_met();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... i) {
// start the song here
if (i[0] == 0) {
song.setLooping(true);
song.start();
}
}
@Override
protected void onPostExecute(Void res) {
}
@Override
protected void onPreExecute() {
// do something before execution
}
}
发布于 2013-08-04 17:23:50
避免添加构造函数。
只需在任务执行方法中传递参数
new BackgroundTask().execute(a, b, c); // can have any number of params
现在,您的背景类应该如下所示
public class BackgroundTask extends AsyncTask<String, Integer, Long> {
@Override
protected Long doInBackground(String... arg0) {
// TODO Auto-generated method stub
String a = arg0[0];
String b = arg0[1];
String c = arg0[2];
//Do the heavy task with a,b,c
return null;
}
//you can keep other methods as well postExecute , preExecute, etc
}
发布于 2011-09-04 01:58:27
不是这样,我会这么做
private class Setup extends AsyncTask<String, Integer, Void> {
@Override
protected Void doInBackground(String... params) {
String identifier = params[0];
if (identifier.matches("abc")) {
publishProgress(0);
db.insert_fri();
} else if ((identifier.matches("xyz"))) {
publishProgress(1);
db.insert_met();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... i) {
// start the song here
if (i[0] == 0) {
song.setLooping(true);
song.start();
}
}
@Override
protected void onPostExecute(Void res) {
}
@Override
protected void onPreExecute() {
// do something before execution
}
}
并在调用异步任务之前检查“asynctask”,以防止创建异步任务的开销
像这样
if (!(getIntent().getExtras().isEmpty())) {
Bundle gotid = getIntent().getExtras();
identifier = gotid.getString("key");
new Setup().execute(identifier);
}
发布于 2011-09-04 04:50:30
一种简单的方法是添加一个构造函数:
public Setup(String a, Int b) {
this.a = a;
this.b = b;
}
https://stackoverflow.com/questions/7294533
复制相似问题