How can you pass multiple primitive parameters to AsyncTask?

后端 未结 6 673
情歌与酒
情歌与酒 2020-11-27 10:36

There are related questions, such as How can I pass in 2 parameters to a AsyncTask class? , but I ran into the difficulty of trying in vain to pass multiple primitives as pa

6条回答
  •  抹茶落季
    2020-11-27 11:02

    I like malajisi's method, but if you didn't, couldn't you use the Bundle class?

     Bundle myBundle = new Bundle();
     myBundle.putInt("foo", foo);
     myBundle.putLong("bar", bar);
     myBundle.putDouble("arple", arple);
    

    Then just pass the bundle and unpack it inside MyTask. Is this a terrible idea? You avoid creating a custom class, and it's flexible if you decide you need to pass additional parameters later.

    Update: It has been quite a few years since I wrote this answer, and I really dislike it now. I would recommend against using a Bundle. If you need to pass multiple parameters into an asynctask (or anything, really), use a custom class that holds all your parameters at once. Using a bundle is a fine solution to a problem you shouldn't have. There is no law against creating a custom class to hold exactly what you need, and nothing else.

    Also, why aren't you using coroutines? Asynctasks are so 2014.

提交回复
热议问题