Using Services for this task - android

I have tried to search many discussion threads but I am not clear on this thing. Being new I am unable to understand half of the things hence I am going to ask the direct question.
For my application when the final button (start analysis button) is clicked, I want a service to start, the analysis to be done inside the service is long almost 2-3 minutes, once the analysis has been done I want the service to automatically start a result activity page present in my main activity.
How can this task be achieved ? and I would also like to know that if the application will run in background and will not be closed by android automatically when on pause ?
Thanks

The definition of Android service is that it can run in the background, devoid of UI. So yes, it is possible. However, a Service by itself does not automatically run in the background (it runs on the main thread). Instead, what you want to do is probably something like this:
Have a service which listens for intents that say to start the operation.
When your user clicks the button, send the intent to that Service.
The service will start a new background thread, do some work for a while.
After finishing its work, the Service will start a new Activity. (Like this..)
Please take note, that it is considered extremely bad practice to start a new Activity if the user is not using your app. It's horrible if you're using a chat application and a random app starts taking over... Instead, a better idea is to stick a flag somewhere and then in the onResume() handler of your other Activity, check if the task is finished, and if so send the user to the other Activity.

Related

Where is the best place to start a long running, application-wide, background task

I have a long running background task that I would like to start when the app launches and shutdown when the application shuts down. I'm already quite aware of the activity life cycle and what gets called when an activity gets created and destroyed.
I'm coming from an iOS background, and over there we have some calls that are made during application startup and shutdown. Is there something similar in the android world? I've searched a lot and all I'm finding are answers relating to an activity, not the entire application.
(Android is relatively new to me, so I may just not know the correct terminology to search for.)
EDIT:
I'll try an be a bit more specific. I have a background task that needs to be continuously running while the user is using the application. It will be streaming data from a server continuously while the application is active. It does not need to run when the application is in the background. It doesn't seem to make sense to me to tie the startup / shutdown of this background process to any one single activity since it may not be the same one activity that starts up when the application becomes active.
I am (possibly mistakenly) assuming that the OS takes care of starting / stopping background threads when the application resumes and pauses. If that is, in fact, the case, then all I really need to do is spin up the background task when the application first launches, i.e. when it is loaded into memory and becomes active for the first time that session.
It doesn't seem to make sense to me to tie the startup / shutdown of this background task to any one single activity since it may not be the same one activity that starts up when the application becomes active.
That's reasonable. It is somewhat difficult to implement, though.
I am (possibly mistakenly) assuming that the OS takes care of starting / stopping background threads when the application resumes and pauses.
You have it exactly backwards. Android pays not one whit of attention to any threads that you fork yourself, directly or via thin wrappers like AsyncTask.
In addition to that point of confusion, you appear to be equating "user switching to another app" with "app shutdown". Those may be the same thing in single-tasking operating systems. They are not the same thing in Windows, OS X, Linux, Android, etc.
So, what you seem to be seeking is having a background thread running doing this streaming work while your UI is in the foreground, and then stop when your UI is in the background. The problem is that there really isn't a straightforward way of accomplishing that in Android.
One close approximation would be to create and register a custom Application class, where you override onTrimMemory(), and stop your background work when you get to TRIM_MEMORY_UI_HIDDEN, TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_MODERATE, or TRIM_MEMORY_COMPLETE -- whichever of those that you encounter first. If, when one of those arrives, you determine that your streaming thread is still outstanding, shut it down.
In terms of startup, you could use onCreate() on that same Application singleton. The problem is that this will be called on any process creation, which may include scenarios in which you do not have UI (e.g., you are responding to some system broadcast, like ACTION_BOOT_COMPLETED), or possibly your process is going to parts of your UI that do not depend on the streaming. If you have none of those scenarios, then onCreate() in Application would be fine. Otherwise, kick off the streaming in onCreate() of whatever activities need it.
While normally we manage long-running threads with a Service, that is for cases where we explicitly want the thread to continue after our UI is in the background. Since you do not want that, you could skip the service.
It depends on what you want to do exactly. When you're just interested in the app starting for the first time you could #Override onCreate().
Or maybe you want to use onResume() as this will get called whenever a user brings the app to the foreground.
But this really depends on what exactly your background task is doing and what you want to do with it, to get an exact answer you need to provide more details.
Here is an overview for the actiity life cycle that should help you:
You can extend the default Application class and implement it's onCreate() method to detect when the app is launched. There is no corresponding method for when the app gets closed though.
Do not forget to specify it in the Manifest file.
In Android the application isn't shut down unless the system runs low on memory. You won't get a warning about that, it will just call your Service's onDestroy lifecycle method. If you want to do it when the Activity is visible on screen, use onStart and onStop. If you want to do it when the Activity is resident in memory, use onCreate and onDestroy.

Update data in Background Periodically (Android)

