首页 > 解决方案 > 如何在后台运行的倒数计时器上继续更新 texview?

问题描述

我有这个倒数计时器,我修改它来计数。计时器将继续运行,同时在文本视图(tvp)上给出百分比。下面是代码。

   timer = new CountUpTimer(date3) {
        public void onTick(int secondt) {
            simpleDateFormat = new SimpleDateFormat ("HH:mm:ss");
            tv_timer.setText(simpleDateFormat.format (secondt));
            t1 = date3 - date;
            percentage = Math.round (secondt/t1 *100);
            tvp.setText ( percentage+"%" );

        }
    };timer.start();

计时器在后台运行,我使用服务和广播接收器,它工作得很好。问题是,百分比文本视图没有更新和运行,并且在按下后退按钮后停留在最后一个值上。下面是用于更新百分比文本视图的可运行代码。

  getActivity ().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            tvp.setText ( percentage + "%" );
        }
    });

以下是我的计时器服务代码

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

@Override
public void onCreate() {

    super.onCreate();

    mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mEditor = mpref.edit();

    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
    intent = new Intent(str_receiver);


}

class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        mHandler.post( () -> {
            timerprogressupdate ();
        } );
    }

}

public String timerprogressupdate() {

    fn_update ( IFTimer.secondt );
    fn_updatep ( IFTimer.percentage );

    return timerprogressupdate();
}


@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("Service finish","Finish");


}

private void fn_update(long str_time){

    intent.putExtra("time",str_time);
    sendBroadcast(intent);
}

}

广播接收器

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String strDate = intent.getStringExtra("time");

    }
};

按下后退按钮后,我需要更新和运行百分比文本视图。有人对此有解决方案吗?如果有人可以帮助我,我将不胜感激。

标签: androidtextviewupdating

解决方案


推荐阅读