I am creating an Android app with Android Studio, however, my app crashes at runtime and I can't figure out why? My code looks fine and it has got no errors. I have an 'if statement' inside a public void onBackPressed().
//stop's the car sound that is currently being played when the devices back button is clicked
#Override
public void onBackPressed() {
if (mySound !=null) {
mySound.stop();
this.finish();
if (mySound == null) {
this.finish();
}
}
mySound is equal to a MediaPlayer.
My first 'if statement' is for when the back button is pressed (while the sound is playing), the sound will stop and the activity will close and go to the previous activity.
And my second 'if statement' is for when the back button is pressed (while the sound is NOT playing), the activity will close and go to the previous activity.
I have tried using || but that doesn't seem to work? Does anyone know what's wrong with my code?
Thanks!
ANSWER:
if (mySound !=null) {
mySound.stop();
this.finish();
}
if (mySound == null) {
this.finish();
}
Related
I am using Java and xml to create an application for the summer. This app has music in the background, that I would like to pause and then play depending on the state it is in. When i lock my screen the music does not pause it keeps playing. How would i fix this, I have tried to use the method on this site:
https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents
I have not been able to successfully get a working prototype, and I am working in android studio.
myPlayer = MediaPlayer.create(c(this is the context), myField(This is the raw file));
myPlayer.start();
myPlayer.setLooping(true);
myPlayer.setVolume(0.7f,0.7f);
What could I add to pause the mediaplayer when the lock button is pressed or the phone goes to sleep and then play it when the phone is unlocked?
#Override
protected void onPause() {
super.onPause();
if (myPlayer != null) {
myPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if (myPlayer != null) {
myPlayer.start();
}
}
In my app my first activity to launch is a login activity (A). When the login is successful another activity is launched (B), in doing so activity A is killed using finish(). This is to prevent the user being taken back to the login screen if they hit the back button, which works fine. Now when the app is closed from activity B using the home button and restored from the multitasking view the user comes back to activity B, which is great. However, when the user taps the back button in activity B the app closes and when the app is restored from the multitasking view, activity A is launched again when I actually want the behaviour clicking the home button gives and presenting the user with activity B.
Is there any way to do this?
You should simply add a check to your login activity, if the user is already signed in finish it and launch your B activity.
I'm really silly, just found my answer in one of the 'related' questions but it didn't come up when I created my question, oh well.
Here's what I did:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
Log.d("CDA", "onKeyDown Called");
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
This essentially emulates what the home button would do in activity B.
I have this app where when it navigates to another activity it does a transition animation. Now I have already got that working properly but, to get it to work i have to turn the animation setting on my phone on. I have been searching on Google and I can"t seem to find solution to my problem. So my problem is this,is it possible to turn this setting on from within the app, with a code, instead of having to manually do it?
Here is the code but as i have said above this works perfectly and I'm using a Telstra next G Huawei phone, just want to no if i can code it so i can turn the animation setting on if i decide to put it on a different phone.
//Button to restart from beginning:
//Declaring the button for OnClickListener and EditText to send data:
private void Restart() {
Button Next = (Button)findViewById(R.id.restart3);
Next.setOnClickListener(new View.OnClickListener() {
//The action the button takes when clicked:
#Override
public void onClick(View v) {
//Goes back to the start of app:
Intent i = new Intent(Height.this, Page_1.class);
//clears the stack of all Activities that were open before this one so that they don't stack up:
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
//The transition animation when going onto next page:
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
// to end the current activity:
finish();
}
});
}
I want to play an audio file in the background of my app. Easy enough. I want the music to persist and NOT stop or pause while switching between activities in my app. Also fairly easy and accomplished simply by doing this in the onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mp = MediaPlayer.create(MainActivity.this, R.raw.lostmexicancity);
mp.setLooping(true);
mp.start();
}
The problem? Getting the music to stop when I press the HOME button.
Killing the sound when the user presses the back button seems easy. Here's what I have for that and works great:
public void onPause() {
if(this.isFinishing()){ //BACK was pressed from this activity
mp.stop();
}
super.onPause(); }
Not complicated, but this does not catch presses of the HOME button. If the Home button is pressed, the music keeps playing even while the user no longer sees my app.
I have seen answers that involve setting permission in the manifest to Get Tasks which I shouldn't have to do and appears dangerous to users. Besides that, the solution didn't even work. I've seen solutions that involve using a service, but none of those work either because the home button STILL plays the music just like before because there doesn't seem to be a way to catch it and it doesn't 'finish' the app (not to mention that every time someone suggest using a service for this task multiple people come in and state that this is not a proper use for services)
It seems the only way to kill the music when the Home button is pressed is to use a non-conditional stop() within onPause, but that's no good because that's called when I swap activities with intents, causing the music to end between activities which is no good.
I have trouble imagining that such a common function like background music is this hard, but I've seen post after post with the same issue as me and no proper answers other than ones that would kill the music between activities within the app.
How do all the other apps on the Google play store accomplish this and yet there appears to be no clear answer online? I could just stop and start the music with each onPause(), but that would cause unprofessional gaps in audio not to mention it would start the background audio from the beginning over and over again which is unacceptable.
I'm a bit new to Android Programming (few months) and today, I faced the same problem you did (maybe you still do?)
I made it work as the following :
Lets say I have MainActivity, and in MainActivity I have Btn2 which leads to SecondActivity, and Btn3 which leads to ThirdActivity.
I declared at the beginning of MainActivity :
public static boolean shouldPlay = false;
I then implemented my onStop() method :
public void onStop() {
super.onStop();
if (!shouldPlay) { // it won't pause music if shouldPlay is true
player.pause();
player = null;
}
}
If the boolean shouldPlay is set to true, then my onStop() won't be called entirely and my music won't turn off. I then have to decide when I set it to true. When I switch from MainActivity to SecondActivity, I do it through an Intent and that's when I'll set shouldPlay to true :
Button Btn2 = (Button) findViewById(R.id.Btn2);
Btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
shouldPlay = true;
startActivity(intent);
}
});
And the same is done for Btn3.
Now, the last thing we want to be looking for is that if I was to go back to MainActivity after visiting SecondActivity or ThirdActivity, shouldPlay would then have been set to true. The first thing I tried was to set it to false as soon as Second and ThirdActivity are called (in their onCreate()) but it want to work, maybe because the onStop() from Main and onCreate() from others are called simultaneously (frankly I don't really get life cycle for now).
What worked is simply to set shouldPlay to false every time we launch onCreate() of Main :
shouldPlay = false;
This works properly for me.
Let me know if it does for you,
Cheers,
bRo.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_HOME){
Log.d("Jorgesys", "Home button pressed!!!");
}
return super.onKeyDown(keyCode, event);
}
but hey! This no longer works as of 4.0 + , Read this: Capture Home Key Event
Try with Back button:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
Log.d("Jorgesys", "Back button pressed!!!");
}
return super.onKeyDown(keyCode, event);
}
To stop the media player, you are using the method:
isFinishing(): if the activity is finishing, returns true; else
returns false, but you are only pausing the activity not finishing the
activity.
public void onPause() {
if(this.isFinishing()){ //INCORRECT, Here you are pausing you activity not finishing.
mp.stop();
}
super.onPause();
}
so change to:
public void onPause() {
if(mp.isPlaying())
{
mp.stop();
}
super.onPause();
}
When your activity is on pause, evaluates if your MediaPlayer is playing, if this is true then stops the audio.
I'm having a very weird situation in my app. I have an activity, on which I have log in button. On button click I'm checking whether user is logged in or not, and simultaneously showing proper message. My code looks like this:
#Override
public void onClick(View v) {
if (loginUserId == null || loginAccessToken == null) {
Intent intent = new Intent();
intent.setClassName("com.example.poc",
"com.example.poc.LoginPromptDialog");
startActivity(intent);
} else {
System.out.println("Else condition here!");
}
}
On else condition I'm printing on the log.
In my case take a scenario that user is not logged in, then Login Prompt Activity will be shown. I have a skip button on my Second Activity, on that button I'm just calling finish() method. And I'm coming back from Second Activity to First Activity. This is confirmed that my onResume() method is called when coming back from Second Activtiy.
Still user is not logged in and when I click again button on the First Activity my else condition is called. Why again my if condition is not called?
I can't figure out why this is happening.
Any kind of help will be appreciated.
I was getting "" values from the other activity. Thanks to the comments I got. Solved.