我希望这里显示的代码一直运行:
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);
}
}如果TimerTask类扩展了活动并实现了OnCLickListener,那么如何让这个MainActivity类与MainActivity类同时运行。
发布于 2014-01-30 01:15:46
因为你能读到这里
每个定时器都有一个线程,在其上依次执行任务。
可以使用调度函数之一调度在该线程中运行的任务,例如:
Timer t = new Timer();
t.schedule(new secondClass(), delay);
//delay is the amount of time in milliseconds before execution.由于您希望它一直运行,所以可以考虑使用时间表(java.util.TimerTask,长,长)来调度任务,以便在特定延迟之后重复执行固定延迟。
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.建议:我会将类名更改为SecondClass,因为类名使用大写。
发布于 2014-01-30 18:26:33
您也可以考虑使用Android服务。
https://developer.android.com/reference/android/app/Service.html
https://stackoverflow.com/questions/21445941
复制相似问题