倒计时器在手机关机或应用程序被杀时仍然运行

时间:2014-08-21 06:26:24

标签: java android multithreading timer android-service

我正在尝试创建倒计时器,即使应用程序被终止或手机关闭时也会运行。例如,假设我运行倒数计时器从5小时开始倒计时。当我关闭它时,它重置为零。我想要它,以便当我从5小时开始计算它并将我的手机转动一小时并将其重新打开时,计时器显示剩余时间为4小时。我正在研究服务和多线程,但无法生成或找到适合我的解决方案。

In Android i want to run countdown timer who can run in background also

Implementing a Count down timer using Service in the background

这是我的代码段:

start_timer.setOnClickListener(new View.OnClickListener() {


    @Override
    public void onClick(View view) {

        new AlertDialog.Builder( MainActivity.this )
                .setMessage( "Are you sure you want to block the selected apps for the set amount of time?" )
                .setPositiveButton( "Yeah man!", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d( "AlertDialog", "Positive" );

                        hourint = Integer.valueOf(number_text.getText().toString());

                        minuteint = Integer.valueOf(minute_text.getText().toString());

                        secondint = Integer.valueOf(second_text.getText().toString());

                        Log.i("YourActivity", "Hours: " + hourint);

                        Log.i("YourActivity", "Minutes: " + minuteint);

                        Log.i("YourActivity", "Seconds: " + secondint);

                        totalTimeCountInMilliseconds = ((hourint*60*60) +(minuteint*60) + (secondint)) * 1000;      // time count
                        timeBlinkInMilliseconds = 30*1000;

                        countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
                            // 500 means, onTick function will be called at every 500 milliseconds

                            @Override
                            public void onTick(long leftTimeInMilliseconds) {
                                long seconds = leftTimeInMilliseconds / 1000;
                                mSeekArc.setVisibility(View.INVISIBLE);
                                start_timer.setVisibility(View.INVISIBLE);
                                block_button1.setVisibility(View.INVISIBLE);



                                if ( leftTimeInMilliseconds < timeBlinkInMilliseconds ) {
                                    // textViewShowTime.setTextAppearance(getApplicationContext(), R.style.blinkText);
                                    // change the style of the textview .. giving a red alert style

                                    if ( blink ) {
                                        number_text.setVisibility(View.VISIBLE);
                                        minute_text.setVisibility(View.VISIBLE);
                                        second_text.setVisibility(View.VISIBLE);


                                        // if blink is true, textview will be visible
                                    } else {
                                        number_text.setVisibility(View.INVISIBLE);
                                        minute_text.setVisibility(View.INVISIBLE);
                                        second_text.setVisibility(View.INVISIBLE);


                                    }

                                    blink = !blink;         // toggle the value of blink
                                }

                                second_text.setText(String.format("%02d", seconds % 60));
                                minute_text.setText(String.format("%02d", (seconds / 60) % 60));
                                number_text.setText(String.format("%02d", seconds / 3600));                     // format the textview to show the easily readable format
                            }


                            @Override
                            public void onFinish() {
                                // this function will be called when the timecount is finished
                                //textViewShowTime.setText("Time up!");
                                number_text.setVisibility(View.VISIBLE);
                                minute_text.setVisibility(View.VISIBLE);
                                second_text.setVisibility(View.VISIBLE);
                                mSeekArc.setVisibility(View.VISIBLE);
                                start_timer.setVisibility(View.VISIBLE);
                                block_button1.setVisibility(View.VISIBLE);


                            }

                        }.start();
                    }
                })
                .setNegativeButton( "Nope!", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d( "AlertDialog", "Negative" );
                        dialog.cancel();
                    }
                } )
                .show();

我如何实现这一点以及我必须对代码进行哪些修改?

编辑:这是我的完整代码:

http://pastebin.com/pth9KZWP

编辑2:此处是修订后的代码:

我的应用无法启动。我没有收到任何logcat声明,所以我不知道该怎么做......

http://pastebin.com/L8HgGtsy

2 个答案:

答案 0 :(得分:2)

在输入倒计时后,计算倒计时结束的时间并将其写入持久存储。然后,只要应用程序重新启动,请阅读该时间并计算从现在开始剩余的时间。

答案 1 :(得分:0)

我认为任何人都有同样的问题;)

这是检索onCreate

中类顶部的SharedPreferences
startimerPreferences = getPreferences(MODE_APPEND);

Date startDate = new Date(startimerPreferences.getLong("time", 0));
timerstarted = startDate.getTime();
Log.e("This is the start time!!!!!:  ", timerstarted + "");


endTimerPreferences = getPreferences(MODE_APPEND);
Date endDate = new Date(endTimerPreferences.getLong("time", 0));
timerends = endDate.getTime();
Log.e("This is the end time!!!!!:  ", timerends + "");


Date openagain = new Date(System.currentTimeMillis());
reopened = openagain.getTime();

