سؤال

I want the code shown here to run all the time:

class secondClass extends TimerTask {

    MediaPlayer mp;

    public void onCreate(Context context) {
        mp = MediaPlayer.create(context, R.raw.flyinghome);
    }

    public void run() {
        float x = (float) Math.random();
        float y = (float) Math.random();
        mp.setVolume(x, y);
    }

    public static void main(String[] args) {  
        secondClass task = new secondClass();  
        Timer timer = new Timer();          
        timer.scheduleAtFixedRate(task, 0, 2000);           
    }  
}

How can I have this TimerTask running a the same time as the MainActivity class if The MainActivity class extends Activity and implements OnCLickListener.

هل كانت مفيدة؟

المحلول

As you can read here

Each timer has one thread on which tasks are executed sequentially.

You can schedule a task to run inside that thread, using one of the schedulling functions, such as:

Timer t = new Timer();

t.schedule(new secondClass(), delay);
//delay is the amount of time in milliseconds before execution.

since you want it to run all the time, you can consider to use schedule(java.util.TimerTask, long, long) that schedules a task for repeated fixed-delay execution after a specific delay.

Timer t = new Timer();

t.schedule(new secondClass(),  delay,period);
//delay is the amount of time in milliseconds before execution.
//period    amount of time in milliseconds between subsequent executions.

An advice: i would change the class name to SecondClass, since the class names use to be capitaliced.

نصائح أخرى

You could also consider using an Android service.

https://developer.android.com/reference/android/app/Service.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top