正在创建一个简单的应用程序。应用程序必须显示对话框,在后台运行计时器。当计时器过去时,应该发出哔声。但是,如果在计时器之前单击对话框,则应取消计时器。我发布了迄今为止我所做的事情,用这段代码,先得到蜂鸣声然后再对话框,怎么说主线程计时器已经完成?
public class main扩展Activity {
static final int DIALOG_ADDPLAYERS = 0;
Thread backgroundThread;
TextView myText;
myCounter counter;
MediaPlayer mp;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg)
{
playAudio();
}
};
protected Dialog onCreateDialog(int id)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch(id)
{
case 0:
builder.setTitle("Restart Game");
builder.setMessage("Are you sure to restart the game?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
counter.cancel();
}});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
counter.cancel();
}
});
break;
default:
}
return builder.create();
}
void playAudio()
{
mp = MediaPlayer.create(this, R.raw.beep);
mp.setLooping(false);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer arg0)
{
finish();
}
});
mp.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer arg0)
{
finish();
}});
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (mp!=null)
{
mp.release();
mp=null;
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.mytext);
//Toast.makeText(this, "onCreate()", Toast.LENGTH_LONG).show();
showDialog(0);
startMyTimer();
}
protected void startMyTimer()
{
counter = new myCounter((long)10000,(long)1000);
backgroundThread = new Thread(new Runnable(){
@Override
public void run()
{
try
{
//Thread.sleep(10000);
counter.startTimer();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
backgroundThread.start();
}
}
这是我的MyCounter课程:
package com.androidbook.bgthread;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.CountDownTimer;
public class myCounter extends CountDownTimer
{
public myCounter(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
@Override
public void onFinish()
{
}
@Override
public void onTick(long millisUntilFinished)
{
}
public void startTimer()
{
start();
}
}
这是正确的方法吗?请帮忙。
答案 0 :(得分:1)
使用处理程序:http://developer.android.com/reference/android/os/Handler.html。这使您可以从任何其他线程向主线程发送消息。
有用的参考资料位于http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html