I want my app to do some tasks no matter if the app is currently active or at the background.
What I have done is:
private static void myCurrMethod() {
boolean checkIn = false;
if (1==1) {
checkIn = true;
}
// Sending message
Time now = new Time();
now.setToNow();
final String res = "Time is " + now.hour + ":" + now.minute + ":"
+ now.second + " stat " + checkIn;
new Thread(new Runnable() {
public void run() {
try {
Socket clientSocket = new Socket("xx.xx.xx.xx", 6790);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
outToServer.writeBytes(res + '\n');
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
// End of it
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
myCurrMethod();
}
}, (TIME_INTERVAL_WIFI_EN * MS_PER_MIN));
}
The socket part is to check how often is message being sent. I have tried this when I am using another app. It works completely fine, if my phone is connected to my computer which has ADT installed. However the problem is, it does not work properly, or works for few times when my phone is not connected to my computer.
I found on the internet that there are ways to run, but they all seem like running things on the background while app is active. Also there are so many things on the internet some people suggest Services, some suggest AsyncTask, some others suggest a way like mine. I am confused, what is the best way to do this?
Note: I don't really discard this from my app. For instance if my app is not started at all, then it shouldn't work. If my app is removed from app list, then this shouldn't work. Basically what I want is the default behaviour that we could have in old Symbian apps.