首页 > 解决方案 > 带有 Handler 和 SharedPreference 的计时器

问题描述

现在,我尝试使用处理程序和 sharedpreferences 来制作计时器。

今天我遇到了共享首选项的问题。

问题是可以按下开始按钮并转到后台然后重新启动此应用程序,该应用程序正常工作。

但是,如果我尝试两次模式(按下开始按钮 -> 背景 -> 应用程序 -> 背景 -> 应用程序),则显示时间的文本视图变为零......我不知道是什么问题……

这是代码..

private Button mStartBtn, mStopBtn, mRecordBtn, mPauseBtn;
private TextView mTimeTextView, mRecordTextView;
private Thread timeThread = null;
private Boolean isRunning = false;
ArrayList<String> record = new ArrayList<>();
Boolean timeThreadd = false;
long i;
long mEndTime;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stop_watch);
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setStatusBarColor(Color.parseColor("#4ea1d3"));
    }

    mStartBtn = (Button) findViewById(R.id.btn_start);
    mStopBtn = (Button) findViewById(R.id.btn_stop);
    mRecordBtn = (Button) findViewById(R.id.btn_record);
    mPauseBtn = (Button) findViewById(R.id.btn_pause);
    mTimeTextView = (TextView) findViewById(R.id.timeView);
    mRecordTextView = (TextView) findViewById(R.id.recordView);

    mStartBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.setVisibility(View.GONE);
            mStopBtn.setVisibility(View.VISIBLE);
            mRecordBtn.setVisibility(View.VISIBLE);
            mPauseBtn.setVisibility(View.VISIBLE);
            if (isRunning != true) {
                isRunning = true;
            }// start 가 true 일때만 실행된다.

            timeThread = new Thread(new timeThread());

            timeThread.start();

        }
    });

    mStopBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.setVisibility(View.GONE);
            mRecordBtn.setVisibility(View.GONE);
            mStartBtn.setVisibility(View.VISIBLE);
            mPauseBtn.setVisibility(View.GONE);

            mRecordTextView.setText("");
            mTimeTextView.setText("00:00:00:00");
            timeThread.interrupt();
            i = 0;
            mEndTime = 0;
            timeThreadd = false;
            isRunning = false;
            if (record.size() > 1) {
                for (int i = 0; i < record.size(); i++) {
                    record.remove(i);
                }
            }

            SharedPreferences sharedPreferences = getSharedPreferences("timer", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.clear();
            editor.apply();


        }
    });

    mRecordBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            record.add(mTimeTextView.getText().toString());
            mRecordTextView.setText(mRecordTextView.getText() + mTimeTextView.getText().toString() + "\n");
        }// 앞에 mRecordTextView.getText()은 n번이상 저장할때 첫번째 값을 n-1번째 라인에 놓고
    });  // n번째 저장한것을 n번째 놓기 위해서 설정

    mPauseBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            isRunning = !isRunning;
            if (isRunning) {

                mPauseBtn.setText("PAUSE");
            } else {
                mPauseBtn.setText("PAUSE");

            }
        }

    });
}


@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        int mSec = msg.arg1 % 100;
        int sec = (msg.arg1 / 100) % 60;
        int min = (msg.arg1 / 100) / 60;
        int hour = (msg.arg1 / 100) / 360;
        //1000 = 1 sec, 1000*60 = 1 min, 1000*60*10 = 10min 1000*60*60 = 1 hour

        @SuppressLint("DefaultLocale")
        String result = String.format(Locale.getDefault(), "%02d:%02d:%02d:%02d", hour, min, sec, mSec);

        mTimeTextView.setText(result);
    }
};

public class timeThread implements Runnable {

    @Override
    public void run() {
        mEndTime = System.currentTimeMillis() / 10 + i;
        timeThreadd = true;


        while (true) {
            while (isRunning) { //일시정지를 누르면 멈춤
                Message msg = new Message();
                msg.arg1 = (int) i++;
                handler.sendMessage(msg);

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {


                            mTimeTextView.setText("");
                            mTimeTextView.setText("00:00:00:00");
                        }
                    });
                    return;
                }
            }
        }
    }
}

@Override
protected void onStop() {
    super.onStop();
    SharedPreferences sharedpreferences = getSharedPreferences("timer", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putLong("time", i);
    editor.putBoolean("switch", isRunning);
    editor.putInt("recordsize", record.size());
    editor.putLong("endTime", mEndTime);
    Log.v("i", String.valueOf(i));
    Log.v("iswitch", String.valueOf(isRunning));
    Log.v("endTime", String.valueOf(mEndTime));
    isRunning = false;

    for (int i = 0; i < record.size(); i++) {
        editor.putString("record" + i, record.get(i));
    }
    editor.apply();
    if (timeThreadd != false) {
        timeThread.interrupt();
    }
    if (record.size() > 0) {
        for (int i = 0; i < record.size(); i++) {
            record.remove(i);
        }
    }

}

@Override
protected void onStart() {
    super.onStart();
    SharedPreferences sharedpreferences = getSharedPreferences("timer", MODE_PRIVATE);
    i = sharedpreferences.getLong("time", 0);

    isRunning = sharedpreferences.getBoolean("switch", isRunning);
    int b = sharedpreferences.getInt("recordsize", 0);
    for (int i = 0; i < b; i++) {
        String c = sharedpreferences.getString("record" + i, null);
        record.add(c);
        mRecordTextView.setText(mRecordTextView.getText() + c + "\n");
    }

    if (isRunning) {
        mEndTime = sharedpreferences.getLong("endTime", 0);

        Log.v("      set mEndTime",String.valueOf(mEndTime));
        i = System.currentTimeMillis() / 10 - mEndTime;


        Log.v("     set i",String.valueOf(i));
        if (i < 0) {
            isRunning = false;
            i = 0;
            mEndTime = 0;
            timeThreadd = false;
            mRecordBtn.setVisibility(View.GONE);
            mStartBtn.setVisibility(View.VISIBLE);
            mPauseBtn.setVisibility(View.GONE);
            mRecordTextView.setText("");
            mTimeTextView.setText("00:00:00:00");

        } else if (i > 0) {
            mStartBtn.setVisibility(View.GONE);
            mStopBtn.setVisibility(View.VISIBLE);
            mRecordBtn.setVisibility(View.VISIBLE);
            mPauseBtn.setVisibility(View.VISIBLE);
            timeThread = new Thread(new timeThread());


            timeThread.start();

        }
    }
}
}

标签: androidtimersharedpreferenceshandler

解决方案


我解决问题。

   public void run() {
        if(timeThreadd!= true){
            mEndTime = System.currentTimeMillis() / 10 + i;
            timeThreadd = true;
        }

问题是 System.currentTimeMillis()。

System.currentTimeMillis() 只需在用户按下开始按钮时存储一次。


推荐阅读