我希望我的计时器在后台运行,但它会在后台android中停止

时间:2014-04-22 09:01:12

标签: java android alarmmanager timertask

##此主要活动类##

>建议我给出合适的答案

pref = getPreferences(MODE_PRIVATE);
            time = pref.getInt("key1", 300);
            if (time == 300) {                

**从碎片优惠中获取初始值**

                number.setText("01:00:00");
                startTimer(time, false);
            } else {
                startTimer(time, false);
            }
        }

        private void prepareView() {

        }

        private void setOnListener() {

            btnLunchOUT.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {

                    startTimer(time, true);
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            btnLunchIN.setEnabled(true);
                        }
                    }, 2000);



}
            });

此处将已停止时间的值存储在共享首选项中

  btnLunchIN.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    countdownTask.cancel();
                    btnLunchIN.setEnabled(false);

                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            btnLunchOUT.setEnabled(true);
                        }
                    }, 3000);
                    btnReset.setEnabled(true);

                    Toast.makeText(getApplicationContext(), "Timer Stopped",
                            Toast.LENGTH_SHORT).show();
                    flag = false;

                    pref = getPreferences(MODE_PRIVATE);**
                    SharedPreferences.Editor edit = pref.edit();
                    edit.putInt("key", time);
                    edit.commit();

                }
            });

**从共享Prefrences获取开始时间的价值**

            btnReset.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    if (!flag) {

                        // countdownTask.cancel();
                        btnReset.setEnabled(false);
                        btnLunchOUT.setEnabled(true);
                        btnLunchIN.setEnabled(false);
                        flag = false;
                        time = 300;
                        number.setText("00:00:00");// Reset Timing Format
                        pref = getPreferences(MODE_PRIVATE);
                        SharedPreferences.Editor edit = pref.edit();
                        edit.putInt("key", 300);
                        edit.commit();
                    }
                }
            });
        }



        @Override
        public void onResume() { ## OnResume method where i think its problem but i m unable to trace it

            System.out.println("In Resume");
            super.onResume();
            pref = getPreferences(MODE_PRIVATE);
            time = pref.getInt("key", time);
            number.setText("" + time);

            s = (time) % 60;
            m = ((time) / 60) % 60;
            h = 00;
            number.setText("0" + h + ":" + m + ":" + s);



            startTimer(time, false);
        }


    ## **onPause method** ##
        @Override
        public void onPause() { 

            System.out.println("Timer Pause:");
            pref = getPreferences(MODE_PRIVATE);
            SharedPreferences.Editor edit = pref.edit(); // Saving the value of timer in shared preferences
            edit.putInt("key", time);
            edit.commit();

            super.onPause();

        }
    ## Here my timer starts on start button click
        public void startTimer(int value, boolean isStartButton) {

            time = value;
            Log.e("ONMAIN:: ", "" + time);
            if (isStartButton) {
                countdownTask = new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                        time--; // ***Here i split 300 into HH:MM:SS format***
                            s = (time) % 60;
                                m = ((time) / 60) % 60;
                                h = 00;

                                System.out.println("In Run" + time);

>在60秒的时间内启用声音和振动器

                if (s < 10) {
                                    if (m < 10) {
                                        number.setText("0" + h + ":" + 0 + m + ":"
                                                + 0 + s);
                                    }
                                } else if (s < 10) {
                                    number.setText("0" + h + ":" + m + ":" + 0 + s);
                                } else if (m < 10) {
                                    number.setText("0" + h + ":" + 0 + m + ":" + s);
                                }

                                else {
                                    number.setText("0" + h + ":" + m + ":" + s);

                                }
                                btnLunchOUT.setEnabled(false);

                                btnReset.setEnabled(false);

                                if (time == 60) {
                                    vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

                                    vibrate.vibrate(pattern, -1);

                                    soundalert.start();
                                    System.out.println("1 Minute Remianing ");
                                }

                                if (time == 1) {

                                    countdownTask.cancel();


                                }
                            }
                        });
                    }
                };
                Timer countdown = new Timer(); //This is timer 
                countdown.scheduleAtFixedRate(countdownTask, 0, 1000);
                flag = false;
            }
        }

    }

1 个答案:

答案 0 :(得分:2)

使计时器在后台运行的最佳解决方案是通过Service进行。 创建一个Service,您可以在onPause方法上启动(并将其传递给您的计时器实例),然后当您使用onResume方法时将其销毁(并检索计时器)将你的主要活动放在首位。

修改

public class TimerService extends Service {

   @Override
   public IBinder onBind(Intent intent) {
       return null;
   }

   @Override
   public void onCreate() {
       super.onCreate();
       Log.i("SERVICE", "CREATED");
   }

   @Override
   public void onDestroy() {
       super.onDestroy();   
       Log.i("SERVICE", "DESTROYED");
       //Save your timer instance on destroy service
   }

   @Override
   public void onLowMemory() {
       super.onLowMemory();
       Log.i("SERVICE", "LOW MEMORY");
   }


   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
     //Retrieve the timer instance here and use it... 

       //Restart service if Android destroys it!
       return Service.START_NOT_STICKY; 
   } 
}

在您的主要活动中,在onPause启动服务(活动进入后台时调用onPause):

Intent inetnt=new Intent(this, TimerService.class);
intnet.putExtra("Timer", YourTimerInstance); //Instance as string or int...
startService(inetnt);

在您的主要活动中,在onResume(当您的活动再次进入前台时调用)停止服务并从中检索实例。要执行此操作,您可以使用SharedPreferences(谷歌中有SharedPreferences的thounsands示例)。要启动服务:

Intent inetnt=new Intent(this, TimerService.class);
//Retrieve timer instance
stopService(inetnt);

希望它有所帮助!