I am having an AsyncTask to play media and I am using a Service for it. The problem is that when my AsyncTask (in the Service) is running, another part of the app that I used an AsyncTask to communicate with web server is not working until playing finishes. (Playing media not buffering it).
I have already tried removing the AsyncTask and using a new Thread but I can't update the UI in this mode.
What should I do to fix it?
You probably don't want both an Asynctask and a Service. Services are designed for long running background tasks. 'Asynctask's are designed to easily launch a new thread, perform some long-running task, and then send data to the UI thread.
There is only one UI thread, so, if you're updating the UI, you are blocking user interaction.
If you're streaming music, you would probably want a Service to spawn a new Thread so that it can constantly be downloading songs in the background. If, for example, the user presses a button and it loads a video, you might instead want an Asynctask to perform the download.
Generally, one might use an Asynctask to download a media file on user request (or, if you're downloading in the background, a Service might be used for this). Then the data is exchagned and the video file can be played using Android's MediaPlayertools:
http://developer.android.com/guide/topics/media/mediaplayer.html
Remember that, unlike with an Asynctask, creating a Service does not automatically mean that you have created a new Thread. Services can run on the UI thread. Generally speaking, though, most use cases for Services require that they launch a new Thread to do their work.
Finally i used a service and a handler to create post delay
Related
I would like to build an android app with a permanent background process. I thought of using a Job, but is there a better class for doing this?
A service may be what you're looking for. These always run in the background, however have many limitations and are often killed by the OS.
If you need your service to (almost) always be alive, it can either be woken up by system intents / notifications, or run as a foreground service (notification is shown to user, but app is almost always active).
From the above link:
Foreground
A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.
Background
A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.
As mentioned in comments, IntentService is another option, here's a comparison between it and a normal Service. It will however suffer the same restrictions as a normal background service.
For a more accurate answer, I'd suggest editing your question to include what your service needs to do.
I am an iOS developer and recently started Android development. Currently I need the application to perform a repeating check regarding a remote resource (a JSON file) in the background, which I would like to:
App finished launching
Initiate scheduled repeating task in Application subclass
Application will be noticed if there are any changes in the remote JSON file and handle it accordingly
After doing some research I found that there seems to have many ways to achieve this, while I can rule out some of them, I can't really tell the differences between the rest and which I should use.
I've found that to perform a scheduled repeating task, I can use the following classes:
ScheduledThreadPoolExecutor
IntentService
AlarmManager
Runnable (with postInBackgroundDelayed / DelayedRunnable, or maybe ScheduledExecutorService?)
And I've ruled out the use of:
ScheduledThreadPoolExecutor, I've read that this is best used when multiple worker threads are needed, which in my case I only need one
AlarmManager, this will be executed even when the app is not running, while I only need the task to be performed when the app is running
And for the rest, which are IntentService and Runnable, from my understanding so far:
IntentService, needed to be started and stopped manually, tasks are invoked by sending an Intent to the service, and then the result is broadcasted
Runnable, like the block used in Objective-C, a specific segment of code to be executed at appropriate time
Other than these are there any other differences between them? Is my understanding correct? Are them both appropriate for my task? It it is the case, are there any considerations before choosing which one to use?
Thanks!
For creating long-running background task in Android, you should create a Service in your application.
Services are executed on the main thread of the application, with the highest priority as Activity, and continue to run even if the user exits the application.
Services have the following types :
Started Services
Foreground Services
Bound Services
Intent Services
In implementation of the services, you should create another thread, using for example ScheduledThreadPoolExecuter and delegate the work you want to accomplish to that thread.
For your requirement, you can create a simple service, extending the Service class, and in the onStart() method, create your thread to do the desired work for you.
I'm building a fairly simple data tracking app. Using a runnable, every 5 seconds my app checks how much data the user has consumed and updates the UI.
The app works well, and the runnable keeps going even when the app is not in the foreground, but when the app is closed, it stops.
I've never used a service before, and after reading some documentation, I'm still unsure if that's what I need. I need to be able to update the UI, and depending on the data amount, start an asynctask to update a server.
Right now this part is happening from the runnable, but from what I've read about services, it seems like interacting with the UI is difficult.
I was originally hoping that I could somehow just prevent the app from ever being killed. It's going to be used on a private system, so there's no concern of the user 'getting annoyed' that the app can't be closed, but I can't figure out how to pull it off.
Thanks in advance for any information!
Note: I didn't post any code because I didn't think it was relevant here, but I'd be happy to upon request.
Is this the correct situation to use a service?
Yes.
from what I've read about services, it seems like interacting with the UI is difficult.
It's not that hard. The easiest solution would be to use an EventBus.
Another solution without a library: The Activity binds to the Service in onCreate. The Service returns a Binder. The Activity passes a Listener to that Binder. The Service calls the listener as soon as the UI needs to be updated.
I'm trying to implement an android app where I can send commands to a server that controls a robot. The problem is quite "simple": I would like to keep a connection and communicate with the thread-service-task to send messages to the server, and get the responses to update UI and keep the user with the related information from the robot sensor.
So, what should be my decision? I know its probably duplicated. But I didnt find my same problem, cause I want to extend the question:
Is there any way to run a background process on an activity, change activity and keep it going? (Activity or fragment, I would go for fragments in the future).
Thanks in advance for any help!
The best solution for this is probably a Service.
A very good article on Services, including how to communicate with a background service via either Intents or broadcast events can be found at http://www.vogella.com/tutorials/AndroidServices/article.html
One typical model for your situation is to use:
Service for long running communication (taking "orders" from a queue
BroadcastReceiver to be notified about asynchronous events handled by Service
Activity to handle UI
One reference to consider looking at is here
Here is a Reference Code that uses an Android App , Arduino to Control a Bot. You can see its Structure thats what i have used in my robot as well. AsynkTasks wont be a good option in this aspect. Using a Service is a goodIdea for Long Running Communication
https://code.google.com/p/mover-bot/
Here is a Live Demo of This Android Controlled Robot.
Mover Bot
Do your work in Background and notify the result to UI thread.
Go through this for more detailed overview.
AsyncTask
It is a helper class around Thread and Handler for making threading and easy for you. Just do your task in background and publish result in UI thread.
http://developer.android.com/reference/android/os/AsyncTask.html
Thread
Use basic concept of threading in java, create your own thread pool do your task and publish your result in UI thread using handler. Mainlly, used when you need more longer running task while your ui is visible (for simple background task asynctask). It will take time in implementation but provide you more control over task management.
https://developer.android.com/training/multiple-threads/create-threadpool.html
Service
Services are used when you have more longer running task and also you want your ui to be independent from your task.
Here in your case i would prefer you should use a service for communication and use binder or broadcast manager for reflecting change in UI.
http://developer.android.com/guide/components/services.html
I need help designing a solution to a problem specific to long running background tasks.
Background:
I have an app with activity that displays a list of files.
The files can each be downloaded. Each downloaded file can have an update.
The updates, if any, are fired as notifications with update now button. The app has an activity that shows the updates for each file.
Clicking on update now in either place triggers a background job downloading the file and update the progress in UI in both the places (depending on where the user is).
The user can update/download a max of 4 files simultaneously.
Design:
I have a GCM setup with WakefulBroadcastReceiver, that starts a IntentService to notify any updates.
The update/download is a Runnable - DownloadRunnable.java
A singleton class, MyDownloadManager has a static method startDownload() that starts the DownloadRunnable with a specific url.
Problem:
How do I update the progress in both notifications and activity while downloading the update?
How do I extend the design to run concurrent downloads and update progress to the corresponding item?
I would move the download task into a service.
I would not implement it myself, instead I would use the DownloadManager System service, see doc and usage example.
In your UI you can query the download status inside a background thread, see this SO question: Show Download progress inside activity using DownloadManager. Different to the solution I would use an AsyncTask instead.
This allows you to perfom downloads in parallel. In the activity you can show the current progress by polling in a background thread, but I am not sure what you mean with the notification? The DownloadManager shows a notification when starts with downloading.
Your downloads will be much stabler instead of using an own implementation, since DownloadManager can deal with connection loss and will perform a retry.
I would suggest to use Android's DownloadManager. This is the Download manager that the whole OS uses. U'll receive broadcast when the download is completed using ACTION_DOWNLOAD_COMPLETE.
Try this tutorial:
http://blog.vogella.com/2011/06/14/android-downloadmanager-example/