Android background music service - android

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 :)

Related

Audio will still play even if I am using other app or the screen is locked

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.

creating android service for simple radio

I've been reading a while and all about services, I'm not all in dev, I'm new to this stuff and wanna learn, as a test I'm trying to make an online radio stream app. I already made it and it works perfect, my only problem is I can't seem to find the way to make the services work or how to do so, I know most of you all are great devs on android and all but just looking for a teacher or someone willing to show me how
this is my code:
public class MainActivity extends AppCompatActivity
{
Button b_play1;
MediaPlayer mediaPlayer;
boolean prepared;
String stream = "http://73.160.214.181:8000/stream";
private boolean started;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, mServices.class));
b_play1 = (Button) findViewById(R.id.play1);
b_play1.setEnabled(false);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if (started) {
started = false;
mediaPlayer.pause();
b_play1.setBackground(getDrawable(play));
} else {
started = true;
mediaPlayer.start();
b_play1.setBackground(getDrawable(pause));
}
}
});
}
#Override
protected void onPause()
{
super.onPause();
if(started){
mediaPlayer.pause();
}
}
#Override
protected void onResume()
{
super.onResume();
if(started){
mediaPlayer.start();
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if(prepared){
mediaPlayer.release();
}
}
class PlayerTask extends AsyncTask<String, Void, Boolean>
{
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
b_play1.setEnabled(true);
}
}}
I wrote an Android audio chapter in my book, and in it I present an app that plays music using a background service.
So here I am going to summarize it and slightly adapt it using your code to show how you should be able to stream from background service. Instead of using the Async task in your Activity, your are going to have a mainActivity that binds to a Service that does the streaming.
First, you need to define the service in your manifest: (obviously use your package name, not mine shown below)
<application
<service
android:name="com.wickham.android.musicservice.MusicService"
android:label="Music Service"
android:enabled="true">
</service>
Then, you need to bind your Activity to the service. The Activity can be used to control the service, such as starting and stopping the stream: (the following code block go in your Main Activity, that is where you have everything now)
// Bind the Service
bindService(new Intent(this,MusicService.class), Scon,Context.BIND_AUTO_CREATE);
// Connect to Service
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder)binder).getServiceInstance();}
// Start the service
Intent music = new Intent();
music.setClass(this,MusicService.class);
startService(music);
// Controlling the service
mServ.resumeMusic();
mServ.pauseMusic();
Then, in your service class that will be doing the actual streaming, you can implement it like this: (I did not include the two methods called resumeMusic() and pauseMusic(), but those go in the service and do basically what you had already in your activity.
public class MusicService extends Service implements MediaPlayer.OnErrorListener{
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService() { }
public class ServiceBinder extends Binder {
public MusicService getServiceInstance() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0){return mBinder;}
#Override
public void onCreate () {
super.onCreate();
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setOnErrorListener(this);
mPlayer.setLooping(false);
mPlayer.setVolume(100,100);
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
}
Hope this can help a little bit.
create a service class like
public class MyService extends Service {
MediaPlayer mPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
mPlayer = MediaPlayer.create(this, R.raw.laila);
mPlayer.setLooping(false); // Set looping
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
mPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
mPlayer.stop();
}
}
Add below line in your Manifest.xml file
<service android:name=".service.MyService" android:enabled="true"/>
You can start service by calling
startService(new Intent(this, MyService.class));
and stop service
stopService(new Intent(this, MyService.class));
This is the basic flow how to start and stop a service. You can read more here Service

Service background music does not turn off

In my app there is a background music, for what I have a service. It works fine, but it "keeps playing" when either I close the app or turn off the screen.
Should I change something in onPause or onStop?
My code:
public class MyService extends Service {
private 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.id);
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;
}
protected void onStop() {
player.pause();
}
public void onPause() {
player.pause();
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
As screen turns off your activity becomes invisible which triggers onPause followed by onStop
Screen on, on the other hand, triggers onStart followed by onResume.
when ever you want to stop service use
stopService(new Intent(ActivityName.this, ServiceClassName.class));
Probably copies of the player are created somehow. Try to make MediaPlayer variable static and then try to deallocate it after pausing onPause(). Anyway it is weird, that you are creating MediaPlayer instance in service.

Background music doesn't turn off or on when it is supposed to

I've got a service which plays background music in all of my activities, but doesn't turn off while onPause or onStop. I want my music to turn off while apps close or screen turn off, doesnt matter in which activity usesr currently is.
The problem is this:
I have a service. In every activity I coded what to do onPause and onStop. It works fine, but service also stops when I switch to another activity.
Code:
public class MyService extends Service {
private 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.id);
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;
}
protected void onStop() {
player.pause();
}
public void onPause() {
player.pause();
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
You will have to stop the service in the onDestroy method of your main activity. Check this answer

Android problems - Background service doesn't stop

Hello guys, I'm an absolute beginner in Android development.
I'm just now creating a simple android application and I use a "BackgroundService" for the background music.
I manage to play music; my problem is that when I close my app or press the home button, the music doesn't stop.
Can you guys help me?
Here's my code:
MediaPlayer player;
public IBinder onBind(Intent arg0) {
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) {
// 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() {
}
}
on the onPause method, add also
player.stop();
player.release();
hope this helps
You should really understand the concepts of a Service. Service is used for managing heavy tasks that runs in the background and don't require a UI. In simpler terms, Service is used to do heavy task in the background even if the activity is no longer visible.
Service will remain alive even if your activity is destroyed. You have to stop the Service manually. In the onPause() of your activity, try to stop the Service.
stopService(this, serviceClassName.class)
and in the onPause() of the Service you should stop and release the player
player.stop();
player.release();
See this link to learn more about Service and its life cycle. developers.android.com

Categories

Resources