首页 > 解决方案 > 服务中的计时器

问题描述

我有一个记录工作时间的应用程序,我的意思是计算工作时间,我使用计时器来运行时间。由于工作长达 9 小时,因此用户无法长时间打开应用程序。为此,我正在使用指示时间的服务。因为我不能使用 Chronometer 因为

Chronometer 是 Android 中的一个 UI 小部件(实际上是一个 TextView)。所以,我不能将它用于非 UI 目的。所以我必须使用计时器来完成这项工作。但我不知道我怎样才能做到这一点。任何代码或帮助表示赞赏。谢谢

当我点击开始按钮时,计时器会像这样开始 ,我的服务也开始了,但我得到的时间是 00:00:00 像这样

我只希望计时器应该在服务中运行,我可以看到服务时间,我不想处理或使用服务中运行的时间,服务时间将向用户显示他们在工作上花费了多少时间.

服务等级

public class ServiceTimer extends Service {

   // Chronometer chronometer ;
    //String valueOfTime ;
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String input = intent.getStringExtra("inputExtra");

        // chronometer = new Chronometer(this);
        //chronometer.setText("00:00:00");
        //chronometer.setOnChronometerTickListener(new //Chronometer.OnChronometerTickListener() {

  //              @Override
//            public void onChronometerTick(Chronometer chronometer) {
  //              CharSequence text = chronometer.getText();
    //            if (text.length()  == 5) {
      //              chronometer.setText("00:"+text);
        //        } else if (text.length() == 7) {
          //          chronometer.setText("0"+text);
            //    }
            //}
   //         });





 //       chronometer.start();
    //before i know about chronometer that i cannot use it in service 
// this is what i have so for with chronometer to achieve 
// but failed ...
        Intent notificationIntent = new Intent(this, Timer_FullTime.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);



        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(chronometer.getText().toString())
                .setSmallIcon(R.mipmap.logoback)
                .setContentText(input)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);

        //do heavy work on a background thread
        //stopSelf();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

更新 这就是我如何得到我想要或在问题中提出的问题

public class ServiceTimer extends Service {

    private   int THE_ID_TO_UPDATE = 1;
    private static Timer timer = new Timer();
    private Context ctx;
    private int second = 0 ;
    NotificationManager notificationManager ;
    private int minute = 0 ;
    private int hour = 0 ;

    //we are going to use a handler to be able to run in our TimerTask
    final Handler handler = new Handler();
    NotificationCompat.Builder notification ;
    @Override
    public void onCreate() {
        super.onCreate();
        super.onCreate();
        ctx = this;
    }


    private class mainTask extends TimerTask
    {
        public void run()
        {

            second = second + 1 ;

            if (second == 60){
                minute++ ;
                second = 0 ;
            }

            if (minute == 60){
                hour++;
                minute = 0 ;
                second = 0 ;

            }


            notification.setContentText( hour + "h " + minute + "m " + second+"s");



            notificationManager.notify(THE_ID_TO_UPDATE , notification.build());


        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {



        String input = intent.getStringExtra("inputExtra");

        Intent notificationIntent = new Intent(this, Timer_FullTime.class) ;
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0) ;



        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notification = new NotificationCompat.Builder(this, CHANNEL_ID);


        notification.setContentTitle(input);
        notification.setSmallIcon(R.mipmap.logoback);
        notification.setOnlyAlertOnce(true);
        notification.setWhen(System.currentTimeMillis());

        notification.setContentIntent(pendingIntent);
        notification.setLights(Color.RED, 1000, 1000);
        notification.setVibrate(new long[]{0, 400, 250, 400});
        notification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

        notification.build();
        notificationManager.notify(THE_ID_TO_UPDATE , notification.build());
        startForeground(THE_ID_TO_UPDATE, notification.build());

        timer.scheduleAtFixedRate(new mainTask(), 0, 1000);



        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

标签: javaandroid

解决方案


您可以尝试将 aTimer与 a 一起使用TimerTask

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        // Update your counter/notification each second
    }

}, 0, 1000);

官方文档链接:https ://developer.android.com/reference/java/util/Timer


推荐阅读