I want to add a button in my application that turns off the music but I don't know how to approach it, I have an idea but I'm sure it's far from best so I want to consult with you. The situation is as follows:
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer easysong;
MediaPlayer normalsong;
MediaPlayer hardsong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.land_main);
mContext = this;
restartButton = (Button)findViewById(R.id.restartButton);
restartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
easysong = MediaPlayer.create(MainActivity.this, R.raw.arideniro);
normalsong = MediaPlayer.create(MainActivity.this, R.raw.junior);
hardsong = MediaPlayer.create(MainActivity.this, R.raw.ketsathis);
counter = 101;
i = 500 - dif;
new Thread(new Runnable() {
public void run() {
if(i==500){
easysong.start();}
else if(i==375){
normalsong.start();
}else if(i==250){
hardsong.start();
}
while (counter > 0) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter--;
runOnUiThread(new Runnable() {
#Override
public void run() {
scoreText.setText(Integer.toString(counter));
}
});
if(i>150){
i/=1.01;}
else if(i>90-(dif/10)){
i-=1;
}
}if (counter==0) {
mChronometer.stop();
if(easysong.isPlaying()) {
easysong.stop();
easysong.release();
easysong = null;
}else if(normalsong.isPlaying()){
normalsong.stop();
normalsong.release();
normalsong = null;
}else if(hardsong.isPlaying()){
hardsong.stop();
hardsong.release();
hardsong = null;
}
This is the main class of my app where the mediaplayer is used, now I deleted much of the code because it was irrelevant to the mediaplayer and the question, so don't look for the missing brackets and such. And this here is the main menu class where the Switch that will turn on and off the music will be located:
public class MainMenu extends Activity{
private Button easy;
private Button normal;
private Button hard;
private Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
easy = (Button) findViewById(R.id.btn_easy);
scores = (Button) findViewById(R.id.btn_highscores);
easy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dif = 0;
startGame();
}
});
}
public void startGame() {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
So my idea is simnple, to add a variable in MainActivity like "int p;" and from the MainMenu class to change it's state between 0 and 1, then I will add around each line that starts music an if(p==1) but is this a good approach ? Also I would like the value of the int to be saved when the app is closed
Related
In my Code I have an Intent to an other Activity but when I use my Phone to test it nothing appears. The program doesn't crashes or something like that. It simply does nothing. I have another Intent and this works perfectly. I don't know what the problem is.
I am using the onClick feature on the xml file
On the Main Activity:
public class MainActivity extends AppCompatActivity {
private Object TextView;
int eggcounter;
Button b1;
android.widget.TextView textClicks;
private Object SafeBrowsingResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b1 = findViewById(R.id.b1);
eggcounter = 100;
final ImageButton ImgButton = findViewById(R.id.eggBtn);
ImgButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
eggcounter = eggcounter - 1;
updateEgg();
if (eggcounter < 80) {
ImgButton.setImageResource(R.drawable.egg_2);
if (eggcounter < 60){
ImgButton.setImageResource(R.drawable.egg_3);
if (eggcounter < 40) {
ImgButton.setImageResource(R.drawable.egg_4);
if (eggcounter < 15) { ImgButton.setImageResource(R.drawable.egg_5);
if (eggcounter <= 0) {
b1.setVisibility(View.VISIBLE);
ImgButton.setImageResource(R.drawable.egg_ende);
b1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
}
}
);
}
}
}
}
}
}
}
);
}
public void updateEgg() {
textClicks = (TextView) findViewById(R.id.textScore);
textClicks.setText(eggcounter + " ");
}
public void backstartseite(View view) {
Intent back = new Intent(this, Startseite.class);
startActivity(back);
}
public void ende (View view) {
Intent e = new Intent(this, Ende.class);
startActivity(e);
}
}
You are never calling backStartSeite or ende therefore no Intent fires.
Also don't set the onClickListener of b1 inside another onClickListener (your listener for b1 will only be able to handle click events once the other button has been clicked already - this would confuse users).
If you want your Intent to work, call either startSeite or ende in the outer onClickListener.
I am facing problem in my app. All the audios are playing well but the problem is when I press on the first button to start playing audio, it plays it and if I click on next play button that also starts playing but the first audio does not stop. how to stop that. please help
Here, my app java code :
public class ringtone_tab extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtone_tab);
clk6 = (Button) findViewById(R.id.btn_play6);
clk5 = (Button) findViewById(R.id.btn_play5);
clk4 = (Button) findViewById(R.id.btn_play4);
clk3 = (Button) findViewById(R.id.btn_play3);
clk2 = (Button) findViewById(R.id.btn_play2);
clk1 = (Button) findViewById(R.id.btn_play1);
mdx6 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_vandana);
mdx5 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_tandav_mantra);
mdx4 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shiv_om);
mdx3 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shiv);
mdx2 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_aaradhna);
mdx = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shankar);
}
public void setBtn_play6(View v)
{
if(mdx6.isPlaying())
{
mdx6.stop();
mdx6.reset();
mdx6.release();
}
mdx6 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_vandana);
mdx6.start();
}
public void setBtn_play5(View v)
{
if(mdx5.isPlaying())
{
mdx5.stop();
mdx5.reset();
mdx5.release();
}
mdx5 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_tandav_mantra);
mdx5.start();
}
public void setBtn_play4(View v)
{
if(mdx4.isPlaying())
{
mdx4.stop();
mdx4.reset();
mdx4.release();
}
mdx4 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv_om);
mdx4.start();
}
public void setBtn_play3(View v)
{
if(mdx3.isPlaying())
{
mdx3.stop();
mdx3.reset();
mdx3.release();
}
mdx3 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv);
mdx3.start();
}
public void setBtn_play2(View v)
{
if(mdx2.isPlaying())
{
mdx2.stop();
mdx2.reset();
mdx2.release();
}
mdx2 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_aaradhna);
mdx2.start();
}
public void setBtn_play1(View v)
{
if(mdx.isPlaying())
{
mdx.stop();
mdx.reset();
mdx.release();
}
mdx = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shankar);
mdx.start();
}
}
Introduce new method call like stopAllplayers
private void stopAllPlayers(){
if(mdx1 != null && mdx1.isPlaying())
{mdx1.stop();mdx1.reset(); mdx1.release();}
if(mdx2 != null && mdx2.isPlaying())
{mdx2.stop();mdx2.reset(); mdx2.release();}
if(mdx3 != null && mdx3.isPlaying())
{mdx3.stop();mdx3.reset(); mdx3.release();}
if(mdx4 != null && mdx4.isPlaying())
{mdx4.stop();mdx4.reset(); mdx4.release();}
if(mdx5 != null && mdx5.isPlaying())
{mdx5.stop();mdx5.reset(); mdx5.release();}
if(mdx6 != null && mdx6.isPlaying())
{mdx6.stop();mdx6.reset(); mdx6.release();}
}
then call this method in all of your play methods.
public void setBtn_play6(View v)
{
stopAllPlayers()
........
do this for all setBtn_play1, setBtn_play2.....
Use below code with one media player
public class ringtone_tab extends AppCompatActivity {
Button clk1;
Button clk2;
Button clk3;
Button clk4;
Button clk5;
Button clk6;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtone_tab);
clk6 = (Button) findViewById(R.id.btn_play6);
clk5 = (Button) findViewById(R.id.btn_play5);
clk4 = (Button) findViewById(R.id.btn_play4);
clk3 = (Button) findViewById(R.id.btn_play3);
clk2 = (Button) findViewById(R.id.btn_play2);
clk1 = (Button) findViewById(R.id.btn_play1);
mediaPlayer = new MediaPlayer();
}
public void setBtn_play6(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_vandana);
mediaPlayer.start();
}
public void setBtn_play5(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_tandav_mantra);
mediaPlayer.start();
}
public void setBtn_play4(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv_om);
mediaPlayer.start();
}
public void setBtn_play3(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv);
mediaPlayer.start();
}
public void setBtn_play2(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_aaradhna);
mediaPlayer.start();
}
public void setBtn_play1(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shankar);
mediaPlayer.start();
}
private void stopPlayer(){
if(mediaPlayer != null && mediaPlayer.isPlaying())
{mediaPlayer.stop();}
}
}
I am using Android Studio. So this is the full code. I am trying to start the countdown by clicking the startButton. The plan is that the countdown is going down while I can still click the other button. The other button(incrementButton) increments. I got the increment working but the timer is not working when I click the startButton. Is there something wrong I am doing?
EDIT : Would it also be good to ask on how to cancel the background thread?
I tried using cancel(true). Changed the code
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView seconds;
TextView increment;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seconds = (TextView) findViewById(R.id.seconds);
increment = (TextView) findViewById(R.id.increment);
Button incrementButton = (Button) findViewById(R.id.incrementButton);
Button startButton = (Button) findViewById(R.id.startButton);
Button stopButton= (Button) findViewById(R.id.stopButton);
incrementButton.setOnClickListener(this);
startButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.incrementButton:
count++;
increment.setText(Integer.toString(count));
break;
case R.id.startButton:
new timerTask();
break;
case R.id.stopButton:
new timerTask().cancel(true);
break;
}
}
private void updateSeconds(final int count) {
runOnUiThread(new Runnable() {
#Override
public void run() {
seconds.setText(Integer.toString(count));
}
});
}
public class timerTask extends AsyncTask<Void, Void, Void> {
private int i;
private int savedSecond;
public timerTask() {
}
#Override
protected Void doInBackground(Void... voids) {
try {
for(i = 10; i > 0; i--){
savedSecond = i;
updateSeconds(savedSecond);
Thread.sleep(1000); //1000 = 1 seconds
if(isCancelled())
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
}
Call execute method to start AsyncTask as:
case R.id.startButton:
new timerTask().execute();
break;
case R.id.startButton:
timerTask timerTask =new timerTask(); // here you created the timer task.
timerTask.execute() //execute has to be called.
break;
I have an activity (not my main activity) that plays some sounds and draw some graphics in a runnable thread. There is an imagebutton with which I'm supposed to suspend and resume the thread. But whatever I try the thread just runs on. I'm totally stuck! Please help.
public class PlayInterval extends Activity {
private Handler customHandler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playinterval);
final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton);//Play/Pause
playPauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onPlayPauseClicked(playPauseButton,(String)playPauseButton.getTag());
}
});
customHandler = new Handler();
new Thread(new Task()).start();
}
#Override
public void onBackPressed() {
customHandler.removeCallbacksAndMessages(null);
finish();
}
class Task implements Runnable {
#Override
public void run() {
// Do really cool stuff
// and even cooler stuff
customHandler.postDelayed(this, 100);
}
}
private void onPlayPauseClicked(ImageButton playPauseButton, String status) {
if (status == "playing") {
playPauseButton.setTag("paused");
customHandler.removeCallbacksAndMessages(null); //TODO suspend here not working!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
playPauseButton.setImageResource(getResources().getIdentifier("pause_image", "drawable", getPackageName()));
} else {
playPauseButton.setImageDrawable(getDrawable(getResources().getIdentifier("pause_image", "drawable", getPackageName())));
}
} else {
playPauseButton.setTag("playing");
customHandler.postDelayed(this, 100); //TODO resume here not working!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
playPauseButton.setImageResource(getResources().getIdentifier("play_image", "drawable", getPackageName()));
} else {
playPauseButton.setImageDrawable(getDrawable(getResources().getIdentifier("play_image", "drawable", getPackageName())));
}
}
}
}
I never did get an answer so after trial and error I came up with this. I've red quite alot here on StackOverflow and what I understand this is NOT the way it is supposed to be done. But it is working very well, so if anyone could explain why one shouldn't use syncronized methods like this and provide a better answer I would be thankful.
Cheers
public class PlayInterval extends Activity {
private Handler customHandler;
Boolean isRunning;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playinterval);
final ImageButton playPauseButton = (ImageButton)findViewById(R.id.playPauseButton);//Play/Pause
playPauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onPlayPauseClicked(playPauseButton);
}
});
customHandler = new Handler();
isRunning=true;
new Thread(new Task()).start();
}
#Override
public void onBackPressed() {
customHandler.removeCallbacksAndMessages(null);
finish();
}
class Task implements Runnable {
#Override
public void run() {
if (isRunning == true){
// Do really cool stuff
// and even cooler stuff
} else {
// it is paused
}
customHandler.postDelayed(this, 100);
}
private syncronized void onPlayPauseClicked(ImageButton playPauseButton) {
if (isRunning==true) {
isRunning=false;
playPauseButton.setImageResource(getResources().getIdentifier("play_image", "drawable", getPackageName()));
} else {
isRunning=true;
playPauseButton.setImageResource(getResources().getIdentifier("pause_image", "drawable", getPackageName()));
}
}
}
I am creating a sound board and after clicking about 30 different sounds it stops working; I believe android is running out of memory. Below is my code. How can I implement .release() so that when the sound is done playing it is released? I don't really care if two things play at the same time; the clips are t0o short for this to be possible. I would just like to get my code set.
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final MediaPlayer pg1 = MediaPlayer.create(this, R.raw.peter1);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.start();
}
});
I have done a lot of searching around but due to my lack of java/android knowledge I have not been able to get anything to work. Thanks in advance, let me know if anyone needs anymore code.
I left a comment, but I'll post an answer to show what I mean anyway...
The idea is that you have a set number of MediaPlayer instances that you can use. That way you never exceed the maximum number of instances. The array should be the length of the number of concurrent sounds you expect to be able to hear. If the sounds are local files, the length of time it takes to prepare the sounds should be almost negligible, so calling create inside the click handler should not result in terrible performance. Each of your buttons is associated with a particular resource, I suppose, so I set up a helper method to create and play the sounds for each button in the same way.
public class soundPageOne extends Activity {
private MediaPlayer[] mPlayers = new MediaPlayer[2];
private int mNextPlayer = 0;
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
Button playSound1 = (Button)this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSound(R.raw.peter1);
}
});
}
public void onDestroy() {
super.onDestroy(); // <---------------------- This needed to be there
for (int i = 0; i < mPlayers.length; ++i)
if (mPlayers[i] != null)
try {
mPlayers[i].release();
mPlayers[i] = null;
}
catch (Exception ex) {
// handle...
}
}
private void startSound(int id) {
try {
if (mPlayers[mNextPlayer] != null) {
mPlayers[mNextPlayer].release();
mPlayers[mNextPlayer] = null;
}
mPlayers[mNextPlayer] = MediaPlayer.create(this, id);
mPlayers[mNextPlayer].start();
}
catch (Exception ex) {
// handle
}
finally {
++mNextPlayer;
mNextPlayer %= mPlayers.length;
}
}
}
Create a class, say AudioPlayer with a SoundPool variable. Setup a constructor to initialise the AudioPlayer object and create a Play method. SoundPool works better for short sounds played many times and does not require you to release.
public class AudioPlayer {
private SoundPool sPool = new SoundPool(Integer.MAX_VALUE, AudioManager.STREAM_MUSIC, 0);
public AudioPlayer(Context c, int id){
sounds.put("1",sPool.load(c, id, 1));
}
public void play(Context c) {
sPool.play("1", 1, 1, 1, 0, 1f);
}
}
So your class should look like
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final AudioPlayer ap = new AudioPlayer(this, R.raw.sound);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ap.play();
}
});
Could you use a MediaPlayer.OnCompletionListener?
Something like:
public class soundPageOne extends Activity implements MediaPlayer.OnCompletionListener {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final MediaPlayer pg1 = MediaPlayer.create(this, R.raw.peter1);
//***set the listener here***
pg1.setOnCompletionListener(this);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.start();
}
});
}
//***this code will be executed once the sound finishes playing***
#Override
public void onCompletion(MediaPlayer mp) {
//log messages, other things can go here
mp.release();
}
Try something like this
Your activity class:
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final AudioPlayer pg1 = new AudioPlayer();
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.play(this, R.raw.sound);
}
});
}
This is another Java Class:
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public void play(Context c, int sound) {
stop();
mPlayer = MediaPlayer.create(c, sound);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
public boolean isPlaying() {
return mPlayer != null;
}
}