具有Handler和SharedPreference的计时器

时间:2019-03-16 19:26:23

标签: android timer sharedpreferences handler

如今,我试图通过使用处理程序和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();

        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

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

问题出在System.currentTimeMillis()。

当用户按下开始按钮时,System.currentTimeMillis()仅需要存储一次。