0

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.

Sarp Kaya
  • 3,686
  • 21
  • 64
  • 103
  • If you want to run something even if you app is not active, then service is definitely way to go. That is exactly what service is for. If you use thread approach instead, you will end up hacking lots of corner cases and debugging messy code. – hendrix Jan 16 '14 at 13:49
  • Does service run when app is not started tho? – Sarp Kaya Jan 16 '14 at 13:50
  • You can have service start automatically when you phone starts AFAIK – hendrix Jan 16 '14 at 13:50
  • Use a Service (http://developer.android.com/guide/components/services.html). You can start it at boot completed. Please take into consideration that your app needs to be started at least once by the user in order to have the Service started at boot completed. – fasteque Jan 16 '14 at 13:51
  • see http://stackoverflow.com/questions/2784441/trying-to-start-a-service-on-boot-on-android about starting service automatically. – hendrix Jan 16 '14 at 13:51
  • No, I don't want that. I want the service to start when app is started, and I want to stop the service when app is closed(removed from the list) – Sarp Kaya Jan 16 '14 at 13:52

1 Answers1

0

Apps do not "close" - they might be killed to free resources when they are not active, but the "recents" list does not mean "active" (it can be on the list and be killed already, or not on the list and still be in an active task stack).

If you want to run things off the UI thread, then use another thread, AsyncTask, etc. They will live as long as your app does and continue to run even if another activity is on the screen.

If you need your process to survive your activity lifecycle or start when your app is not active (or continue running the process even if the activity is killed) then you need a service.

There are many references here on SO to help implement any solution. In your particular case, the connection to the computer - or a charger - may make a difference in how many active tasks Android allows to continue running, so your inactive activity is being killed faster when not connected. You likely need a service to "finish up" whatever processing is expected to occur while the app is inactive or in the background.

Jim
  • 10,172
  • 1
  • 27
  • 36
  • So does AsyncTask behaviour is guaranteed that it will still run if Android OS itself kills the app for freeing resources? – Sarp Kaya Jan 16 '14 at 14:06
  • AsyncTask runs in the same process on a different thread (from the docs): "An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread." Sounds like you need a service... – Jim Jan 16 '14 at 14:49
  • How do you stop a service if an app is killed by the user?(Not by the operating system) – Sarp Kaya Jan 16 '14 at 15:09
  • you can startService and stopService in an activity. You can also stop it after it completes, etc. Here's an example: http://stackoverflow.com/questions/5555765/stop-service-in-android and here: http://stackoverflow.com/questions/17343661/android-service-startservice-stopservice-and-play-stop-button-in-one – Jim Jan 16 '14 at 15:39
  • Not really, because the links you have posted are stopping service when the app itself is active. What I am looking for is, if user kills the app, or device restarts etc. service must be stopped. – Sarp Kaya Jan 17 '14 at 01:29
  • Users do not "kill apps" - they leave them. Use "onStop" and flags to determine if any of your activities are active, if you must. Refer to this post for an excellent and thorough explanation on why you shouldn't "exit" or "kill" your app through user interaction ("logout" is a gray area - users may need to feel a sense of security when leaving an app, but that is not the same): http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon?lq=1 – Jim Jan 17 '14 at 03:07
  • I don't mean pressing home button, what I mean is holding on home button and removing it from background. – Sarp Kaya Jan 17 '14 at 06:08
  • when you hold "home" you get the "recents" list. Removing it from the list does not kill the task or app. It is simply removed from the "recents list". Your app can still be running. – Jim Jan 17 '14 at 07:41
  • What about forcing to stop? – Sarp Kaya Jan 17 '14 at 07:52
  • A force stop will automatically stop the active process, including services, which I believe addresses your concern. One note, the service will never restart until the user restarts the app itself (after version 3.0) – Jim Jan 17 '14 at 07:57