【发布时间】:2016-01-18 11:09:44
【问题描述】:
我不确定在哪里/如何运行此服务以在后台运行。 我开发了使用 CountDownTimer 的应用程序。 我发现我应该在 Service.class 中创建一个 CountDownTimer,并在 MainActivity.class 中运行一个 Service.class。
为什么 TextView 不显示在我的屏幕上?我把它放在 OnCreate 和 onStartCommand 中。接下来我尝试在 MainActivity 中运行它,但没有成功。
我仍然尝试实现我的代码以在后台正常工作这个 CountDownTimer。在 Android 官方网站上,我看到他们使用“Log.i”命令来运行这个 Foreground 方法。如何在我的代码中使用它?我应该在 Service.class 中添加这个吗?
下面是我的代码:
MainActivity:
Button btnStart, btnStop;
TextView textViewTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
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);
}
我的服务:
Button btnStart, btnStop;
TextView textViewTime;
public String hms;
@Override
public void onCreate() {
btnStart = (Button) btnStart.findViewById(R.id.btnStart);
btnStop = (Button) btnStop.findViewById(R.id.btnStop);
textViewTime = (TextView) textViewTime.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) {
//startService(v);
timer.start();
}
});
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { // create start a service
textViewTime.setText("00:01:30");
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
// timer.start();
//return START_STICKY; // return integer value
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) { // it's not needed but we must override this method
return null;
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
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.");
}
}
【问题讨论】:
标签: java android android-studio service countdowntimer