I'm developing a simple Android game that plays sound in background by service. When game starts, the sound is playing good. But when pressing volume up key or down button, the app exits immediately.
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.relax);
}
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;
}
}
this code to start playing sound
public void playAudio() {
Intent objIntent = new Intent(this, PlayAudio.class);
startService(objIntent);
}
Problem solved. I just missed the condition:
if (keyCode == KeyEvent.KEYCODE_BACK){}
Related
Heres my problem:
I am implementing a music player (PlayerActivity.java / xml) which is bound to a service (PlayerService.java) that basically is just an instance of a musicplayer so that it can run in the background. When lefting the app or changing the activity and the restarting the activity i want to bind to the still running service without stopping or restarting it. I have tried using only bindService() but that made me face the problem: somehow without calling startService() before bindService the Service doesn't get initialized or it takes a few milliseconds so that the functions only get null when accessing service functions.
Here is my service class:
public class playerService extends Service {
public boolean running = false;
public MediaPlayer mediaPlayer;
public boolean isPrepared = false;
private String url;
public class serviceBinder extends Binder {
public playerService getService() {
return playerService.this;
}
}
public boolean isRunning(){
return running;
}
private IBinder mBinder = new serviceBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Service", "started");
mediaPlayer = new MediaPlayer();
running = true;
Log.e("!!!", running + "");
return START_STICKY;
}
public void pause() {
mediaPlayer.pause();
}
public void resume() {
mediaPlayer.start();
}
public void setupPlayer() {
try {
if (mediaPlayer != null) {
mediaPlayer.reset();
}
} catch (Exception e) {
Log.e("MediaPlayer", e.getMessage());
}
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.e("MediaPlayerToo", e.getMessage());
}
}
public void reset(){
mediaPlayer.reset();
}
public void updateUrl(String url){
this.url = url;
}
public void start(){
mediaPlayer.start();
}
public int getCurrentPosition(){
return mediaPlayer.getCurrentPosition();
}
public int getDuration(){
return mediaPlayer.getDuration();
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.reset();
}
}
I experimented with waiting until the Service has started with a boolean. But when i add any kind of code
after
mService = binder.getService();
startService(intent);
it seems to not get created at all.
Here is also my onServiceConnected class
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
playerService.serviceBinder binder = (playerService.serviceBinder) service;
Intent intent = new Intent(getApplicationContext(), playerService.class);
mService = binder.getService();
startService(intent);
//... <- adding code here will result in the Service not starting?!!
}
I know that my problem is quite confusing, but this was the best i could come up explaining it. I would be really glad if you had any idea because this problem stops me from deployment. Thank you very much!!
I'm developing music player app that runs music on the background service and when I leave the app media player stops.
This is my code when I leave the app media player mustn't be playing.
class MusicService extends Service{
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
private void initPlayer(){
if (mediaPlayer==null){
mediaPlayer =new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(this,Settings.System.DEFAULT_RINGTONE_URI);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent!=null && intent.getAction()!=null && intent.getAction().equals("com.play")){
mediaPlayer.start();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
If you mean to keep playing the music in the background after leaving the app, update the manifest too:
Android background music service
as this post describes.
I'm relatively new to android development and I'm trying to make a game in Android Studio where I want background music to play. Here is my code for the service:
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.backgroundmusic);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
player.pause();
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
player.pause();
}
}
And in the activity where I want to initialise the backgroundmusic
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
which is placed in the onCreateMethod. When I open the activity where I call the service to play the music, nothing happens, total silence.
For some further details: the backgroundmusic file is in a .mp3 format and the phone on which I do my testing is a Nexus 6 running the latest version of Marshmallow.
I'm probably missing something obvious, can anyone point it out for me and/or give any tips on how to do it better in the future? Thanks in advance.
try this piece of code for running the music on the start up
public class start extends Activity {
MediaPlayer intro;
#Override
protected void onCreate(Bundle Start) {
// TODO Auto-generated method stub
super.onCreate(Start);
setContentView(R.layout.start);
intro = MediaPlayer.create(start.this,R.raw.SONGNAME);
intro.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStart = new Intent("com.example.main.MAIN");
startActivity(openStart);
}
}
};
timer.start();
}
#Override
protected void onPause() {
super.onPause();
intro.release();
finish();
}
and make sure that the music file is located in the correct folder (raw)
Try to add a prepare-Listener:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "preparation Completed ...playing ");
player.start();
}
});
I think the setVolume is by default handled with a float (0=off, 1=max). Check your log output too. Sometimes the MediaPlayer is reporting a error-code.
EDIT / Second approach:
Did you added this line to your manifest (inside application tag)?
<application
... >
<service android:name="BackgroundSoundService" android:enabled="true"></service>
I have a service to play sound.
I'm trying to stop the sound when I receive a call but I can't.
I want to stop the sound when I receive a call and replay when it ends.
Someone know what I did wrong?
This is my Service code:
public class MyMediaPlayer extends Service implements OnInfoListener, OnPreparedListener, OnErrorListener, AudioManager.OnAudioFocusChangeListener {
public static MediaPlayer mMediaPlayer;
public static String START_PLAY = "START_PLAY";
IBinder mBinder = new LocalBinder();
MusicServicePhoneStateListener mPhoneListener;
public static final String BROADCAST_ACTION = AC.PACKAGE_NAME+".ACTION_HEADSET_PLUG";
Intent intent;
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
/*public MyMediaPlayer getServerInstance() {
return MyMediaPlayer.this;
}*/
}
#Override
public void onCreate()
{
super.onCreate();
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
intent = new Intent(BROADCAST_ACTION);
}//onCreate
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getBooleanExtra(START_PLAY, false)) {
initializePlayer();
}
return START_STICKY;
}
public void initializePlayer() {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mMediaPlayer.setDataSource("rtsp://example.com/file.stream");
}
catch (Exception e) {
Log.e("MyMediaPlayer", "Error");
}
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnInfoListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.prepareAsync();
}
#Override
public void onPrepared(MediaPlayer player) {
startMediaPlayer();
}
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
if (mMediaPlayer == null) initializePlayer();
else if (!mMediaPlayer.isPlaying()) mMediaPlayer.start();
mMediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
stopMediaPlayer();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
pauseMediaPlayer();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mMediaPlayer.isPlaying()) mMediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
#Override
public void onDestroy(){
stopMediaPlayer();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);
}
#Override
public boolean onError(MediaPlayer player, int what, int extra) {
if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED || what == MediaPlayer.MEDIA_ERROR_UNKNOWN || extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT || extra == MediaPlayer.MEDIA_ERROR_IO) {
Log.e("MediaPlayer","Error");
}
stopMediaPlayer();
return true;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
public void startMediaPlayer() {
mMediaPlayer.start();
}
public void pauseMediaPlayer() {
if(mMediaPlayer.isPlaying()) mMediaPlayer.pause();
}
public void stopMediaPlayer() {
if(mMediaPlayer.isPlaying()) mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
Log.d("MediaPlayer","stop()");
}
private class MusicServicePhoneStateListener extends PhoneStateListener {
private boolean mResumeAfterCall = false;
#Override
public void onCallStateChanged(int state, String incoming_number) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
mResumeAfterCall = mMediaPlayer.isPlaying();
stopMediaPlayer();
break;
case TelephonyManager.CALL_STATE_IDLE:
if (mMediaPlayer == null && mResumeAfterCall) initializePlayer();
break;
default:
break;
}
}
}
}
I do not understand why pause() and stop() are not working :(
I have put stopMediaPlayer(); on TelephonyManager.CALL_STATE_OFFHOOK || TelephonyManager.CALL_STATE_RINGING and initializePlayer(); on TelephonyManager.CALL_STATE_IDLE an this work, but I do not know why not work with stop() or pause().
You can try a some hack.
Remember current play progress with getCurrentPosition()
Execute release()
When you need to resume playing you need open stream again and rewing to last remember position by seekTo(int ms)
64 state explanation :
It's the 'stopped' state. When in that state, you need to call
prepare() again before starting playback.
I am using a Service to play background Music. The problem is that the music continues playing when i have finished the activity.
Here is code From Main Activity which starts the service
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
startService(svc);
BackgroundSoundService.java
public class BackgroundSoundService extends Service {
private static final String TAG = null;
public static MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("atMedia", "Backround Music playing");
player = MediaPlayer.create(this, R.raw.background);
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() {
super.onDestroy();
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Try to stop service from your MainActivity:
Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
stopService(svc);
You have to call selfStop() method inside your service.
or use stopService() API