Reputation: 11642
i trying to send email as assync task. But i don't know how exactly to pass different params into doInBackground?
I want to pass data like this:
Context ctx, String typeOfEmail , Map data
How can i pass it into AsyncTask class?
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Executed";
}
public boolean sendLogsByEmail(Context ctx, String typeOfEmail , Map<String, String> data) {
Thanks for any advice.
Upvotes: 1
Views: 556
Reputation: 12919
Just declare the arguments to be of the common supertype of the objects you want to pass, which is Object
.:
private class LongOperation extends AsyncTask<Object, Void, String> {
@Override
protected String doInBackground(Object... params) {
Context c = (Context) params[0];
String typeOfEmail = (String) params[1];
Map data = (Map) params[2];
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Executed";
}
Now call execute like this:
myLongOperation.execute(context, emailType, data);
Upvotes: 0
Reputation: 2336
You can do like this
new LongOperation().execute(new String[5]/* or add many parameter of string type*/);
You can also create a arg constructor in class LongOperation and then pass within the constructor while creating obj.
Upvotes: 0
Reputation: 13761
When you are defining an AsyncTask
, you're extending its class. So nothing prevents you from implementing your own methods too, you could simply define:
public void my_vars(Context context, String str, Map map) { mycontext = context; mystr = str, mymap = map; }
and call it before calling your execute()
method.
Upvotes: 0
Reputation: 49986
For more complex parameters you can add constructor:
public LongOperation (Context ctx, String typeOfEmail, Map data) {
/// here initialize LongOperation class instance fields
}
also, its safier to put Context into WeakReference inside your AsyncTask, so it would look like:
WeakReference<Context> ctx;
and then use:
Context ctxe = ctx.get();
if ( ctxe != null ) {
// do something with Context
}
this way you will not introduce reference leaks that might happend during configuration changes/or normal activity lifecycle. But since your AsyncTask is internal to activity class (I suppose from your code), then it already has implicit reference to enclosing class - which is probably Activity.
Upvotes: 2