The main objective of my app is, when a button is pressed:
Collect data from the sensors
Store data in the database
Repeat periodically (every X seconds)
I want to have it done in background, and if the Main Activity is destroyed, the background progress to be still running. So if you delete the activity, I want it still running.
What I am doing right now, is having an AlarmManager with an Intent Service, to set the periodic recording of the Data, but whenever I destroy the Activity, as they are related, my app crashes.
I know there are different to run a background process, but none fits in mine:
Service: Depends on MainThread, so if the MainActivity is destroyed,
crashes
Intent Service: The one using right now, but as far as it is
related to AlarmManager, that is related to MainActivity, when it is
destroyed, crashes.
AsyncTask: The problem of this one, is that it is
supposed to do one task in background and it finishes, but what I
really want is to do it periodically until the user says to stop. So
it's not a matter of one time thing.
Is there any other way to have a background service?
Can any of the stated before be used for my purpose?
How do you recommend me to do it?
Thanks for your answers.
Try to start service in separate process using android:process=":servicename" in AndroidManifest.xml. If service is running in another process, it wouldn't be killed with activity.

Start service from an activity in a new thread and let it runs independently?

I appreciate any advice about what can I do, because I was searching for an example or a clear explanation and I could not find.
Actually I think that I have to separate problems:
1- I want to start a service from an activity, this service should run in the background in a new thread and keep on running all the time even if I close the activity interface, even if the mobile is not active...
2- Once I open again the activity (by clicking on the application icon), I want that Activity indicate for me that the service is running and I can stop it if I want or I can keep it running and close the activity interface again.
Any relevant tutorials, links or codes are welcome :-)
Thank you, R.
is the Asynk Task not able to do this?? Have you tried it?? Like Java we have a special kind of thread or service in android which does its work in background without affecting your UI means you will not get any ANR(Application Not Responding Errors).

Android Connect to Running Thread

I am creating an app that has a UIThread and a background thread. The background thread is basically being used as a timer - every second it sends a message to the UIThread to update the UI. When the user exits the app by hitting the backbutton, the thread continues to run. I want this to happen since the user may want to open another app while the timer continues to count down.
My question is when the user comes back to my app. I want to connect to that background thread that is running to display the current state of the app - how much time is left, etc. My question is how to hook back in to the thread that is still running in the background. I have tried using Thread and AsyncTask, but the same issue occurs.
Thanks for any help that you can provide.
Your thread is still turning by sheer chance - your application is in fact still running but it and the thread will be shut down when Android decides it needs the resources.
However what you want to do is well-provided for in Android - you need to implement a Service to have a process that runs in the background separately from your application. You can even have a Service start at boot and run whether or not your application is started.
This http://developer.android.com/reference/android/app/Service.html has most of what you need to know. To communicate between the Service and a foreground Activity you'll need to bind to a service interface, which is fortunately very easily done.
First thing that comes to mind is to change your timer thread to a Service and have apps interested in it bind to that service. Based on the Android documentation and suggested app design, you cannot depend on that thread to not be killed by the OS whenever it deems necessary.
http://developer.android.com/guide/topics/fundamentals/services.html
The android system provides a broadcast event every minute, it's call TIME_TICK.
You should:
Create a service. This is the recommended way to have a part of the app running in the background
Listen to the TIME_TICK event. This will consume less battery. (It won't wake the phone, though, so use an ALARM, too)
Add an alarm (to wake the phone if necessary)
Let the UI and the service interact. You need a callback via rpc (see the last callback example on the api page)
You should also ensure that the phone can sleep during the timeframe. You thus may want to compute the state as a delta between the starting point and now, instead of updating the state all the time.

Need design suggestions for my android application

Currently I am in process of developing my android application. My requirement is something like this.
I need to run a timer of 5mins and when timeout occurs I need to check certain things and take certain action. This need to be keep on running if the user starts the application.
In my knowledge I want to proceed like this
Create a service and start a timer in that service and do whatever needed when the timer expires. I will put one activity to interact with the service like start or stop.
I need suggestion for my approach and its pros and cons for this approach. To just run a timer do I need a service? If I run the repeated timer in a activity itself and if I press the back-button the activity will go background and will the timer also stop if I have started the timer in that activity?
I am sorry If I am not clear in my question. I have gone through the android application fundamentals and then thinking to ask this question. Please give me some idea.
There's no need for a service. You can use a Timer and schedule a TimerTask. If the task needs to touch the UI, then you should create a Handler to which you can post a Runnable.
P.S. You asked about what happens if your activity goes to the background. The Timer will keep running unless you cancel either the task or the timer itself in onPause or one of the other lifecycle methods. Whichever one you do it in, you should start the timer task in the matching start-up lifecycle method. If you are not going to cancel the Timer itself, you should create it as a daemon thread.

Categories

Resources