Android - How to keep music playing while inside the app? - android

I want to set up the background music of my app so that it will keep playing while I am on the app, and pause when I press the home button. The problem is that if I pause the music when the phone goes to the home screen, it also pauses the music when I go to a different activity within my app. Is there a way to keep the music playing while I switch activities (e.g. I have a menu, from which I can open different screens in my app, and the music stops playing as soon as the phone leaves the menu screen). My code is as follows:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1,
classes));
mp = MediaPlayer.create(Menu.this, R.raw.music);
mp.start();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
mp.pause();
}
#Override
protected void onResume() {
super.onResume();
mp.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.release();
finish();
}
}

You can create a Service that will keep the music playing on the background
Sample code:
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayAudio extends Service{
private static final String LOGCAT = null;
MediaPlayer objPlayer;
public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.sleepaway);
}
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}
public void onStop(){
objPlayer.stop();
objPlayer.release();
}
public void onPause(){
objPlayer.stop();
objPlayer.release();
}
public void onDestroy(){
objPlayer.stop();
objPlayer.release();
}
#Override
public IBinder onBind(Intent objIndent) {
return null;
}
}
For more details, please refer here.

I see 2 different solutions:
Create a class that extends Application and put your music player there.
Create a Service that will read the music on the background

Related

How to pause background music when app is running in background

I created a game.I added some background music to the app and now I want to pause the music when the app is exited using home button and the song should resume when it is opened from the multitasking.
package tssll8.coloursmash;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
Import android.os.IBinder;
/**
* Created by ciddarth on 04/07/17.
*/
public class bgmusic 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.bg);
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() {
}
}
Mediaplayer has a pause() method: MediaPlayer#pause()
so you could call that in the on pause which gets triggered by pressing the home button, like so
public void onPause() {
player.pause();
}
and resume it in onResume like this:
public void onResume() {
player.play();
}

Keep radio playing in background

hi i'm trying to create a simple Online Radio i want to keep radio playing in bakcground and i know i should use Service but i don't how to use it please help me to make my app radio keep playing in background
this my code :
Button b_play ;
MediaPlayer mediaPlayer ;
boolean prepared = false;
boolean started = false;
String stream = "http://stream.radio.co/s98f81d47e/listen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_play = (Button)findViewById(R.id.b_play);
b_play.setEnabled(false);
b_play.setText("Loading");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(started){
started = false;
mediaPlayer.pause();
b_play.setText("Play");
}else{
started = true;
mediaPlayer.start();
b_play.setText("Pause");
}
}
});
}
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_play.setEnabled(true);
b_play.setText("Play");
}
}
#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();
}
}
}
Play the music from the foreground service.
Official Android documentation says:
that is a service that the user is actively aware of and is not a
candidate for the system to kill when low on memory. A foreground
service must provide a notification for the status bar, which is
placed under the Ongoing heading. This means that the notification
cannot be dismissed unless the service is either stopped or removed
from the foreground.
In your case a radio that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.
Here is an example

Background music stops while swithing activities

How to make service (background music) to turn off when I close the app or turn off the screen, but not when I switch to another activity?
Currently Music plays fine, I lasts until the screen turn off or I close the app, but also close when I switch to another activity. It is probably caused by onStop and onPause assigned to every activity. Please help me solve this issue
My service:
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.music;
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() {
}
}
My example activity has this:
public void onPause() {
super.onPause();
stopService(new Intent(a.this, MyService.class));
}
public void onStop() {
super.onStop();
stopService(new Intent(a.this, MyService.class));
}
public void onResume() {
super.onResume();
startService(new Intent(a.this, MyService.class));
}
public void onRestart() {
super.onRestart();
startService(new Intent(a.this, MyService.class));
}
There are two ways i can suggest
1) let it be in onPause(), create a flag/boolean that will set to false by default and will be true in every-case such as new activity startup, on back press etc. so if onPause is called and flag is false you can stop the music.
2) you have background service already, you can keep checking which activity is in foreground, if is homeScreen you can stop the music.
Edit :- to know if your app is not in the foreground
check this link
this is good example
Use this code.
Remove this line:
player.pause();
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.music;
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() {
}
}

