Android: Simple how to stop mediaplayer after given time - android

I am trying to play an mp3 file (with an onClickListener) and stop after 2 seconds. I tried the code below but it is not working. Could anyone please help?
final MediaPlayer mpsound = MediaPlayer.create(this, R.raw.media_player_sound);
ImageView sound = (ImageView) findViewById(R.id.button);
sound.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mpsound.start();{
sleep(2000);
mpsound.stop();
}
}
});

Why are you calling stop() on mpfrog if you are playing audio with mpsound? You need to call the stop() function on the mpsound MediaPlayer. Also, you might want to add the #Override annotation to your onClick() method.
for the override...
sound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mpsound.start();{
sleep(2000);
mpsound.stop();
}
}
});
for a timer.....
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg){
mpsound.stop();
}
};
//Task for timer to execute when time expires
class SleepTask extends TimerTask {
#Override
public void run(){
handler.sendEmptyMessage(0);
}
}
//then in some other function...
Timer timer = new Timer("timer",true);
timer.schedule(new SleepTask(),2000);

You have to wait 2 seconds in different thread, for this case use your own created thread and wait there and stop player, or you can use CountDownTimer - very simple solution.
You can find same question aggregated here and here
In eclipse you can use autocomplete (ctrl + space by default) to fill automatically all inmplemented methods and #Overrides will already be there.

Related

Android Button click Handler

I have a button(in say Activity 1), which when clicked should start a service (eg Service 1). But there must be a delay of 5 seconds before the service starts. I achieved this using SystemClock.sleep(5000) in the onStartCommand of the service. This worked properly.
Now I want to add the functionality that if the button is clicked again(even before the 5 seconds end), the service WILL NOT BE STARTED.
Any ideas how to do this?
(Edit : Please read the entire question before marking it as a duplicate. Thanks)
You can use handler with post delayed to achieve your goal. Make your button disable and enable it after five seconds along with starting your service. You can implement the following code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//start your service here
button.setEnabled(true);
}
}, 5000);
}
});
Above code will disable your button for 5 second and will start your service after 5 second.
I'd use a util class similar to the following. Pass it in a runnable and a delay in ms and you can call stop() on it to cancel before it has run. You can also call restart() if you want to restart your timer. I use it for things like auto showing/hiding controls on an immersive view.
public class DelayableRunnable{
int mDelay = 0;
Handler mHandler = new Handler();
Runnable mRunnable;
boolean mIsRunning = false;
public DelayableRunnable(Runnable runnable, int delay){
mRunnable = runnable;
mDelay = delay;
}
public void setNewDelay(int delay){
mDelay = delay;
}
public void start(){
if(mIsRunning) {
stop();
}
mHandler.postDelayed(mRunnable, mDelay);
mIsRunning = true;
}
public void stop(){
mHandler.removeCallbacks(mRunnable);
mIsRunning = false;
}
public void restart(){
stop();
start();
}
}
You can use Handler.postDelayed function for delayed actions in Android enviroment (better than plan java methods)
final Handler handler = new Handler(); // or use existed one your_view.getHandler()
handler.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
Or simpler use you view function (work same as above):
your_view.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals void schedule (TimerTask task,long delay) Schedules the specified task for execution after the specified delay.
new Timer().schedule(new TimerTask() {
#Override
public void run() {
alertDialog.dismiss();
startActivity(new Intent(****.this,*********.class));
}
},5000);

Handler does not run after specified time

I am trying to restart the same Activity after a specific time say after 2 min when a button is clicked. However, it does close the activity, however does not launch in the specified time , here is the code:
public void snoozeup(View view)
{
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run()
{
//start your activity here
startActivity(new Intent(Time_Date.this, Time_Date.class));
}
}, a); //where a is integer with value 120000
mp.stop();
mp.release();
voicePlayer.stop();
voicePlayer.release();
songPlayer.stop();
songPlayer.release();
this.finish();
}
You can't do it in that way - once your Activity is finished, all UI threads are stopped. Your Runnable will never be called.
If you want some functionality to run when your Activity is closed, you need to create a Service.
You should also take note of the problems with using postDelayed as described in postDelayed() in a Service.
I fixed it by using:
public void snoozeup(View view)
{
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run()
{
startActivity(new Intent(Time_Date.this, Time_Date.class));
}
};
handler.postDelayed(x, 6000);
mp.stop();
mp.release();
voicePlayer.stop();
voicePlayer.release();
songPlayer.stop();
songPlayer.release();
finish();
}

How can I wait for a period of time after a button is clicked?

