我是android编程的新手..
我的活动中有一个媒体播放器播放声音。
我想在播放媒体播放器的特殊时间做一些代码。我的意思是我想在媒体播放器中执行code1 0到5秒,在5到14期间执行code2,在14到18秒内执行code3。
这是我的计时器代码,我不知道如何在特殊时间运行我的代码..
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView timerTextView;
long startTime = 0;
//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
Button b = (Button) findViewById(R.id.button1);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
@Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button1);
b.setText("start");
}
}
答案 0 :(得分:1)
这不是最优雅的解决方案,特别是如果您所有的时间块相隔5秒,但如果您在媒体播放器启动时设置了initalTime,它应该可以工作。有关uptimeMillis()和其他Android计时器方法的更多文档是linked here
int initialTime= SystemTimer.uptimeMillis();
while (mediaIsRunning){
int currentTime=SystemTimer.uptimeMillis();
int elapsed=currentTime-initialTime;
if (elapsed<=5000){ // 5 seconds
//your code 1
}
else if (elapsed<=10000){ //10 seconds
//code 2
}
//etc ...
}