I have a class that extends AsyncTask to send an ethernet message. When created and called within my MainActivity it works fine:
new SendCommandTask(MainActivity.this).execute(ipAddress, portNum, message);
However, I would like to embed this within a method in a new class instead…
public class NewClass{
String ipAddress;
String portNum;
String command;
public NewClass(String ip, String pn, String, c){
ipAddress = ip;
portNum = pn;
command = c;
}
public send(){
SendCommandTask(MainActivity.this).execute(ipAddress, portNum, command);
}
}
… and call the method directly from my MainActivity:
NewClass newClass = new NewClass;
NewClass.send();
I have tried passing the activity as another parameter in the constructor, but the method pukes when I do that. Is there another way to refer to the calling Activity in my NewClass? Or am I stuck running the AsyncTask from the MainActivity?
(I hope this makes sense, I’m very new to Java and OO programming in general.) Any help is very much appreciated!
Please see this answer that I wrote a couple of days ago. I think it applies here as well. The main additional consideration is, does your AsyncTask need to be able to outlive its calling Activity or not? If there’s any chance that the Activity will be closed or restarted, either kill the task in onStop() or be careful not to use any shared fields.
If your AsyncTask is going to directly read any members that are part of the Activity that you are passing in, you may as well just keep it inside the Activity. Factoring out the task into a freestanding class is best done when you want it to be independent and able to work with several Activity classes.
Also, consider doing your work in a Service instead of an Activity. I’m a big fan of IntentService.