将参数传递给 Asynctask
我正在使用异步任务从菜单活动中获取字符串并加载一些东西..但我是 无法这样做..我是否以正确的方式使用它并且我是否正确传递参数? 请查看代码片段。谢谢
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
}
}
I am using Async tasks to get string from the menu activity and load up some stuff..but i am
not able to do so..Am i using it in the right way and am i passing the parameters correctly?
Please see the code snippet. thanks
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
避免添加构造函数。
只需在任务执行方法中传递参数即可
现在您的后台类应该如下所示
Avoid adding a constructor.
Simply pass your paramters in the task execute method
Now your background class should look like this
相反,我会
在调用 asynctask 之前检查“标识符”,以防止创建
这样的AsyncTask 的开销
Instead of this i would do
and check for "identifier" before invoking the asynctask to prevent overhead of creating a AsyncTask
like this
一个简单的方法是添加一个构造函数:
A simple way is to add a constructor:
AsyncTask 意味着 doInBackground() 返回 Void,onProgressUpdate() 接受整数参数,而 doInbackground 接受...字符串参数!
因此,您不需要(而且真的不应该)使用 Intent,因为它旨在用于通过活动而不是线程传递参数。
如前所述,您可以为您的类创建一个构造函数和一个名为“标识符”的全局参数
希望它能有所帮助。
问候
AsyncTask means doInBackground() returns Void, onProgressUpdate() takes Integer params and doInbackground takes... String params !
So you don't need (and REALLY shouldn't) use Intent, since it is meant to be used for passing arguments through Activities, not Threads.
And as told before, you can make a constructor and a global parameter to your class called "identifier"
Hoped it could help.
Regards