10

I m new in android, I'm not much aware about services.i have an activity class with a UI, i want to make this activity class runs in background, when i click the back button. how to make my activity runs in background like a service, plz help me..

Jesbin MJ
  • 3,219
  • 7
  • 23
  • 28

4 Answers4

5

You cannot really run an Activity on background! When an activity is not on foreground it gets to onStop and then the system could terminate it, to release resources, by onDestroy method! see Activity Lifecycle

In order to run on background you need to create a Service or IntentService

Checkout android javadoc about Services here and here or IntentService

and here is a third-party Android Service Tutorial

Edit: you may also need a communication between your service and your activity so you can get through that: Example: Communication between Activity and Service using Messaging

Community
  • 1
  • 1
madlymad
  • 6,367
  • 6
  • 37
  • 68
5

If you simply want your activity runs in back Try using

moveTaskToBack(true);
madlymad
  • 6,367
  • 6
  • 37
  • 68
0

It seems like you want to run an activity in background when it quits. However, activity can't be run unless it's on foreground.

In order to achieve what you want, in onPause(), you should start a service to continue the work in activity. onPause() will be called when you click the back button. In onPause, just save the current state, and transfer the job to a service. The service will run in the background when your activity is not on foreground.

When you return to your activity later, do something in the onResume() to transfer the service 's job to your activity again.

Xuan Wu
  • 118
  • 3
-2

You should read the developer guide on Threads: http://developer.android.com/guide/components/processes-and-threads.html

Specifically the function doInBackground() Example from page:

public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
    return loadImageFromNetwork(urls[0]);
}

    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}
RyPope
  • 2,645
  • 27
  • 51
  • i dont want to make it a thread.. i just want to run this in backgroung like a service...my activity consist of telephony manager, broadcast reciever etc so no need to make it into a thread – Jesbin MJ Mar 25 '13 at 17:16