如果还有剩余时间,则启动剩余时间的计时器:

    if(timerstarted > 0)
    {
        if(reopened <timerends){
            //start countdown timer with new time.
            //set countdowntime to timerends-reopen.

            newtotalTimeCountInMilliseconds = timerends-reopened;
            countDownTimer = new CountDownTimer(newtotalTimeCountInMilliseconds, 500) {
                // 500 means, onTick function will be called at every 500 milliseconds

                @Override
                public void onTick(long leftTimeInMilliseconds) {

                    long seconds = leftTimeInMilliseconds / 1000;
                    mSeekArc.setVisibility(View.INVISIBLE);
                    start_timer.setVisibility(View.INVISIBLE);
                    block_button1.setVisibility(View.INVISIBLE);


                    if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
                        // textViewShowTime.setTextAppearance(getApplicationContext(), R.style.blinkText);
                        // change the style of the textview .. giving a red alert style

                        if (blink) {
                            number_text.setVisibility(View.VISIBLE);
                            minute_text.setVisibility(View.VISIBLE);
                            second_text.setVisibility(View.VISIBLE);


                            // if blink is true, textview will be visible
                        } else {
                            number_text.setVisibility(View.INVISIBLE);
                            minute_text.setVisibility(View.INVISIBLE);
                            second_text.setVisibility(View.INVISIBLE);


                        }

                        blink = !blink;         // toggle the value of blink
                    }

                    second_text.setText(String.format("%02d", seconds % 60));
                    minute_text.setText(String.format("%02d", (seconds / 60) % 60));
                    number_text.setText(String.format("%02d", seconds / 3600));                     // format the textview to show the easily readable format
                }


                @Override
                public void onFinish() {
                    // this function will be called when the timecount is finished
                    //textViewShowTime.setText("Time up!");
                    number_text.setVisibility(View.VISIBLE);
                    minute_text.setVisibility(View.VISIBLE);
                    second_text.setVisibility(View.VISIBLE);
                    mSeekArc.setVisibility(View.VISIBLE);
                    start_timer.setVisibility(View.VISIBLE);
                    block_button1.setVisibility(View.VISIBLE);


                }

            }.start();



        }
    }

以下是用户提交操作的初始计时器。我将当前时间和结束时间提交并保存在SharedPreferences中。

start_timer.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {

                new AlertDialog.Builder( MainActivity.this )
                        .setMessage( "Are you sure you want to block the selected apps for the set amount of time?" )
                        .setPositiveButton("Yeah man!", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Log.d("AlertDialog", "Positive");

                                hourint = Integer.valueOf(number_text.getText().toString());

                                minuteint = Integer.valueOf(minute_text.getText().toString());

                                secondint = Integer.valueOf(second_text.getText().toString());

                                Log.i("YourActivity", "Hours: " + hourint);

                                Log.i("YourActivity", "Minutes: " + minuteint);

                                Log.i("YourActivity", "Seconds: " + secondint);

                                Date currenttime = new Date(System.currentTimeMillis());

                                timerstarted = currenttime.getTime();
                                Log.e("This is the current time:  ", timerstarted + "");
                                startimerPreferences = getPreferences(MODE_APPEND);
                                SharedPreferences.Editor starteditor = startimerPreferences.edit();
                                starteditor.putLong("time", timerstarted);
                                starteditor.commit();


                                Date endtime = new Date(System.currentTimeMillis());

                                timerends = endtime.getTime() + (((hourint * 60 * 60) + (minuteint * 60) + (secondint)) * 1000);
                                Log.e("This is the end time:  ", timerends + "");
                                endTimerPreferences = getPreferences(MODE_APPEND);
                                SharedPreferences.Editor endeditor = endTimerPreferences.edit();
                                endeditor.putLong("time", timerends);
                                endeditor.commit();









                                totalTimeCountInMilliseconds = (((hourint * 60 * 60) + (minuteint * 60) + (secondint)) * 1000);      // time count
                                timeBlinkInMilliseconds = 30 * 1000;

                                countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
                                    // 500 means, onTick function will be called at every 500 milliseconds

                                    @Override
                                    public void onTick(long leftTimeInMilliseconds) {

                                        long seconds = leftTimeInMilliseconds / 1000;
                                        mSeekArc.setVisibility(View.INVISIBLE);
                                        start_timer.setVisibility(View.INVISIBLE);
                                        block_button1.setVisibility(View.INVISIBLE);


                                        if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
                                            // textViewShowTime.setTextAppearance(getApplicationContext(), R.style.blinkText);
                                            // change the style of the textview .. giving a red alert style

                                            if (blink) {
                                                number_text.setVisibility(View.VISIBLE);
                                                minute_text.setVisibility(View.VISIBLE);
                                                second_text.setVisibility(View.VISIBLE);


                                                // if blink is true, textview will be visible
                                            } else {
                                                number_text.setVisibility(View.INVISIBLE);
                                                minute_text.setVisibility(View.INVISIBLE);
                                                second_text.setVisibility(View.INVISIBLE);


                                            }

                                            blink = !blink;         // toggle the value of blink
                                        }

                                        second_text.setText(String.format("%02d", seconds % 60));
                                        minute_text.setText(String.format("%02d", (seconds / 60) % 60));
                                        number_text.setText(String.format("%02d", seconds / 3600));                     // format the textview to show the easily readable format
                                    }


                                    @Override
                                    public void onFinish() {
                                        // this function will be called when the timecount is finished
                                        //textViewShowTime.setText("Time up!");
                                        number_text.setVisibility(View.VISIBLE);
                                        minute_text.setVisibility(View.VISIBLE);
                                        second_text.setVisibility(View.VISIBLE);
                                        mSeekArc.setVisibility(View.VISIBLE);
                                        start_timer.setVisibility(View.VISIBLE);
                                        block_button1.setVisibility(View.VISIBLE);


                                    }

                                }.start();
                            }
                        })
                        .setNegativeButton("Nope!", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Log.d("AlertDialog", "Negative");
                                dialog.cancel();
                            }
                        })
                        .show();