在具有“暂停”和“恢复”选项的后台服务中,在TextView中设置运行计时器

时间:2013-12-24 11:39:42

标签: java android service broadcastreceiver timertask

我已经通过Stopwatch class创建了一个Timer,并在活动中成功实现了它。 但我想在关闭应用程序后继续计时器,所以我使用了Service并将方法放在其中。如下所示:

MyService.java:

    Stopwatch stopwatch = Stopwatch.createStarted();
    String workingTime1 = "";

    void startThreadUpdateTimer() {
    final DecimalFormat format = new DecimalFormat("00");
    Timer T = new Timer();
    T.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    workingTime1 = "Your effort is "
                            + format.format(Double.valueOf(stopwatch
                                    .elapsed(TimeUnit.HOURS)))
                            + ":"
                            + format.format(Double.valueOf(stopwatch
                                    .elapsed(TimeUnit.MINUTES)))
                            + ":"
                            + format.format(Double.valueOf(stopwatch
                                    .elapsed(TimeUnit.SECONDS)))
                            + " till now for the day";

                    SwipePage.efforttimer.setText(workingTime1);
                }
            });
        }
    }, 1000, 1000);

}

void runOnUiThread(Runnable runnable) {
    handler.post(runnable);
}

efforttimer 是TextView,我想在其中展示我的努力时间。我认为绑定服务或广播接收器将在这里提供帮助。实施多种方式但尚未成功。

所有帮助和建议都非常明显。

由于

1 个答案:

答案 0 :(得分:1)

LocalBroadcastManager将是您案例中最简单的解决方案。

MyService中,您需要此代码:

public class MyService extends Service {
    public static final String ACTION_UPDATE = "MyServiceACTION_UPDATE";
    ...

    private void updateEmitterMethod() {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(ACTION_UPDATE));
    }
}

在您的活动中,您将拥有:

private BroadcastReceiver mMyServiceUpdateReciever;
...

@Override
public void onResume() {
    super.onResume();
    mMyServiceUpdateReciever = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                onUpdateMethod();
            }
        };
    LocalBroadcastManager.getInstance(this).registerReceiver(mMyServiceUpdateReciever, new IntentFilter(MyService.ACTION_UPDATE));
}

@Override
public void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyServiceUpdateReciever);
}