Android:Asynctask中的多个参数

use*_*684 3 android android-asynctask

我需要将两个参数(lv和位置)传递给Asynctask doInBackground方法,但我不知道它是怎么做的......

LoadSound.execute(lv,position)
class LoadSound extends AsyncTask<**[ListView,int]**, String, String>
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑:

我有一个listView.如果您单击项目播放声音(来自Internet).

我想用Asynctask显示progressDialog.

在doInBackground方法中,我有itemOnClick:

HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Run Code Online (Sandbox Code Playgroud)

因此我需要传递lv和位置.

Ray*_*kud 22

尝试在您的内部创建构造函数,AsyncTask并且无论何时创建对象,都可以传递参数.像这样的东西:

MyAsyncTask asynctask = new MyAsyncTask(10, true, myObject);
//this is how you create your object

 public class MyAsyncTask extends AsyncTask<Void, Void, Void>{

        int a;
        boolean b;
        Object c;

        public MyAsyncTask(int a, boolean b, Object c){
            this.a = a;
            this.b = b;
            this.c = c;
        }

        @Override
        protected Void doInBackground(Void... params) {
            if(b)
                c = a;
            return null;
        }

    }
Run Code Online (Sandbox Code Playgroud)

然后你就可以打电话了 asynctask.execute();

编辑:在阅读更新后的问题后,我同意Squonk使用服务作为播放背景声音; 你也可以在启动你的AsynkTask之前显示一个进度对话框(如果这个是unfinetly)并在你的postexecute中解除它.


Ded*_*ted 8

就像在这个答案中所说,你可以使用一个对象数组作为参数:

private class LoadSound extends AsyncTask<Object, String, String> {
    @Override
    protected void doInBackground(Object... params) {
        ListView lv = (ListView) params[0];
        int position = (Integer) params[1];
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

务必将它们转换为正确的对象类型

这就是如何调用AsyncTask:

LoadSound loadSound = new LoadSound();
loadSound.execute(lv, position);
Run Code Online (Sandbox Code Playgroud)