Android, should I make MediaPlayer a service? - android

I'm trying to write an Android application which will allow users to listen to a radio station.
I have got the start and stop buttons to work and it plays the stream. If I press the home key and start doing other bits and pieces with the phone, the stream continues to play. This is how I want it to work.
Should I bother creating a service to play the stream, or is the method I already use good enough? What benefit would having it in a service bring? A lot of tutorials and examples online seem to use services but it seems to me it's just adding extra complications into the code. Or is it more efficient?
Regards,
David

You don't need to use a service, but your users may under normal use find that playback stops unexpectedly, it depends on the normal use case, so a Service is the best approach.
The reason is due to the lifetime of the Activity that your streaming object / media player is currently attached to.
At some point the system will completely release the Activity now that it is no longer visible to the user, and once GC happens playback will stop. This will happen depending on memory pressure and what other actions the user takes, such as launching other apps. Services are allowed a longer life span, in general they will be released only after all other backgrounded activities are released but before the foreground activity. A more complete description of process lifecycle rules around Services can be found in the Android docs here.
You may also want to look at the PowerManager and the use of PARTIAL_WAKE_LOCK, which would allow playback to continue when the handset would normally sleep (at the cost of battery life).

Related

Song Plays in Background even Without Using Service

I am just clearing up my Android doubts. So lets talk about Services, we use services when we have to perform an operation in the background. Lets say Playing Music in the background? Thats one of the most popular reasons why people use Services.
But i just used Mediaplayer in my Mainactivity and i used .start() method in onCreate of my activity. I then minimized the app, but guess what....music still plays. I open the app again, and the music is still playing. I then remove the app from recent apps, basically destroying it and the music stops. Basically the app performs how it is supposed to. Works PERFECT!
Then why do we use services at all for these kind of tasks?
Is there any scenario this code might create a problem? Or is this creating some memory leak or something?
When "minimized" the App continues to play music due to OS delay which allow an User to re-open the App without delay (due to a closure mistake?) because all remained in memory (even the Music) in the previous state.
But the memory is limited, and the CPU the same, so the OS could kill or freeze (using Doze) a background Activity in any moment without prompt User/Developer.
An Activity could be killed to claim Memory or freezed to save CPU cycles. In this situation only explicitely declared Background Services are allowed to run (however with some limitations and special-behaviours), so if you don't use Service your Music could stop in any moment in the future.
PS: even Background Service could be killed from OS, but this case is very-very rare and only on Extreme Low Memory situations.
It will play as long as Android lets it live. It may stop at any moment, usually after 10-20 minutes.
Consider using Foreground Service to playback music. It will last until user kills it, and also provides notification bar with control over the playback.

File operations in Android service

Android services might get killed by the operating system at any possible time. There are no guaranteed lifecycle calls like onDestroy() you can rely on. I have to implement a service doing a lot of long running tasks and a bunch of file operations in the background. So my questions are:
Is it generally a good idea to do that in any kind of service? What happens with an open file handle when the process gets killed?
Is there a preferred way to achieve this like using a foreground service?
I think I won't be the first person having this type of problem/question, but I could not find anything on Google or SO. Thanks in advance.
Android services might get killed by the operating system at any possible time.
More accurately, Android app processes might get killed by the operating system at any point.
There are no guaranteed lifecycle calls like onDestroy() you can rely on.
Correct. onDestroy() is very likely to be called, but it is not guaranteed.
I have to implement a service doing a lot of long running tasks and a bunch of file operations in the background.
Pretty much any piece of software bigger than "hello, world" fits that description.
Is it generally a good idea to do that in any kind of service?
You do not have much of an option. A service is what is helping to keep your process around when it no longer is in the foreground from a UI standpoint. If you do not use a service, your process lifetime will likely be on the order of minutes, maybe less. With a service, your process lifetime can be hours, though it depends a lot on the device (e.g., amount of system RAM) and user (e.g., how busy the user is and how many other apps want to do background work).
What happens with an open file handle when the process gets killed?
If you have tried writing stuff to the file at about the point of process termination, any bytes not yet handed over to the OS (e.g., buffered in Java) will not be in the file.
Is there a preferred way to achieve this
I have no idea what "this" is.
like using a foreground service?
There are three main patterns for using a foreground service:
Brief transactions. K9 Mail, for example, appears to use a foreground service while it is checking for new messages, but only during that short window.
User-controlled operations. This is the conventional use case for foreground services. Music players, for example, will usually implement a foreground service for the music playback.
"I am going to try to live forever" types of services. That's not especially practical, as foreground services do not live forever. Users also get irritated with foreground services where they do not understand what they are getting as trade-off for the system RAM/CPU consumption and the always-visible notification icon.
Whether any of these patterns fits your project is something you would need to determine for yourself.

What's the reason or benefits that I must start a Service to control background mediaplayer?