So I have an activity which runs a simple snakes and ladders game, and I want to allow the player to click a button and move, which would subsequently be followed by the computer moving. My problem is, that once the player moves, the computer immediately makes its move.
Instead I want the activity to wait before the computer makes its move. I've looked around a lot and found that waiting involves using a thread, but I have failed to implement it without my app crashing
My attempt at declaring a thread:
final Runnable runnable = new Runnable() {
#Override
public void run()
{
while (true)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Thread thread= new Thread(runnable);
My onClick() method for the button:
Button rollButton = (Button) (findViewById(R.id.rollButton));
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//executes only if current player is a human
if(GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie(); // rolls the die
showDie(GAME_BOARD); // displays die on screen
GAME_BOARD.move(); // moves the player and sets next player as current player
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");// sets TextView to display who's player's turn it is
thread.start();
if(!GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie();
showDie(GAME_BOARD);
GAME_BOARD.move();
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");
}
}
}
});
So again, my question is, how do I make it so that before the second if statement executes, the activity waits, say 4 seconds?
you can use an Handler.postDeleayed. You have to provide a Runnable to execut and the delay period in milliseconds. The Runnable will be executed on the UI Thread
You can use Handle to post your task defined in runnable after some delay
use this
Inside Activity define
Handler hand = new Handler();
and define your task in runnable like this
Runnable run = new Runnable() {
#Override
public void run() {
**your Task here.......**
}
};
In on click event
btnStartShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
hand.postDelayed(run,3000); // For delay three seconds
}
});
also remove all pending messages by calling following sentence at appropriate place
hand.removeCallbacksAndMessages(null);
Use a CountDownTimer:
CountDownTimer timer = new CountDownTimer(4000, 1000) {
#Override
public void onFinish() {
*function containing the second statement*
}
#Override
public void onTick(long millisLeft) {
// not ticking
}
};
and in the onClick method in the click listener use:
timer.start();
Try the following,
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Runnable runnable = new Runnable() {
#Override
public void run() {
// whatever you would like to implement when or after clicking rollButton
}
};
rollButton.postDelayed(runnable, 5000); //Delay for 5 seconds to show the result
}

update text constantly through for() loop and Handler

I am working on a Testing Project for me , just so I could learn more , so now I need to update the text of a TextView constantly every 250 milliseconds through a for(;;) loop , it happens after a Button click ... My problem is that whenever I press that button my app freezes (Yes my button is totally working , verified through previous testings) , I am using a handler to the Main thread doesn't get affected while the Runnable is up ... Here is my code of the Button and Handler ...
final Handler handler = new Handler();
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(;;){
String a = Shells.sendSingleCommand("free");//Here I send a command "free" and it returns its output
text.setText(a);//text is my TextView which is used through my experimentations ...
synchronized(this){
try{
wait(250);
}catch(Exception e){
}
}
}
}
});
}
});
If you need anymore info ask please :)
use handler.postDelayed for updating textview constantly every 250 milliseconds instead of using for loop to avoid freeze current Activity as :
Handler handler=new Handler();
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.post(runnable);
}
});
Runnable runnable=new Runnable(){
#Override
public void run() {
String a = Shells.sendSingleCommand("free");
text.setText(a);
handler.postDelayed(runnable, 250);
}
};
Android doesnt allow you to do long tasks in the main thread. If you need to do something like this I recommend moving the for loop and depdendent code into a separate thread..

Countdown playing Alarm

I really hope you can help me here. Below is a section of my code that successfully runs two count down timers side by side...all I want to do is play a short mp3 file when count down has finished....I have tried many different bits of code but I am struggling to make anything work...an quick wins would be good..
So to round up two timers each need to play sound when finished..
//Declare Start/Stop button
Button btnstart = (Button)findViewById(R.id.btnstart);
Button Button1 = (Button)findViewById(R.id.Button01);
final TextView mCounter1TextField=(TextView)findViewById(R.id.counter1);
final TextView mCounter2TextField=(TextView)findViewById(R.id.counter2);
//Counter 1
final CountDownTimer Counter1 = new CountDownTimer(9000000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter1TextField.setText(" " + formatTime(millisUntilFinished));
}
public void onFinish() {
start();
}
};
//Counter 2
final CountDownTimer counter2 = new CountDownTimer(9000000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter2TextField.setText(" " + formatTime(millisUntilFinished));
}
public void onFinish() {
start();
}
};
//Start Button1
btnstart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Counter1.start();
}
});
//Start Button2
Button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
counter2.start();
Thanks in advance
Dj
I assume start() is the function you call to play the sound, right ?
so inside the definition of start(), put the following code :
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound); //replace 'sound' by your music/sound
mp.start();
Hope this helps!
Edit: trying to be super clear :)
Somewhere in your code, it is written :
public void onFinish() {
start();
}
This method/function is called when the counter finishes.
Inside this function it is written 'start()'
I don't know what this start() does.
In both cases, I suggest you keep it (if it doesn't create an error), and after start(), add playSound() inside the two onFinish() methods.
and then write OUTSIDE of this function, the following:
public void playSound() {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound); //replace 'sound' by your music/sound
mp.start();
}

Categories

Resources