我正在创建一个使用CountDownTimer的应用。 我想使用Service方法在后台正确使用CountDownTimer。
但是,在我的代码实现中,它无法正常工作。
服务不会在Toast中显示文本,也不会向活动发送正确的意图。 我应该在MyService类中使用CountDownTimer的这段代码吗? 有人可以帮我这个吗?
这是 MainActivity.java
public class MainActivity extends ActionBarActivity {
Button btnStart, btnStop;
TextView textViewTime;
@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);
textViewTime = (TextView) findViewById(R.id.textViewTime);
textViewTime.setText("00:01:30");
final CounterClass timer = new CounterClass(90000, 1000);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.start();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
}
});
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
textViewTime.setText(hms);
}
@Override
public void onFinish() {
textViewTime.setText("Completed.");
}
}
public void startService(View view)
{
Intent intent = new Intent(this,MyService.class);
startService(intent);
}
public void stopService(View view)
{
Intent intent = new Intent(this,MyService.class);
stopService(intent);
}
}
这是 MyService.java
public class MyService extends Service {
@Override
public void onCreate() { // initial performance (setup service in this method)
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { // create start a service
Toast.makeText(this,"Service Started...",Toast.LENGTH_LONG).show();
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() { // stop a service
Toast.makeText(this,"Service Destroyed...", Toast.LENGTH_LONG).show();
//super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
答案 0 :(得分:0)
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(v);
timer.start();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(v);
timer.cancel();
}
});
}