I have a problem here, I have a music track works in the background of an app that is never stop and when I add OnDestroy() or Pause() in my main activity class gives me an error when running the application not in the class and I don't know where to put them to control the music in the main !!
here are the codes that gives me an error:
mServ.pauseMusic();
mServ.resumeMusic();
mServ.stopMusic();
The Main Activity:
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder)binder).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;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent music = new Intent();
music.setClass(this,MusicService.class);
startService(music);
And The Service 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 getService()
{
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
public void onCreate(){
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.la);
mPlayer.setOnErrorListener(this);
if(mPlayer != null){
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener(){
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
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();
Toast.makeText(this, "Music is Paused", Toast.LENGTH_LONG).show();
}
}
public void resumeMusic()
{
if(mPlayer.isPlaying()==false)
{
mPlayer.seekTo(length);
Toast.makeText(this, "Music is started", Toast.LENGTH_LONG).show();
mPlayer.start();
}
}
public void stopMusic()
{
mPlayer.stop();
Toast.makeText(this, "Music is stoped", Toast.LENGTH_LONG).show();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy ()
{
super.onDestroy();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Toast.makeText(this, "Music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
return false;
}
}
The code is based on this link tutorial
Related
I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.
Here's my code currently, everything works except background audio.
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageButton btn;
private ImageView img;
private boolean playPause;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
//mp.start();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
img.setImageResource(R.drawable.ic_toweron);
img.setAlpha(1.0f);
playPause = true;
}
} else {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btn.setBackgroundResource(R.drawable.ic_play_button);
img.setImageResource(R.drawable.ic_toweroff);
img.setAlpha(0.3f);
playPause = false;
}
}
}
});
try {
mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Any help would be much appreciated.
use service to play audio file instant of activity.
here is simple code how to use media player in service.
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
//region "member variable"
boolean isServiceRunning = false;
ArrayList<Song> PlayerList = new ArrayList<>();
MediaPlayer mediaPlayer;
int position = 0;
MainActivity mainActivity;
private final IBinder mBinder = new LocalBinder();
int playingMood;
private final static int MAX_VOLUME = 15;
Toast toast;
public static MusicService objService;
//endregion
//region "service method"
#Override
public void onCreate() {
objService = this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
isServiceRunning = true;
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
// showNotification(false);
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
playPrevious();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
play();
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
playNext();
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
stop();
stopForeground(true);
stopSelf();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
objService = null;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
//returns the instance of the service
public class LocalBinder extends Binder {
public MusicService getServiceInstance() {
return MusicService.this;
}
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
//endregion
//region "Media player"
public void SongRequest() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
//Handel UI on main activity
mainActivity.showPlayer();
mediaPlayer = new MediaPlayer();
mainActivity.updatePlayerUI();
prepareMediaPlayer(PlayerList.get(position).getUrl());
} catch (Exception ex) {
ex.printStackTrace();
}
}
void showToast(String text) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
toast.show();
}
#Override
public void onPrepared(MediaPlayer mp) {
// try {
mediaPlayer.start();
mainActivity.checkPlaying(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
mainActivity.sentUpdateBroadcast(true);
if (playingMood == 1) {
mediaPlayer.start();
}
if (playingMood == 2) {
playNext();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (mainActivity != null)
mainActivity.updateProgressBuffer(percent);
if (percent == 1)
mainActivity.showPlayer();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
try {
Log.i("MediaPlayer", "error");
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
void startPrepare(String url) {
prepareMediaPlayer(url);
}
void prepareMediaPlayer(String url) {
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(MusicService.this);
mediaPlayer.setOnErrorListener(MusicService.this);
mediaPlayer.setOnCompletionListener(MusicService.this);
mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
//endregion
//region "media player method"
public boolean play() {
if (mediaPlayer != null) {
switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
isServiceRunning = false;
if (mainActivity != null) {
mainActivity.ShowPlayer(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void playNext() {
if (position < PlayerList.size() - 1) {
position++;
mediaPlayer.stop();
SongRequest();
}
}
public void playPrevious() {
if (position > 0) {
position--;
mediaPlayer.stop();
SongRequest();
}
}
public void onError() {
}
public void onCompletion() {
}
public void onCleanMemory() {
}
public void initilizePlayerList(ArrayList<Song> list, int position) {
this.PlayerList = list;
this.position = position;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
public boolean isRunning() {
return isServiceRunning;
}
public Song getCurrentSong() {
if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
return PlayerList.get(position);
}
return null;
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void seekTo(int duration) {
if (mediaPlayer != null) {
mediaPlayer.seekTo(duration);
}
}
public int getMood() {
return playingMood;
}
public void setMood(int mood) {
playingMood = mood;
}
public void setVolume(int soundVolume) {
if (mediaPlayer != null) {
final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
mediaPlayer.setVolume(volume, volume);
}
}
//endregion
}
you can start your service from activity like this.
public void startMusicService() {
Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
for stop service use this code
public void stopMusicService() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
for bind service with activity use this
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
if (listHolder != null) {
initilizeSongsList(listHolder.list, listHolder.position);
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
where service is music service object in activity MusicService service;
So this is the working service for a single live stream URL thanks to asim.
public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
public static final String ACTION_PLAY = "com.example.action.PLAY";
private static final String STREAM_URL = "...";
private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";
MainActivity mainActivity;
MediaPlayer mediaPlayer = null;
WifiManager.WifiLock wifiLock;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class LocalBinder extends Binder {
public StreamService getServiceInstance() {
return StreamService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
wifiLock.acquire();
try {
// Set the stream URL location
mediaPlayer.setDataSource(TEST_URL);
// prepareAsync must be called after setAudioStreamType and setOnPreparedListener
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public boolean play() {
if (mediaPlayer != null) {
//switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
//player.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if( wifiLock != null) wifiLock.release();
if (mediaPlayer != null) mediaPlayer.release();
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
}
Which is implemented in the main activity:
public class MainActivity extends AppCompatActivity {
private ImageButton btn; // Play | Pause toggle button
private ImageView img; // Radio tower image that alternates between on and off
StreamService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind the view buttons to local variables
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
startStream();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (service.isplaying()) {
Log.d("pause","Pause Playback");
} else {
Log.d("play", "Start Playback");
}
}
});
}
public void startStream() {
Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
serviceIntent.setAction(StreamService.ACTION_PLAY);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
public void stopStream() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
}
Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.
When I play the music and come on home the music is running, but when I kill the app music is restart. I want to run the music when I kill the app instead of it restarting.
Please help me.
My code is:----
MainActivity.java
public class MainActivity extends ActionBarActivity {
Context context;
private Button mPlay, mStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlay = (Button) findViewById(R.id.button1);
mStop = (Button) findViewById(R.id.button2);
mPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent service = new Intent(MainActivity.this, Myservice.class);
startService(service);
}
});
mStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent name = new Intent(MainActivity.this, Myservice.class);
stopService(name);
}
});
}
}
And my service class is:---
public class Myservice extends Service implements
MediaPlayer.OnErrorListener{
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public Myservice() { }
public class ServiceBinder extends Binder {
Myservice getService()
{
return Myservice.this;
}
}
#Override
public IBinder onBind(Intent arg0){return mBinder;}
#Override
public void onCreate (){
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.follow);
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();*/
Toast.makeText(getApplicationContext(), "ondestroy", 2000).show();
}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;
}
}
Add the below method in your service and call the method when media starts playing. Foreground service are high priority service which are not killed by android system often, starting a foreground service needs a notification. you can manually stop foreground service by calling stopForeground(true). Please watch for basics of Media Playback State of Media Playback (Android Dev Summit 2015)
private static final String NOTIFICATION_ID = 91;
private void runAsForeground(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentText("Media is playing")
.setContentIntent(pendingIntent).build();
startForeground(NOTIFICATION_ID, notification);
}
I need a background music which is continuously playing through Activities. I want to stop my background music when clicking on the Home Button.
This is my Service Code.
public class BackgroundSoundService extends Service
{
private static final String TAG = null;
MediaPlayer player;
Context context;
private int length = 0;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.haha);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
#Override
public void onStart(Intent intent, int startId) {
player.start();
}
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {
player.stop();
player.release();
player = null;
}
public void onPause() {
player.pause();
}
public void onHomePressed(){
player.stop();
}
public void pauseMusic()
{
if(player.isPlaying())
{
player.pause();
length=player.getCurrentPosition();
}
}
public void resumeMusic()
{
if(player.isPlaying()==false)
{
player.seekTo(length);
player.start();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(player != null)
{
try{
player.stop();
player.release();
}finally {
player = null;
}
}
}
#Override
public void onLowMemory() {
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(player != null)
{
try{
player.stop();
player.release();
}finally {
player = null;
}
}
return false;
}
}
This is my 1st Activity Class
public class AdventureTime extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story);
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
View story1 = this.findViewById(R.id.button1);
story1.setOnClickListener(this);
View story2 = this.findViewById(R.id.button2);
story2.setOnClickListener(this);
View story3 = this.findViewById(R.id.button3);
story3.setOnClickListener(this);
View back= this.findViewById(R.id.buttonback);
back.setOnClickListener(this);
}
#Override
public void onBackPressed(){
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
Intent button1 = new Intent(this, Story1.class);
startActivity(button1);
break;
case R.id.button2:
Intent button2 = new Intent(this, Story2.class);
startActivity(button2);
break;
case R.id.button3:
Intent button3 = new Intent(this, Story3.class);
startActivity(button3);
break;
case R.id.buttonback:
Intent buttonback = new Intent(this, MainActivity.class);
startActivity(buttonback);
break;
}
}
}
Add this in the Activity AdventureTime :
...
#Override
public void onPause(){
stopService(svc);
super.onPause();
}
...
if you want to pause music without stopping your service
try this
add this class in your service
public class LocalBinder extends Binder {
BackgroundSoundService getService() {
return BackgroundSoundService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
and add this in your activity
private BackgroundSoundService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((BackgroundSoundService.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
replace
startService(svc)
with
bindService(svc, mConnection, Context.BIND_AUTO_CREATE);
and call the pause method in service whenever u need it
mBoundService.pauseMusic();
Why don't you try to listen to a dispatchKeyEvent instead? You could write:
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
stopService(svc)
return true;
}
else
return super.dispatchKeyEvent(event);
}
on each of your activities.
on you mainActivity class add this.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
// pause or stop ung Background music here.
return true;
}
return false;
}
I made a simple music player which can play some songs in the background.
Going to the homescreen and reopen the app through notification works as well.
The only Problem I have is that if I press the back button(going to parent activity) in the music player activity my app crashes. There are two classes, the activity MP3Player.java and the service MP3Service.jave.
I am getting the following error:
java.lang.RuntimeException: Unable to destroy activity {package/package.MP3Player}: java.lang.IllegalArgumentException: Service not registered: package.MP3Player$1#b135b300
Do you know any advide?
Thanks in advance!
EDIT1:
I bound my player like this in my player activity:
MP3Player.java(Activity)
playIntent = new Intent(this, MP3Service.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
I used this tutorial and modified it.
EDIT 3:
Now I get this error:
java.lang.RuntimeException: Unable to stop service package.MP3Service#b13a6f80: java.lang.IllegalStateException
MP3Service.java
public void onCreate() {
super.onCreate();
songPosn = 0;
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
...
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void setList(ArrayList<Song> theSongs) {
songs = theSongs;
}
public class MusicBinder extends Binder {
MP3Service getService() {
return MP3Service.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public void playSong() {
player.reset();
Song playSong = songs.get(songPosn);
try {
player.setDataSource(getApplicationContext(),
Uri.parse(playSong.getPath()));
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
public void pauseMusic() {
if (player.isPlaying()) {
player.pause();
length = player.getCurrentPosition();
}
}
public void resumeMusic() {
if (player.isPlaying() == false) {
player.seekTo(this.length);
player.start();
} else {
Toast.makeText(getApplicationContext(),
"Please select a song to play", Toast.LENGTH_LONG).show();
}
}
public void stopMusic() {
player.stop();
player.release();
player = null;
}
// set the song
public void setSong(int songIndex) {
songPosn = songIndex;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if (player != null) {
try {
player.stop();
player.release();
} finally {
player = null;
}
}
}
MP3Player.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mp3_player);
getActionBar().setDisplayHomeAsUpEnabled(true);
songList = getSongList();
listAdapter = new PlayListAdapter(this, songList);
listMusic.setAdapter(listAdapter);
listMusic.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long arg3) {
currentSongPos = pos;
musicSrv.setSong(currentSongPos);
musicSrv.playSong();
}
});
}
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder) service;
musicSrv = binder.getService();
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MP3Service.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
...
protected void onDestroy() {
if (musicBound) {
stopService(playIntent);
unbindService(musicConnection);
musicSrv = null;
}
super.onDestroy();
}
Service not registered means it wasn't bound to service during unbindService() call.
Read about service lifecycle on : API Guide: Services
EDIT:
Try to add:
protected void onDestroy() {
if(musicBound){
stopService(playIntent);
unbindService(musicConnection);
musicSrv=null;
}
super.onDestroy();
}
EDIT 2:
Sorry my fault, you need to call first stopService() and then unbindService()
The Android documentation for stopService() states:
Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed
until all of these bindings are removed. See the Service documentation
for more details on a service's lifecycle.
I did a small simulation of background music play on Android, but it doesnt work... there's the code:
[my activity, in onCreate]
Intent music = new Intent(this, MusicService.class);
startService(music);
[and there's the class MusicService]
public class MusicService extends Service implements MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
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.song1);
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;
}
}
I can't hear any song in the emulator. I did complete the Manifest file like this:
<service
android:name="MusicService"
android:enabled="true">
</service>
Is there something else to add to the Manifest, is there a problem with my code or with my emulator?
Thank you!
I am shearing my code on background music play on Android. It will be solve your problem.
I head created two classes first one is MainActivity and second one is MyService.
MainActivity code is
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
Button play, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(this);
stop.setOnClickListener(this);
}
#Override
public void onClick(View src) {
switch (src.getId()) {
case R.id.play:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.stop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}
Now the MyService code is
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();
}
}
U have to create a "raw" folder in your "res" folder than paste your music file in that raw folder.