EDIT: Realized and solved the problem on my own. Thank you.
Please bear with me it's actually my first time using Android Studio and Stackoverflow. What I am trying to make is a music player, there are 2 activities. In the second activity when the user taps the play button, the music plays. If the user backs, the music will stop playing and go back to the first activity. Somehow on back pressed is not working. It's grayed out and it tells me that the Method is never used.
package com.radiantminds.radiantminds;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
}
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
}
You have to put it on an Activity, don't forget to call #Override
#Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
The problem is that you have to place the onBackPressedMethod() outside, as follows :
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
#Override
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
//if you want to do the back action aswell, uncomment the following line
//super.onBackPressed();
}
Make sure the #override is there above the method and you don't declare the method twice.
other alternative is:
onKeyDown()
or add:
super.onBackPressed();
in the method onBackPressed (though i dont suggest it really)
Related
hello I use MediaPlayer for play sound in my project in android studio
when I click in a button and play sound , and when I click in another button that button play another sound , I want the first sound or another sound be stoped and just the last button that I clicked be played
I try this code but it not worked
package azad.broooska.fartfuns;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MusicFartActivity extends AppCompatActivity implements View.OnClickListener {
private CardView cardView1, cardView2, cardView3, cardView4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cardView1 = findViewById(R.id.card_music1);
cardView2 = findViewById(R.id.card_music2);
cardView3 = findViewById(R.id.card_music3);
cardView4 = findViewById(R.id.card_music4);
cardView1.setOnClickListener(this);
cardView2.setOnClickListener(this);
cardView3.setOnClickListener(this);
cardView4.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
final MediaPlayer s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
final MediaPlayer s2 = MediaPlayer.create(this, R.raw.fart_ballade);
final MediaPlayer s3 = MediaPlayer.create(this, R.raw.fart_uverture);
final MediaPlayer s4 = MediaPlayer.create(this, R.raw.farting_xmas);
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music2) {
s2.start();
s1.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music3) {
s3.start();
s2.stop();
s1.stop();
s4.stop();
} else {
Toast.makeText(this, "noThing", Toast.LENGTH_SHORT).show();
}
}
}
you are creating new instances of MediaPlayer each time something is clicked and assigning the variables to new objects; make s1,s2... class property;
MediaPlayer s1 ,s2,s3,s4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
//some code
s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
//assign the rest;
}
public void onClick(View view) {
int id = view.getId();
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
}
//rest of the code
}
Well, its seems like you don`t want to play very long sounds because you have names like
"fart_ballade" and "fart_uverture" in your code.
If your sounds are not very long it is better to work with the SoundPool class.
The MediaPlayer class sometimes can cause problems if you switch fast between sounds.
So if your sounds are not that long, you can try the SoundPool class.
Here you can learn more about the SoundPool class:
How to use SoundPool
I won`t write any code because SoundPool needs more than 5-6 lines of code to work properly.
I am working on android activities. I have one main activity and two other activities, these two activities are launched from the main activity. There are back buttons on each of When any of these two activities are launched , on pressing the back button i want the intent to start the resumed main activity, not to relaunch it on other page.
Below is the code for Main Activity
package com.example.nadeemahmad.smartcalculator;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends Activity {
Button show_cam_ctrl,
show_voice_ctrl;
TextView ma_res_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Control Buttons
show_cam_ctrl = (Button) findViewById(R.id.show_cam_ctrl);
show_voice_ctrl = (Button) findViewById(R.id.show_voice_ctrl);
show_cam_ctrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,cam_calculator.class);
startActivity(i);
}
});
show_voice_ctrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,voice_calculator.class);
startActivity(i);
}
});
}
Codes for the two activities
public class voice_calculator extends Activity {
Button back_frm_voice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_calculator);
back_frm_voice = (Button) findViewById(R.id.back_frm_voice);
back_frm_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(voice_calculator.this,MainActivity.class);
startActivity(i);
finish();
}
});
}
}
public class cam_calculator extends Activity {
Fragment cam_fragment;
Button back_frm_came;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cam_calculator);
back_frm_came = (Button) findViewById(R.id.back_frm_came);
back_frm_came.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(cam_calculator.this,MainActivity.class);
startActivity(i);
finish();
}
});
}
}
This is the main activity, having two buttons on top BTN1 and BTN2
The second activity is launched on the BTN1 press, but when i press the back button on the top
This mainactivity is launched, but not the resumed one, when i press the back button on my phone then it get close and the main activity with calculations on screen appears, what i want is , when i press the back button, so the intent should take me to the main activity with resumed calculations.
Just call cam_calculator.this.finish() or voice_calculator.this.finish() from the OnClickListener. Those activities will finish and "automatically" return to the MainActivity.
edit:
If you put a code like this: startActivity(new Intent(this, SomeActivity.class)); you'll directly telling the framework to start an activity.
Just remove that!
Please use the below edited code,
public class voice_calculator extends Activity {
Button back_frm_voice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_calculator);
back_frm_voice = (Button) findViewById(R.id.back_frm_voice);
back_frm_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent i = new Intent(voice_calculator.this,MainActivity.class);
//startActivity(i);
finish();
}
});
}
}
public class cam_calculator extends Activity {
Fragment cam_fragment;
Button back_frm_came;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cam_calculator);
back_frm_came = (Button) findViewById(R.id.back_frm_came);
back_frm_came.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent i = new Intent(cam_calculator.this,MainActivity.class);
//startActivity(i);
finish();
}
});
}
}
The MainActivity will be in the stack, so when you do finish() in your second activity, the MainActivity will be popped and onResume() will be called instead onCreate()
From what I understand, you're launching two children activities from a parent activity and when you press back, the parent activity is restarting. It's because the Android call stack doesn't know that the parent activity is a parent activity for the two children activities. In your Android Manifest, specify parentActivity for the two child activities like this -
android:parentActivityName="com.example.android.ParentActivity"
Let me know if it still doesn't work. Happy Coding!
I am very new to Android development. I am following Google's Android "classes" and am receiving an error for this code in Eclipse:
package com.feistie.myfirstapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
//does not behave as a buutton
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
}
}
#Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass
// Stop method tracing that the activity started during onCreate()
android.os.Debug.stopMethodTracing();
}
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// Release the Camera because we don't need it when paused
// and other activities might need to use it.
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage (View view) {
// Do Something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
There is an error for each of these lines:
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
The error for the first and third lines says "mCamera cannot be resolved to a variable." The error for the second line just says "mCamera cannot be resolved."
If you need more information please let me know.
Thanks!
You need to declare mCamera before you can reference it:
public class MainActivity extends Activity {
Camera mCamera;
And then you need to initialize it, probably in onResume()
#Override
protected void onResume() {
super.onResume();
mCamera = Camera.open()
}
Make sure you added the appropriate permission that you manifest:
<uses-permission android:name="android.permission.CAMERA" />
Addition
You need to declare_every_ variable before you try use it in Java. I don't see where you declare mTextView either.
public class MainActivity extends Activity {
Camera mCamera;
TextView mTextView;
I have a button in an activity and when i press it the sound plays. The sound itself is 2 seconds long. And it only plays when i press on the button. I wanna make it that a user can hold down the button and the sound plays till he releases the button. How can i do this? Here's my current code.
package android.app;
import android.app.R;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class activity2 extends Activity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//back button that takes u to main.xml
Button next = (Button) findViewById(R.id.Back);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
} );
//Button that plays sound (whippingsound)
Button sound = (Button) findViewById(R.id.sound);
sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(activity2.this, R.raw.whippingsound);
mp.start();
}
} );
}
}
Thanks!!!
The solution to your problem is a combination of
Triggering event when Button is pressed down in Android
and
play sound while button is pressed -android.
Namely, you're using an onClickListener instead of onTouchListener.
Try this instead (note: I also moved the media player out so you create it once and use it over and over again).
public class activity2 extends Activity{
MediaPlayer mp = null;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//back button that takes u to main.xml
Button next = (Button) findViewById(R.id.Back);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
} );
mp = MediaPlayer.create(activity2.this, R.raw.whippingsound);
//Button that plays sound (whippingsound)
Button sound = (Button) findViewById(R.id.sound);
sound.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mp.setLooping(true);
mp.start();
break;
case MotionEvent.ACTION_UP:
mp.pause();
break;
}
return true;
}
});
}
I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.