Search code examples
javaandroidtimerdelaycountdowntimer

How would I set a delay on a toggle button based on the number entered into a number field?


I'm trying to make a toggle button play a song but on a delay. The user has to enter the minutes into a number field (Palette/Text Fields/Number), which will be used to set the delay. I've checked the android developer resources and I still have no idea where to start.

Currently I have this:

public class Main extends Activity {

MediaPlayer mp;
Button startButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    mp = MediaPlayer.create(getBaseContext(), R.raw.songthingy);

    ToggleButton toggle = (ToggleButton) findViewById(R.id.ToggleButton);
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            if (isChecked) {
                mp.start();
            } else {
                mp.stop();
            }
        }
    });

    mp.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.release();
        }
    });

}

Solution

  • A great method is Handler.postDelay. You have to make your action a Runnable, and pass it in the params of them method. Then it will execute after the given time.

    Update:

       private Runnable doStuff= new Runnable() {
    //Notice doStuff is a member of the class.
                public void run() {
                   //do awesome stuff here.
                 mp.start();
                }
            };
    //...
     toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                 final Handler mHandler= new Handler();
                    mHandler.postDelayed(doStuff,1000*30);//30 second delay.
                } else {
                    mp.stop();
                }
            }
    

    You can Google around and see examples on how to use this. Your code may look very something like this but this code won't run out of the box. You have to fix scopes and meet your requirments.