سؤال

I have created a Timer through Stopwatch class and implement it successfully in activity. But i want to continue the timer after closing the application, so i used Service and put the method inside this. Something like below:

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 is the TextView in which I want to show my effort time. I think binding service or broadcastreceiver will help here. Implement many ways but not succeed yet.

All helps and suggestions are mostly appreciable.

Thanks

هل كانت مفيدة؟

المحلول

LocalBroadcastManager will be the simplest solution in your case.

In your MyService you'll need this code:

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

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

While in your Activity you'll have:

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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top