Question

I want to make one dialog displaying the timer. Every one second timer value will increase. In every moment user can click ok and close the dialog.

The dialog itself is not the problem. But how to create timer which will execute the given procedure every one second? And moreover it will "not explode (=will not cause problems)" after the user closes the dialog (then dialog object will not exist so the handler procedure should be able to detect such a situation and instead of displaying new timer value, it should stop timer.

Thanks in advance for help.

Was it helpful?

Solution

I code a sample but I am not sure if it is what you are looking for:

public class TimerDialog extends DialogFragment {

    private static final String TIME = "sec";

    private TextView mTime;
    private TimerTask mTimerTask;
    private long mSec;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setTitle("Timer");
        alert.setPositiveButton("OK", null);

        View view = View.inflate(getActivity(), R.layout.timer_dialog, null);
        mTime = (TextView) view.findViewById(R.id.time);

        alert.setView(view);
        return alert.create();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            mSec = savedInstanceState.getLong(TIME);
            mTime.setText(String.valueOf(mSec));
        }
        startTimer();
    }

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(TIME, mSec);
    }

    private void startTimer() {
        Timer t = new Timer();

        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                mSec++;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTime.setText(String.valueOf(mSec));
                    }
                });
            }
        };

        t.scheduleAtFixedRate(mTimerTask, 1000, 1000);
    }

    private void stopTimer() {
        mTimerTask.cancel();
    }
}

and timer_dialog:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/time"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="0"
    android:gravity="center" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top