Background music for game app that will play to all class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i created a android app game that has a welcome screen named MainActivity.class and will intent in Maimenu.class after 5 sec of sleep. the MainMenu class has start game,settings,about, and high score function. but my problem is i dont know how to make my background music play in all my activities/class it only plays in my welcome screen. i want that the background music will play continously in all my activity/class. 2nd problem is ihave a button ON and OFF in my settings class. how can i turn OFF my background music if i click the button off in my Settings.class. hope you can help me :) i appreciate your time answering my problem.god bless. btw newbie here
public class MainActivity extends Activity {
MediaPlayer backgroundmusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer backgroundmusic = MediaPlayer.create(MainActivity.this, R.raw.bsound);
backgroundmusic.start();
Thread timer = new Thread(){
public void run(){
try {
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
}
};
timer.start();
}
You can use below code
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
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 {
MusicService getService()
{
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0){return mBinder;}
#Override
public void onCreate (){
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.jingle);
mPlayer.setOnErrorListener(this);
if(mPlayer!= null)
{
mPlayer.setLooping(true);
mPlayer.setVolume(100,100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int
extra){
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
mPlayer.start();
return START_STICKY;
}
public void pauseMusic()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
length=mPlayer.getCurrentPosition();
}
}
public void resumeMusic()
{
if(mPlayer.isPlaying()==false)
{
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic()
{
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy ()
{
super.onDestroy();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
return false;
}
Binding the Activity to the Service
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder
binder) {
mServ = ((MusicService.ServiceBinderbinder).getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
void doBindService(){
bindService(new Intent(this,MusicService.class),
Scon,Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService()
{
if(mIsBound)
{
unbindService(Scon);
mIsBound = false;
}
}
Starting, Pausing, Resuming and Stopping the Music
Follow the given steps:
Step 1: First bind the service to the activity by calling doBindService on your activity's onCreate as passing an intent to the service.
Step 2: Start the service by an explicit Intent:
Intent music = new Intent();
music.setClass(this,MusicService.class);
startService(music);
Step 3: From your activity, wherever you want to pause, resume or stop music, call the corresponding service functions as follows:
mServ.pauseMusic();
mServ.resumeMusic();
mServ.stopMusic();
Step 4: Don't forget to call doUnbindService from places where you want to unbind the service from the activity. An ideal place is the call to activity's onDestroy()method.
Step 5: In your application's androidmanifest file, paste the following XML code:
< service android:name=".MusicService" android:enabled="true" / >

MediaPlay in Android MusicServices crashes when calling <MediaPlayer>.pause()

In our app we have a MusicService. Currently, it works perfectly fine in terms of playing music and stopping it, but that is from starting and stopping the service. We are calling it in other methods, but mp.pause() is crashing unless it is surrounded by a null checker. But when it checks for nulls it doesn't work at all. We had all this working earlier, but we started reformatting the way were doing it, because on Android 4.0 (ICS) the Music kept playing randomly even when we stopped it, but thats not the point anyway.
public class MusicService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(final Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(this, R.raw.title_music);
mp.setLooping(true);
mp.setVolume(200, 200);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
mp.start();
return 1;
}
#Override
public void onStart(final Intent intent, final int startId) {
}
public IBinder onUnBind(final Intent arg0) {
return null;
}
public static void onStop() {
mp.stop();
mp.release();
}
public static void onPause() {
if (mp!=null) {
mp.pause();
}
}
public static void onResume() {
if (mp!=null) {
mp.start();
}
}
#Override
public void onDestroy() {
mp.stop();
mp.release();
super.onDestroy();
}
#Override
public void onLowMemory() {
mp.stop();
mp.release();
}
}
We are using this to start the service in another activity:
intent = new Intent(this, MusicService.class);
startService(intent);
Without a log I can't really say with 100% certainty this is the issue, but it would appear that the pause method is being called while mp is in an invalid state. I suggest you change your onPause method so that it reads like so.
public static void onPause() {
if (mp!=null) {
if (mp.isPlaying())
mp.pause();
}
}
This will check to see if it is actually playing and will work for any state it is in, except an error state. At least according to the documentation.

Categories

Resources