I read Anndroid document - http://developer.android.com/guide/topics/media/mediaplayer.html
which said ".. you want it to continue playing while the user is interacting with other applications—then you must start a Service and control the MediaPlayer instance from there. "
But I found if I start a local a music file from an activity, then leave that activity, ( for example, press HOME key and interact with another app ), the music continues playing.
So, I don't understand " the "must start a Service" in document. Did I miss something?
This was not a big obstacle for my app at this moment. I am just wondering what's the potential problems could be if I do not use Service.( Services have longer lifespan, so the mediaplayer could be killed earlier, any others ? )
Our development is based on Android 2.2.
Thanks for any help in advance.
Big reason, if you are not using a service, users cannot listen to music outside of your app when the the activity gets paused or terminated. Technically you can make a music app but if your users cant listen to music when another app is in the foreground or the phone is in a different state(locked) it wont make for a very good app. You should take a look at the activity lifecycle for a deeper understanding of the process. Note that this behavior is by design for saving power, memory and cpu cycles.
It helps also not to think of services in the more traditional desktop dev usage. You want this thing to live even when your activity is not up and about.
For more about activity life cycles Managing the Activity Lifecycle
For the How
http://www.androidcompetencycenter.com/2009/01/basics-of-android-part-iii-android-services/
For the why
Why is it important to use Services for background tasks?
Playing the music in the Activity might be fine for now, but when Android is low on resources it might try to kill your Activity. When you add a service to an app, Android will try to keep that process alive as long as possible if it falls under certain criteria (such as playing music). Read over the Process Lifecycle section on Services:
http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle
The activity can get killed by Android or by the user and then the music would stop playing.

Is there a way to be aware of the execution of a 3rd party app?

Basically, I want to find out when another app starts, so I can adjust my app in a particular way. For example, if the user starts the GMail app, my service can detect that and react.
My current idea is to check 'topActivity' for each element in getRunningTasks() from the ActivityManager class. But that sounds quite expensive, since it needs to be constantly checking in the background (and I'm quite fussy about the CPU usage of my app).
If anyone knows a better way, I'd love to hear it!
There is not way of doing that the "nice way" meaning a BroadcastListener since applaunch don't get broadcasted. The only way is to Start a service that checks the getRunningTasks()
(For not to load the CPU too much you can also check what app is to the foreground. I'll search for the code if you are interested on that technic)
Have the service checking at interval of 5-10 seconds. Also shut down the service at SCREEN_OFF and restart it at SCREEN_ON.
Sorry but there is no other way for that.

Why dont Android applications provide an "Exit" option?

Is there something in the Android developer guidelines that disuades developers from providing the option to "exit" (stop running) an application from within the application itself?
I love multitasking and all but it's not clear to me why:
the vast majority of apps don't have their own Exit functions and hence just keep running forever
don't give you a choice about running when you turn on the phone - they just do by default
Both of these things lead to memory usage constantly increasing and your device running with this performance burden all of the time despite the fact that you may only want certain apps to run some of the time.
Am I missing something?
Is there something in the Android
developer guidelines that disuadea
developers from providing the option
to "exit" (stop running) an
application from within the
application itself?
Yes. It is generally not needed, just as it is generally not needed to restart a Web server because some user with a browser decided (s)he is done with a Web app.
the vast majority of apps don't have
their own Exit functions and hence
just keep running forever
They don't keep running forever. Android will close things up as needed.
don't give you a choice about running
when you turn on the phone - they just
do by default
Those developers aren't paying attention to me.
Both of these things lead to memory
usage constantly increasing
Generally, it doesn't. If you find specific apps that do this, uninstall them.
and your device running with this
performance burden all of the time
Generally, it doesn't. If you find specific apps that do this, uninstall them.
Also, this question is a duplicate of this one.
"Both of these things lead to memory usage constantly increasing"
Which doesn't matter since Android apps are limited to a fixed amount of RAM. Freeing RAM won't give more RAM to other apps.
Essentially, there's no need for a quit button as long as the developer does a good job of designing their app. Android activities are stopped when they aren't visible and resources are needed elsewhere, so the are no longer consuming resources. You can read about the lifecycle here:
Here's a related question:
From Google's Android Application Fundamentals page:
Shutting down components
A content provider is active only while it's responding to a request from a ContentResolver. And a broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components.
Activities, on the other hand, provide the user interface. They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. Similarly, services may also remain running for a long time. So Android has methods to shut down activities and services in an orderly way:
An activity can be shut down by calling its finish() method. One activity can shut down another activity (one it started with startActivityForResult()) by calling finishActivity().
A service can be stopped by calling its stopSelf() method, or by calling Context.stopService().
Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components. A later section, Component Lifecycles, discusses this possibility and its ramifications in more detail.
So it seems like Content Providers and Broadcast receivers should never be explicitly shut down, as they are inert while not handling their specific events.
As for Activities, I would argue in favor of having an end to it, but in certain cases. If your app has a finite state in which the user is done using it, why keep it alive until GC gets it? The activity manager still needs to keep track of that Activity while the user has finished their task. My best example for this is the Calculator. You open it, you have it solve a problem for you, and then you close it. If the onCreate function is so expensive that it's more effective to do onCreate once and then onRestart whenever the user moseys back to your application then you're probably doing something wrong. Maybe I'm misinterpreting how Android handles Activities, and if so I'm always interested in learning more :)
It all comes back to the answer that users want total control of their running and auto-start list and what they do and don't want installed, example: google maps, etc etc. there are no two ways about this.

Categories

Resources