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.
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.
I have a service, which plays background music in all of my app's activities.
In every activity I added:
public void onPause() {
super.onPause();
stopService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onStop() {
super.onStop();
stopService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onResume() {
super.onResume();
startService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onRestart() {
super.onRestart();
startService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
My purpose was to stop or resume service which plays music when I close the app or turn off the screen. But It also stops when I switch to another activity.
Should I change something in my service's code?
Finally: I would like my service playing music to stop on screen turn off or app closing but not during activities switching.
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() {
}
}
Try this in your Activity's onDestroy Method...
#Override
protected void onDestroy() {
super.onDestroy();
if(isMyServiceRunning(MyService.class))
{
stopService(new Intent(this, MyService.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Here when the Activity is finished you should stop the service..
Also in your service you should release the mediaplayer
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null){
mediaPlayser.stop();
if (isFinishing()){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
I would like to create Activity with video player to play online stream using MediaPlayer class and SurfaceView to display. I'm creating MediaPlayer in separate Service so after screen rotation player don't have to be created again and don't have to connect to stream. My problem is that I don't know how to write Activity so my service wouldn't start every time after screen rotation.
My code below, in onStart() I start service but I don't know how to change it so it didn't start every time.
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback {
private String path;
private SurfaceHolder vidHolder;
private SurfaceView vidSurface;
private VideoService videoService;
private Intent playIntent;
private boolean videoBound = false;
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
VideoService.VideoBinder binder = (VideoService.VideoBinder) service;
videoService = binder.getService();
videoService.setUrl(path);
videoBound = true;
if (vidHolder != null && videoService.getMediaPlayer() != null) {
videoService.getMediaPlayer().setDisplay(vidHolder);
videoService.playVideo();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
videoBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
path = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4"; //TODO tmp
playIntent = new Intent(this, VideoService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
vidSurface = (SurfaceView) findViewById(R.id.surfView);
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(VideoPlayerActivity.this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (videoService != null && videoService.getMediaPlayer() != null) {
videoService.getMediaPlayer().setDisplay(vidHolder);
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
Log.d("ServiceConnection", "surfaceChanged " + i + " " + i1 + " " + i2);
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.d("ServiceConnection", "surfaceDestroyed");
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(musicConnection);
stopService(playIntent);
videoService = null;
}
}
Service class:
public class VideoService extends Service implements OnPreparedListener {
private MediaPlayer player;
private String path;
private final IBinder musicBind = new VideoBinder();
#Override
public void onCreate() {
Log.d("VideoService", "onCreate");
super.onCreate();
player = new MediaPlayer();
initMusicPlayer();
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
public void initMusicPlayer() {
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
}
public void playVideo() {
try {
player.setDataSource(path);
player.prepareAsync();
} catch (IOException e) {}
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
public void setUrl(String url) {
path = url;
}
public MediaPlayer getMediaPlayer() {
return player;
}
public class VideoBinder extends Binder {
public VideoService getService() {
return VideoService.this;
}
}
}
You could either check for savedInstanceState being null to only start the service if the Activity is freshly created
if (savedInstanceState == null) {
startService...
}
or handle screen rotation yourself by adding
android:configChanges="orientation|keyboardHidden|screenSize"
to your Activity in manifest. Like this onCreate will not be called on rotation any more.
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 have 4 activities in my android app.When the first activity is created, it starts music in the background. Now when the user goes from 1st activity to the 2nd activity I want the song to continue without any interruption. The song should stop only when the user is out of the app.
Right now the music stops when I am going out of one activity and starts from the beginning in the next activity.
Keep the player in the background as a static reference. Then let it know if you are moving within the app or out of it. Here is how I would do it. I am using a class named DJ for this purpose.
public class DJ {
private static MediaPlayer player;
private static boolean keepMusicOn;
public static void iAmIn(Context context){
if (player == null){
player = MediaPlayer.create(context, R.raw.music1);
player.setLooping(true);
try{
player.prepare();
}
catch (IllegalStateException e){}
catch (IOException e){}
}
if(!player.isPlaying()){
player.start();
}
keepMusicOn= false;
}
public static void keepMusicOn(){
keepMusicOn= true;
}
public static void iAmLeaving(){
if(!keepMusicOn){
player.pause();
}
}
}
Now from your Activity call the DJ like this.(Let him know if you would like to keep the music on)
public void onPause() {
super.onPause();
DJ.iAmLeaving();
}
public void onResume(){
super.onResume();
DJ.iAmIn(this);
}
public void buttonOnClick(View view){
DJ.keepMusicOn();
Intent intent = new Intent(this, TheOtherActivity.class);
startActivity(intent);
}
I did it this way and I'm pleased with the result:
1st create the service:
public class LocalService extends Service
{
// This is the object that receives interactions from clients. See RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
private MediaPlayer player;
/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder
{
LocalService getService()
{
return LocalService.this;
}
}
#Override
public void onCreate()
{
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy()
{
destroy();
}
#Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
public void play(int res)
{
try
{
player = MediaPlayer.create(this, res);
player.setLooping(true);
player.setVolume(0.1f, 0.1f);
player.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void pause()
{
if(null != player && player.isPlaying())
{
player.pause();
player.seekTo(0);
}
}
public void resume()
{
try
{
if(null != player && !player.isPlaying())
{
player.start();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void destroy()
{
if(null != player)
{
if(player.isPlaying())
{
player.stop();
}
player.release();
player = null;
}
}
}
2nd, create a base activity and extend all your activities in witch you wish to play the background music from it:
public class ActivityBase extends Activity
{
private Context context = ActivityBase.this;
private final int [] background_sound = { R.raw.azilum_2, R.raw.bg_sound_5 };
private LocalService mBoundService;
private boolean mIsBound = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doBindService();
}
#Override
protected void onStart()
{
super.onStart();
try
{
if(null != mBoundService)
{
Random rand = new Random();
int what = background_sound[rand.nextInt(background_sound.length)];
mBoundService.play(what);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onStop()
{
super.onStop();
basePause();
}
protected void baseResume()
{
try
{
if(null != mBoundService)
{
mBoundService.resume();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
protected void basePause()
{
try
{
if(null != mBoundService)
{
mBoundService.pause();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private ServiceConnection mConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder) service).getService();
if(null != mBoundService)
{
Random rand = new Random();
int what = background_sound[rand.nextInt(background_sound.length)];
mBoundService.play(what);
}
}
public void onServiceDisconnected(ComponentName className)
{
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
if(null != mBoundService)
{
mBoundService.destroy();
}
}
};
private void doBindService()
{
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
Intent i = new Intent(getApplicationContext(), LocalService.class);
bindService(i, mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService()
{
if (mIsBound)
{
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
doUnbindService();
}
}
And that's it, now you have background sound in all the activities that are extended from ActivityBase.
You can even control the pause / resume functionality by calling basePause() / baseResume().
Don't forget to declare the service in manifest:
<service android:name="com.gga.screaming.speech.LocalService" />
The idea is that you should not play music from the activity itself. On Android, Activities, and other contexts, have life cycles. It means they will live...and die. And when dead, they can't do anything any more.
So you gotta find something with a lifecycle that lasts more than a single activity if you want the music to live longer.
The easiest solution is an Android service. You can find a good thread here : Android background music service