I have an Android application that plays streamed audio from the Internet using the MediaPlayer class.
How do I let it continue to play the audio on the background when the
user hits the home button to run other applications?
While running other apps, I'd like it to continue to play the audio.
You have to use something called Android Services.
From the docs:
"A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use."
Here's the excellent official guide to using services to get you started:
http://developer.android.com/guide/components/services.html
Here's a good tutorial on building an audio player:
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
Here's a video tutorial for building a streaming music player:
http://www.youtube.com/watch?v=LKL-efbiIAM
You'll need to implement a Service in order to play media in the background without it being tied to the Activity that started playback. Have a look at this example.
The key is define Service.START_STICKY to continue playing in background:
public int onStartCommand(Intent intent, int flags, int startId) {
myMediaPlayer.start();
return Service.START_STICKY;
}
Service.START_STICKY : if this service's process is killed while it is
started the system will try to re-create the service.
This is an example of to do this:
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by jorgesys.
*/
/* Add declaration of this service into the AndroidManifest.xml inside application tag*/
public class BackgroundSoundService extends Service {
private static final String TAG = "BackgroundSoundService";
MediaPlayer player;
public IBinder onBind(Intent arg0) {
Log.i(TAG, "onBind()" );
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.jorgesys_song);
player.setLooping(true); // Set looping
player.setVolume(100,100);
Toast.makeText(this, "Service started...", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onCreate() , service started...");
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_STICKY;
}
public IBinder onUnBind(Intent arg0) {
Log.i(TAG, "onUnBind()");
return null;
}
public void onStop() {
Log.i(TAG, "onStop()");
}
public void onPause() {
Log.i(TAG, "onPause()");
}
#Override
public void onDestroy() {
player.stop();
player.release();
Toast.makeText(this, "Service stopped...", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onCreate() , service stopped...");
}
#Override
public void onLowMemory() {
Log.i(TAG, "onLowMemory()");
}
}
Start service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);
Stop service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);
Complete code of this example.
Related
I am creating an app similar to other audio streaming apps. Is there a way to let a third party player stream music even though the screen of the mobile phone is locked or I am using other application?
You require to create the unbound service to play the media in background while other app may be opened or screen might be lock.
You can refer this for understanding in detail regarding use of services: https://developer.android.com/guide/components/services.html
Like this:
Create Intent first
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
Create class for the service to run in the background:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Do not forget to call service in manifest file
<service android:enabled="true" android:name=".BackgroundSoundService " />
Hope this helps you.
I have an application which has background music in it. When I am pressing the home button, the background music is still playing. After that when I am clicking the recent apps button, to the right of the home button, and closing the app by swiping or pressing X, it is restarting as if the application is started again instead of closing the currently playing music. How do I solve this problem?
Where do I add the onTaskRemoved() method?
package com.example.dmacs.myapplication;
/**
* Created by dmacs on 4/8/16.
*/
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import java.util.Random;
/**
* Created by digen on 3/8/16.
*/
public class BackgroundAudioService extends Service implements MediaPlayer.OnCompletionListener {
MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
int mfile[] = new int[5];
mfile[0]= R.raw.bgm1;
mfile[1]= R.raw.bgm2;
mfile[2]= R.raw.bgm3;
mfile[3]= R.raw.bgm4;
mfile[4]= R.raw.bgm5;
Random random = new Random();
int Low = 0;
int High = mfile.length;
int randomInt = random.nextInt(High-Low) + Low;
mediaPlayer = MediaPlayer.create(this, mfile[randomInt]);// raw/s.mp3
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand (Intent intent,int flags, int startId){
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
Clicking the Home button obviously won't stop a Service running in the background and swiping the app out of Recents won't work either, the OS will restart the Service because of START_STICKY returned from onStartCommand().
You just have to stop the Service when appropriate (in onPause(), for example) by calling stopService().
To stop your Service when your app is getting swiped out of Recents, you could just override onTaskRemoved() and call stopSelf() from there:
#Override
public void onTaskRemoved(Intent rootIntent) {
stopSelf();
}
I am using a Service to play background Music. The problem is that the music continues playing when i have finished the activity. when i press home button the music stop i want to make music continue playing while application is use and stop when home button press help me please. can some tell me how to do this
private static final String TAG = null;
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.sample);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
You should use a service and play the music.
http://developer.android.com/guide/components/services.html
Service runs in the background so even when you switch activities it still runs and you can play your music there.
You can start a service and then stop it when you need. Also you can bind the service to the activity. Look at the docs in the above link for more info.
Example :
https://thenewcircle.com/s/post/60/servicesdemo_using_android_services
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
// song is res/raw/yourmusicfile.mp3
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
Now just start the service and you can stop the service when you need. You can switch between activities and the service still runs playing the music.
Since the code i huge i uploaded to DropBox. Here's the sample i made
https://www.dropbox.com/s/fjc4krpcwsg7qm6/ServicesDemo.zip
I just want an app that runs some code to shortcut to a certain part of ics. How can I run this code at run time without having to launch the main.xml? I see the manifest launches the main.xml but that is about all I know.
Have you heard of Service Components in Android ? Service allows you to do work in background without disturbing your current GUI. You can do most of all the work that you want to hide from the user in GUI.
Have a look at example of Audio playing code, ( Original Source from Makarana's Blog. )
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
I am developing an entertainment app in android. I want to play background music, and I want to use service for that. App have 3 activities and music must be played across all activities. Also, when activity is paused, music must PAUSE and stopped when destroyed. Can anyone tell me how to do this ? any links or examples ?
Thank you.
Do it without service
https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion
If you are so serious about doing it with services using mediaplayer
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Please call this service in Manifest
Make sure there is no space at the end of the .BackgroundSoundService string
<service android:enabled="true" android:name=".BackgroundSoundService" />
way too late for the party here but i will still add my $0.02, Google has released a free sample called universal music player with which you can learn to stream music across all android platforms(auto, watch,mobile,tv..) it uses service to play music in the background, do check it out very helpful. here's the link to the project
https://github.com/googlesamples/android-UniversalMusicPlayer
#Synxmax's answer is correct when using a Service and the MediaPlayer class, however you also need to declare the Service in the Manifest for this to work, like so:
<service
android:enabled="true"
android:name="com.package.name.BackgroundSoundService" />
i had problem to run it and i make some changes to run it with mp3 source. here is BackfrounSoundService.java file. consider that my mp3 file is in my sdcard in my phone .
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("service", "onCreate");
player = new MediaPlayer();
try {
player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/your file.mp3");
} catch (IOException e) {
e.printStackTrace();
}
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("service", "onStartCommand");
try {
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Theres an excellent tutorial on this subject at HelloAndroid regarding this very subject. Infact it was the first hit i got on google. You should try googling before asking here, as it is good practice.
Create a foreground service with the START_STICKY flag.
#Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
if (startIntent != null) {
String action = startIntent.getAction();
String command = startIntent.getStringExtra(CMD_NAME);
if (ACTION_CMD.equals(action)) {
if (CMD_PAUSE.equals(command)) {
if (mPlayback != null && mPlayback.isPlaying()) {
handlePauseRequest();
}
} else if (CMD_PLAY.equals(command)) {
ArrayList<Track> queue = new ArrayList<>();
for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
queue.add((Track) Parcels.unwrap(input));
}
int index = startIntent.getIntExtra(ARG_INDEX, 0);
playWithQueue(queue, index);
}
}
}
return START_STICKY;
}
This can then be called from any activity to play some music
Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)
You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.
Here's a good tutorial about Playing music in the background on Android
I have found two great resources to share, if anyone else come across this thread via Google, this may help them ( 2018 ).
One is this video tutorial in which you'll see practically how service works, this is good for starters.
Link :- https://www.youtube.com/watch?v=p2ffzsCqrs8
Other is this website which will really help you with background audio player.
Link :- https://www.dev2qa.com/android-play-audio-file-in-background-service-example/
Good Luck :)