我想在我的应用程序做什么:1.当用户打开应用程序时,他将能够看到一个已经运行的倒计时。 因此,在这种情况下,我想在一个TextView,将随时更新每秒显示的倒计时数字。 2.用户将能够阻止它。 3.用户可以离开应用程序,但倒数还是应该继续下去,并显示更新的时候,他回来给应用程序UI。
因此,基于以上几点,我明白我需要实现服务,它在后台工作。 我看了这个链接,但我的问题是与实现。 我很为丢失如何实现这种方式。 话虽这么说,我也不能一旦用户回来到应用程序想办法,以显示在UI的时间。 我也看到了这个链接为好,但我不知道如果只实施CountDownTimer使得正在运行的服务。 所以,我应该如何进行,实现它? 到特定的教程的任何链接/码被理解。 谢谢。
更新:我到目前为止已经能够做到以下几点:MainActivity.java
public class MainActivity extends Activity {
Button btnStart,btnStop;
Intent serviceIntent;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
tv = (TextView) findViewById(R.id.timeView);
//final MyCounter timer = new MyCounter(100000,1000);
//tv.setText("100");
//timer.start();
serviceIntent = new Intent(MainActivity.this,MyService.class);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(serviceIntent);
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(serviceIntent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
MyService.java:
public class MyService extends Service {
MyCounter timer;
@Override
public void onCreate() {
// TODO Auto-generated method stub
timer = new MyCounter(100000,1000);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
timer.start();
return super.onStartCommand(intent, flags, startId);
}
private class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "death", Toast.LENGTH_LONG).show();
stopSelf();
}
@Override
public void onTick(long millisUntilFinished) {
Toast.makeText(getApplicationContext(), (millisUntilFinished/1000)+"", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
timer.cancel();
//stopSelf();
super.onDestroy();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
问题是:1。我不知道如何从这个吐司除了显示对在MainActivity UI倒计时。 2.它不会停止,当我按下停止按钮计数。