计时表保持在后台花费的时间

Chronometer keep in background time spent

我会在我的应用程序中开发一项功能,当单击我的 activity 上的按钮时,会启动一个 service 来启动、暂停和恢复 Chronometer。 但是我有一个问题如何在我的后台启动和停止 service

我创建了我的 Activity

public class StartWorkActivity extends ActivityGeneralToolbar {

    protected final void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState, R.layout.activity_start_work);
        Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer);



    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void startWork(View v){
        Intent msgIntent = new Intent(StartWorkActivity.this, WorkTimerService.class);


        msgIntent.setAction("START_TIMER");
        getBaseContext().startService(msgIntent);
    }

    public void pauseWork(View v){
        Intent msgIntent = new Intent(StartWorkActivity.this, WorkTimerService.class);
        msgIntent.setAction("PAUSE_TIMER");

    }

    public void resumeWork(View v){
       //call service
        Intent msgIntent = new Intent(StartWorkActivity.this, WorkTimerService.class);
        msgIntent.setAction("RESUME_TIMER");


    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {

        super.onResume();
    }
}

还有我的 WorkTimerService

public class WorkTimerService extends IntentService {

    long timeWhenStopped = 0;
    Chronometer chronometer;

    public WorkTimerService() {
        super("SystemService");

    }

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

    @Override
    protected void onHandleIntent(Intent intent) {
        if(intent.getAction() == "START_TIMER"){
            startWork();
        }
        if(intent.getAction() == "PAUSE_TIMER"){
            pauseWork();

        }if(intent.getAction() == "RESUME_TIMER"){
            resumeWork();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags,startId);

        return START_STICKY;
    }
    public void pauseWork(){

        timeWhenStopped = chronometer.getBase() -  SystemClock.elapsedRealtime();
        chronometer.stop();
    }

    public void resumeWork(){

        chronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
        timeWhenStopped = 0;
        chronometer.start();

    }

    public void startWork(){

        chronometer.start();
    }
}

但我的问题是 Chronometer 在我的服务中显然是空的,因为我读到那是不可能的,在服务中,与 ui 交互。 那么,我如何在后台发送或使用 Chronometer

Chronometer 是 Android 中的 UI 小部件(实际上是 TextView)。因此,您不能将其用于非 UI 目的。尝试使用 TimerCountDownTimer 代替。

查看 TimerService 中的示例用法: