I have developed a game using andengine
I am facing a problem when using the power Button. If I press the POWER Button while playing the game the screen turns off and the onPause() is called as expected. But when I press the HOME button or POWER button again to turn on the screen, onResume() method is called and but the lockscreen shows up.
In the onResume() method, I resume the music of the game.
So as a result lockscreen shows up , but the game music plays in the background. I do not want to play the music in the lockscreen. Please help me solving this.Thank you
The solution is here: Activity handle when screen unlocked
By registering a BroadcastReceiver filtering the Intent.ACTION_SCREEN_ON, Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_PRESENT actions, you will be able to handle these 3 cases:
Intent.ACTION_SCREEN_OFF: When the POWER button is pressed and the screen goes black.
Intent.ACTION_SCREEN_ON: When the POWER button is pressed again and lockscreen is showed up.
Intent.ACTION_SCREEN_PRESENT: When you pass the locksreen and are back in your game.
However, in my case (using a Galaxy S GT I9000 with Froyo 2.2) these actions are not called when dealing with the HOME button (and I think it's a general behavior).
One simple and quick (but maybe not the best) way to handle both HOME and POWER buttons to pause and resume your music could be to keep the onPause and onResume methods and use a simple boolean flag like this:
private boolean mPowerButton = false;
#Override
public void onPause() {
super.onPause();
// Pause your music
Log.d("Game activity", "Music paused");
}
#Override
public void onResume() {
super.onResume();
if (!this.mPowerButton) {
// Resume your music
Log.d("Game activity", "[HOME button] Music resumed inside onResume");
}
}
public class receiverScreen extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// This is the lockscreen, onResume has been already called at this
// step but the mPowerButton boolean prevented the resumption of music
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
LevelActivity.this.mPowerButton = true;
}
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
// Resume your music
Log.d("Game activity", "[POWER button] Music resumed inside ACTION_USER_PRESENT action");
LevelActivity.this.mPowerButton = false;
}
}
}
Hope it helps!
Related
I currently have an app (Java) that uses the Navigation Component with Bottom Navigation. I have a fragment for each tab.
One of the fragments navigates to a secondary fragment that features an audio player (using Media Player). This audi fragment has the following code that stops the audio when I go back to the parent fragment:
#Override
public void onDestroy() {
super.onDestroy();
if (mp != null) {
mp.pause();
mp = null;
}
}
The problem is that when the audio is playing and I tap on a different tab from the bottom navigation, the audio continues to play. I thought of using the following:
#Override
public void onStop() {
super.onStop();
if (mp != null) {
mp.pause();
mp = null;
}
}
And this solves the problem but it also prevents the audio from playing when the screen is turned off. (This doesn't happen when the onStop is not there).
The idea is to have the pause() function execute when the user taps on any of the bottom navigation tabs.
With my current structure, how can I get the sound to stop when the user taps on a bottom tab?
You can use "setOnItemSelectedListener()" to listen for clicks on Bottom Navigation.
If the user selects an item other than the one inside the audio player, stopAudioPlayer function is called
Example :-
navBottom.setOnNavigationItemSelectedListener(item -> {
if (item.getItemId() != R.id.nav_bottom_audio_player)
stopAudioPlayer();
return true;
});
i am searched many solution but could not find proper result when i press the back button of mobile i am using one counter variable and put the condition like when counter is 0 it called the music file.
but when i am comeout from that activity means press back button of mobile still that activity is runnig and called the music file .i am using this below code for music play.please anyone have solution then help me.i am using one timer function.like this when i==0 that time call one music file but when i press back button. this timer i wants to stop.
public void btntimer(){
new Handler().postDelayed((new Runnable() {
#Override
public void run() {
if(i!=32) {
matchNo();
}
else {
try{
showdialog();
media=1;
}catch (Exception e){
media=0;
}
updatepoints();
}
}
}), 4000);
}
song=MediaPlayer.create(this,R.raw.cartoon1);
song.start();
song.setLooping(false);
If I understand you correct, you want to stop playing music on back button pressed.
Call stop() in onBackPressed method.
#Override
public void onBackPressed() {
song.stop();
song.release();
song = null;
}
I have a button which leads to open a Preference Screen, hence I have not released Media Player object in onPause().
But this leads to problem of running background music when clicks on Home button in Android Emulator.
take variable before oncreate
boolean pref_clicked=false;
onclick of button just write pref_clicked=true;
and
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!pref_clicked)
//pause your music player
}
#Override
public void onStop() {
super.onStop();
//pause your music player
}
I am using MediaController.MediaPlayerControl in order to display a MediaController at the bottom of my Custom View but I can't get it to work properly. When I play music for first time then there should be pause button visible but instead there is play and when I press that button then the music is paused correctly and state remains the same and after that its working properly. Also when I play next song, the old MediaController widget gets overlapped with the new one. And sometimes the progress/seek bar doesn't refresh while the music is playing. It just updates itself when something on the MediaController is pressed (Play/Pause, forward, etc).
I found these questions similar to mine but I don't think the answers they got will solve my problem.
Android mediacontroller Play Pause controls not refresh properly
Android MediaController seekbar not refreshing
Android VideoView Playback Controls Show "Play" Initially Instead of "Pause" Even Though File is Already Playing
This is how I initialize the controller:
private void setController()
{
controller = new MusicController(this);
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.song_list));
controller.setEnabled(true);
}
This is how I show controller:
public void playMusic()
{
musicSrv.playSong(); //Play song in a service
setController();
controller.show(0);
controller.requestFocus();
}
I had exactly this problem. Don't know if you still need help, but I thought I'd post anyway. For posterity, are you following this tutorial?
First, the easy problem: you're getting multiple instances of your controls because of repeated calls to setController(). Change the first line of your function to:
if (controller == null) controller = new MusicController(this);
With regards to the play button malfunctioning, I believe it's because you're showing it before the music player has been prepared (disclaimer: I'm a newbie to Android myself, and the following are the things I've found to have worked).
Set up a broadcast from your music-playing service to notify your music-controlling activity when the musicplayer has been prepared. Append the following function in your music-playing service to broadcast intent:
#Override
public void onPrepared(MusicPlayer player) {
// Do some other stuff...
// Broadcast intent to activity to let it know the media player has been prepared
Intent onPreparedIntent = new Intent("MEDIA_PLAYER_PREPARED");
LocalBroadcastManager.getInstance(this).sendBroadcast(onPreparedIntent);
}
Set up a broadcast receiver in your music-controlling activity to receive the intent broadcast by your service. Add the following class to your activity:
// Broadcast receiver to determine when music player has been prepared
private BroadcastReceiver onPrepareReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
// When music player has been prepared, show controller
controller.show(0);
}
};
Register your receiver in your activity's onResume() method:
// Set up receiver for media player onPrepared broadcast
LocalBroadcastManager.getInstance(this).registerReceiver(onPrepareReceiver,
new IntentFilter("MEDIA_PLAYER_PREPARED"));
Depending on the structure of your code, you'll have to do some general tidying up. In my code, I've only called setController() twice: from the onCreate() and onResume() methods in my activity. I also only call controller.show(0) from my broadcast receiver, and my onResume() method.
Bit of a strange one this and I can't work out what's happening.
When I launch my app (a game) the music starts playing. I have a button which turns the music on and off. The settings are saved to shared prefs so they are retained.
All works well, you can press the home key, re-invoke the app, leave it in the background while doing other things etc. However, if the app is left in the background for a while (say, overnight), and then re-invoked. Everything works apart from the music.
You can go into the main menu, hit the 'music on/off' button multiple times, but get nothing.
The only way to start the music is to kill the app (or exit correctly, ie, press the 'back' key from the main menu) and then relaunch it so everything is re-created from scratch.
I've confirmed that the 'music' object is still valid and the 'music on/off' button presses are being registered.
Has anyone has similar issues with Media Player? I can't work out what I am (or am not doing) to cause this.
Code
This is my media player class:
public class MusicMan implements MediaPlayer.OnPreparedListener {
MediaPlayer musicPlayer;
MusicMan(Context myContext){
musicPlayer = MediaPlayer.create(myContext, R.raw.music);
musicPlayer.setVolume(.6f, .6f);
}
public void listener(){};
public void start(){
musicPlayer.setLooping(true);
musicPlayer.start();
}
public void stop(){
musicPlayer.stop();
}
public void pause(){
musicPlayer.pause();
}
public int getPos(){
return musicPlayer.getCurrentPosition();
}
public void skipTo(int position){
musicPlayer.seekTo(position);
}
#Override
public void onPrepared(MediaPlayer arg0) {
}
}
And then I simply crate an object like so:
MusicMan music = new MusicMan(view.getContext());
And then I just start and stop the music using the methods in the MusicMan class:
music.start();
You need to use
musicPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
Use this where you set new MediaPlayer player. It sets the wake lock to MediaPlayer and don't let CPU go sleep till you yourself didn't kill or stop application.