I would like to develop a media player for Android on my own but I have a conception issue : should I use a Service or an Activity just for the player?
I have Fragments in my App and I would like to play a song when I click on one of the items within my music lists but I don't really know which of those 2 technologies I should use to allow music to keep playing even during navigation or outside the app.
Does it better to start a new Activity when a song is played and then keep the Activity running or launch a Service waiting for some events?
Thanks in advance.
The best solution for your app may be
i) Visualize your app with frontend ( like selecting music to play, pause, forward and other features )
ii) start service that runs in background which continues the activity process in background even if the activity is closed ..
You can accomplish this by implementing following ->
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
...
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = ... // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
I think this is somehow helpful to you ..
If you want music playing in background, you should definitely use Service. Use activity only for UI-related operations. Since playing music is not UI-related operation, it should be done in Service. Please take a look here: http://developer.android.com/guide/topics/media/mediaplayer.html
Related
Example:
Activity 1:
main screen.
player = new media player()
player.start() //the sound began
now i have to equalize this same sound in another Activity...
Activity 2:
edition screen
the sound keeps playing and want to stop
example:
player.setVolume(0.0)
player.stop()
thank you
Declare player as public static in screen1
then you can access this media player in screen 2
like screen1
:
public static MediaPlayer player;
player=new MediaPlayer();
=================
===========
write your code
Screen 2 ::-
if you want to use media player in screen 2 use this code ::-
screen1.player.start(); screen1.player.stop();
You must create Service. Service to host the MediaPlayer and have your Activities communicate with the Service to play and stop songs. Don't forget to call release on the MediaPlayer when you are done. Bind the activity to service
For the sample Equalizer sample. The sample is not integrated with Service it just a seperate unit.
Obtain the sessionid of the MediaPlayer and pass it to equalizer.
Usually when we are using MediaPlayer, as playing music in itself doesnt really require to have a graphical interface, we usually use a service because only the sound resulting by the playback is needed.
- Create the mediaplayer in a service
- Send somes request to the Service after binding to it, or even by sending broadcasts to it so that it can play, stop, pause, set volume whatever you want.
How can I play Background Sound throughout my application, even if activities keeps on changing.
I have found code for playing sound in background for one activity as:
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
return null;
}
}
I am not getting anyway to play sound in application content not activity context.
So I think there must be some way to achieve this using singleton class or service?
Play Background Sound in android applications
How to play audio in android
I have followed above both links but it doesn't seems to help me though, its playing sound but not with my instruction from second time, first it works where ever I want to start.
Any Help would be highly appreciated!!!
I am new to android and stuck up at some point in the app i am currently developing. In my onCreate method I have two independent tasks : First is playing sounds in an array using for loop and Second is an onClickListener to an image that makes it animate on click. The sound starts perfectly as soon as I start the app, My problem is when I click the image, it animates as required but it stops the sound. How can I play sound and animation independent of each other? Any help/idea would be appreciated.
Use AsyncTask in android it will update the ui too in method updateProgress in android
You can use service for playing music.Services are designed to continually running in the background.
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer player = MediaPlayer.create(this, R.raw.audio);
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setVolume(1f, 1f);
player.start();
I am new to Android. I am creating service for Media Player so that it can continue to play song even if i close the application. I have created activity for Media Player and it is having all the functionality like play , pause , next , previous , seekbar and also includes oncompletionlistener . All works excellent. But Now i want that all should be managed by service.
I have Created MyService Class :
public class MyService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
But in my player activity i have created ArrayList for Songlist from which i am taking currentsongIndex and through it i am maintaining all the functionality like next , previous and all.. Now in service how do i get songlist which is also required in my activity ?? Where should i create MediaPlayer object mean in service or activity ??
for MediaPlayer I have reffered http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/ . For my media player code you can refer this site. Thanks.
Pleaze clear my doubt. I am so confused. Reply me soon..
You are on the right track. I have adapted from the SDK Samples; this is how I do it and it works great.
From your ArrayList (in your activity NOT from the Service) call
onListItemClick
and start an intent that starts the music service:
startService(new Intent(MusicService.ACTION_PLAY));
In your manifest you will need to add:
<intent-filter>
<action android:name="com.blah.blah.action.PLAY" />
<xxx xxx>
</intent-filter>
And of course in your Music Service you need to receive the Intent:
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY))
processPlayRequest();
}
Be sure to add Intents for skip, rewind, stop etc.
Let me know if this helps.
Getting the app to run in background should be taken care of by the 'Service' itself.
Try following this example http://www.vogella.com/articles/AndroidServices/article.html
A service is designed to work in the background.
I went through exactly the same thing! It's a long haul to develop even a really great mp3 player app. The answer is long.
Here are a few resources that really helped me. Android has a article on this very thing in their developer docs:
http://developer.android.com/guide/components/services.html
Pay attention to what it says at the bottom of this long article about bound services and running in the foreground.
Additionally, managing player state is what caused me the most headaches.
You'll also want to take a look at threading because spawning that new service will still execute everything on the Main UI Thread, sounds crazy but true. Take a look at the ExecutorService for managing thread pools. I wish I could tell you it was easier.
Unfortunately most of my formal training from all over the web but with android services comes from a paid site:
http://www.pluralsight.com/training/Courses/TableOfContents/android-services
It is a good resource for all programmers I think but has great sections about many aspects of android programming that are only covered briefly at other tutorial sites.
The resources at Vogella are good also, mentioned above.
I've created a music service for my application (a music player), and after making some tests I'm observing a behaviour that's causing me a headache as I don't know how to solve it.
For testing purposes, I've modified the service so, as soon as it's started, it plays a specific mp3 file from my sd card. Also, I've modified the application so the first activity is started, it starts the service, and then it calls "finish()".
Ok, so... I launch the application, and the first activity starts, my service starts and plays the music, the activity finishes and the application is closed and... the music is stopped and after some seconds the service is restarted (I'm using the START_STICKY flag, so I suppose that's normal).
I don't want the music to be stopped when I close the application, or in another words, I don't want the service to be stopped (and then restarted because it's been stopped) when my application is closed.
Right now, to control the music service, I start the service and then I bind to it so I can call the service functions I've defined in an interface.
Any ideas?
Thanks!
EDIT:
This is an example of what my application and service do (in the tests I'm doing).
Activity:
public class FirstActivity extends SherlockFragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, MyService.class));
...
// Here is a postDelayed that will run after 2 seconds and call finish()
}
}
Service:
public class MyService extends Service {
private MediaPlayer mPlayer;
#Override
public void onCreate() {
mPlayer = new MusicPlayer(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Here is the code that plays the music using MediaPlayer
return START_STICKY;
}
}
do not forget to put that the service is remote in your manifest application tag:
<service
android:name="somepackage.PlayerService"
android:label="Player Service"
android:process=":remote"/>
Note, that the remote name can be something else, so you can have more than one services that are not bound to the main application process