I have an app that plays some music file while the application is open but when i press the power button the sound keeps playing for some reason. Is there a way to override the power button so it will also stop the media player when pushed ?
MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
...
...
mp = MediaPlayer.create(this, mAudio[0]);
mp.start();
...
...
}
I would like to call mp.stop() when the power button is pressed.
Override onKeyDown and check if it's KEYCODE_POWER.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// Stop the media player here
return true;
}
return super.onKeyDown(keyCode, event);
}
Add this method:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// stop the media from playing
return true;
}
return super.onKeyDown(keyCode, event);
}
This method is being activated when a key is being pressed. It checks what key is pressed and reacts for it.
First of all you need to understand, when you want to pause or stop the sound. If you want to do it, when you exit/hide an application, then overriding onKeyDown won't help. I think better approach in this case will be:
protected void onCreate(Bundle onSaveInstanceState) {
super.onCreate(onSaveInstanceState);
mp = MediaPlayer.create(this, mAudio[0]);
}
protected void onStart() {
super.onStart();
mp.start();
}
protected void onStop() {
super.onStop();
mp.stop();
}
But if you want to stop your sound only when Power button is pressed, then yes, you need to override onKeyDown
Related
In my application I override volume up and volume down keys. The problem is that when user click one of these two keys, sound is played. I want somehow to disable/mute this sound.
Here is fragment of my code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN: {
// do something when user click volume down key
return true;
}
case KeyEvent.KEYCODE_VOLUME_UP: {
// do something when user click volume up key
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Using onKeyDown or onKeyUp still gives the default sound of changing the volume. Use dispatchKeyEvent instead.
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
return true;
default:
return super.dispatchKeyEvent(event);
}
}
I figured it out for myself.
There is a way to stop the sound when volume key is pressed. You need to play an empty sound infinitely, so when user click a volume key it is "trying" to change the media volume, so there isn't click sound played.
You can download an empty sound by searching for empty sound and then put it in your raw folder in the project.
The last step is just to override the volume keys.
Here is the code you need:
Define MediaPlayer variable.
private MediaPlayer infinite_sound;
In onResume() you need to play the empty sound infinitely.
#Override
protected void onResume() {
super.onResume();
infinite_sound = MediaPlayer.create(this, R.raw.empty);
infinite_sound.setLooping(true);
infinite_sound.start();
}
In onPause() you need to stop the sound.
#Override
public void onPause() {
super.onPause();
infinite_sound.release();
}
And finally overriding the actions of the buttons.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN: {
// Do something when volume down button is clicked
return true;
}
case KeyEvent.KEYCODE_VOLUME_UP: {
// Do something when volume up button is clicked
return true;
}
}
return super.onKeyDown(keyCode, event);
}
my problem is :
As in the Instagram's Video recording activity, I whant to perform an action(record audio) for the time that a button is pressed..
than when the button is released i whant to perform another action (the saving of the audio file and the release of the resoruces)
thaks you in advantage
You can use OnTouchListener :
button.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if(arg1.getAction() == MotionEvent.ACTION_DOWN) {
//start recording
}
else if(arg1.getAction() == MotionEvent.ACTION_UP) {
//stop recording
}
return true;
}
});
I'm having a problem when I press the back key to leave game at this web site. I get a forced error message on back key. I used the destroy code I learned from my first question. Didn't change anything. Any ideas?
public class MainActivity extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.limejs.com/static/roundball/index.html");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
finish();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up
// to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
#Override
public void onDestroy() {
super.onDestroy();
myWebView.destroy();
}
}
Here is the Logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.roundball.MainActivity.onKeyDown(MainActivity.java:33)
at android.view.KeyEvent.dispatch(KeyEvent.java:1256)
at android.app.Activity.dispatchKeyEvent(Activity.java:2078)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent
(PhoneWindow.java:1771)
at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2563)
at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2538)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1870)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)`enter code here`
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at dalvik.system.NativeStart.main(Native Method)
I have used this code before to load web sites, it is just particular to this game?
i would remove the return true; right after the finish();
It would help if you had some adb logs to show the exact error you are getting.
You can also check to see if myWebView is not null. I am thinking that might be null as well.
Your log says:
java.lang.NullPointerException at
com.example.roundball.MainActivity.onKeyDown(MainActivity.java:33)
Which means there is a null reference in the code inside the onKeyDown method at the moment of execution. You only use 2 references there, but since its unlikely that you receive a null KeyEvent (it comes from the Android Runtime and documentation says implicitly that you always receive a valid reference when onKeyDown is called), it has to be the reference to your webview. So check if myWebView != null before calling myWebView methods, like this.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if(myWebView != null) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
finish();
return true;
}
} else {
android.util.Log.w("MyActivity", "myWebView is null!!");
}
// If it wasn't the Back key or there's no web page history, bubble up
// to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
From that code I can't tell what is causing you to have a null reference to the webview, but It might tell you where to look next for the problem if you expect your webview reference to be not null.
change your code to the code given below.. basically.. i updated your call to finish() to MainActivity.this.finish() , where MainActivity is your activity! So, you will have to change MainActivity to whatever name you gave.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
MainActivity.this.finish();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up
// to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//replace for this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
if (keyCode != KeyEvent.KEYCODE_BACK){
return MainActivity.onKeyDown(keyCode, event);
}else{
myWebView.destroy();
MainActivity.finish();
return false;
}
}
I would like to start a new activity for a result, with startActvityForResult(), but I would like to have the back button working as normal in the new activity.
Currently when I invoke a new Activity for result, nothing happens when I press the back button in the new Activity.
I tried something like this:
#Override
public void onBackPressed() {
setResult(0);
super.onBackPressed();
finish();
}
in the new Activity, but it didn't work. Still nothing happens when the back button is pressed.
Is there a way around this?
EDIT : I could of course load the last Activity in the onBackPressed() (can I?), but it seems like a rather crappy hack.
Alex Ady's answer solves my problem, but I still don't understand why onBackPressed() doesn't work. The working code now is something like this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
setResult(1);
finish();
}
return super.onKeyDown(keyCode, event);
}
I could use an explanation.
You could try
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return super.onKeyDown(keyCode, event);
}
You shouldn't have to override the Back button behavior at all. By default, if the user presses the back button, the result will be Activity.RESULT_CANCELED.
Try getting rid of the line that contains the finish().
I have created an application and with some background music.
Result = SUCCESS
Problem is.. -.- if app receives a call, music is still playing and plays instead of the user's original ringtone.
Plus if "Home" button is selected on the phone. Activity exits but the music is still running?
I managed to quit the music if the "Back" button on the phone is selected.
other than that music runs 24/7.
What I have used is.
A menu option in the application that when the user selected "Menu" a list of options pop up and an option to choose "Settings..."
If the user selects "Settings..." a preference dialogue pops up to check or uncheck music (ON/OFF)
Result = SUCCESS
The music plays throughout the application, from activity to activity.
This is my media player code in my application.
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
Music.play(this, R.raw.bgmusic);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
finish();
Music.stop(this);
return true;
}
return super.onKeyDown(keyCode, event);
}
This is my music.java
public class Music {
private static MediaPlayer mp = null;
/** Stop old song and start new one */
public static void play(Context context, int resource) {
stop(context);
// Start music only if not disabled in preferences
if (Prefs.getMusic(context)) {
mp = MediaPlayer.create(context, resource);
mp.setLooping(true);
mp.start();
}
}
/** Stop the music */
public static void stop(Context context) {
if (mp != null) {
mp.stop();
mp.pause();
mp.release();
mp = null;
}
}
}
anyone have a clue?
You need to call
Music.stop(this);
in the onPause method. This may have the effect of an instant glitch, when switching from one of yours activities to another.
Read also this question and the accepted answer.