我想在倒数计时器中做一个后台应用程序,也就是说,如果我开始 计时器并从该应用程序中出来,然后转到另一个应用程序 回到同一个倒计时应用程序。我希望那个计时器是 一直跑到我停下来。我知道其中涉及的方法,但我不确定 关于其中使用的线程概念。
//MyActivity.class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyappActivity extends Activity
{
private static final String Tag = "Background_Timer";
private Button start;
private Button stop;
private TextView tv;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.button);
stop = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.text1);
this.runOnUiThread(new Runnable()
{
public void run()
{
tv.setText(MyAppService.seconds + " Seconds Left");
}
});
}
public void onClick(View src)
{
switch (src.getId())
{
case R.id.button:
Log.e(Tag, "onClick: starting service");
startService(new Intent(this, MyAppService.class));
break;
case R.id.button1:
Log.e(Tag, "onClick: stopping service");
stopService(new Intent(this, MyAppService.class));
break;
}
}
}
//MyService.class
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;
public class MyAppService extends Service
{
private static final String TAG = "My Service";
private static boolean state;
private static TextView TextTimer;
public static String seconds;
MyThread mt = new MyThread();
@Override
public void onCreate()
{
CountDownTimer Myapp = new CountDownTimer(50000, 1000)
{
public void onTick(long millisUntilFinished)
{
TextTimer.setText("Seconds left: " + (millisUntilFinished)
/ 1000);
}
public void onFinish()
{
TextTimer.setText("Finished!");
}
};
}
public void onStart(Intent intent, int startid)
{
Log.d(TAG, "on-Start");
mt.start();
}
public void onDestroy()
{
Log.d(TAG, "on-Stop");
mt.stop();
}
public static class MyThread extends Thread
{
public void run()
{
try
{
while (state = true)
{
MyThread.sleep(500);
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
}
最佳答案
在您的 Activity 中有一个静态处理程序来接收您的 Tick 和 Finish 消息
在服务中有一个启动倒计时的线程,这样您的倒计时将在您的线程而不是主线程中工作。
关于java - 如何使用线程概念在倒数计时器中运行后台应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9176545/