【问题标题】:Android count down timer in backgroundAndroid 在后台倒计时
【发布时间】:2011-12-28 17:21:26
【问题描述】:

我有一个 Android 应用程序,它管理一个倒数计时器(CountDownTimer 类),它显示在应用程序屏幕中,以显示距离 00:00 还剩多少时间。

我现在的问题是,当我按下主页按钮或启动另一个应用程序时,应用程序/计时器不会在后台运行。所以我怀疑我必须做一个服务,但是怎么做呢?同事对我说,当设备被锁定时,我必须做一些特别的事情才能让计时器继续运行。我想在到达 0 时醒来。

最好的方法是什么?

【问题讨论】:

    标签: android service background


    【解决方案1】:

    您必须创建 CountDownTimer 类并从 Service 类扩展它。 通过这样做,您的活动将成为一项服务,即使您关闭它也会在后台运行 应用程序或屏幕无关紧要,它只是在后台执行您分配给它的任务。

    【讨论】:

    • 目前我有:“public class MyCount extends CountDownTimer{ ....”来使用 onTic 例程,所以我知道我必须创建一个 MyCount 扩展服务,并在其中“我的类扩展 CountDownTimer” ???在这种情况下,如果我更新班级抽动例程(倒计时)剩余时间的文本视图,它会正确更新吗?
    • 我也在研究 asyntask,它可以轻松更新 UI。如果我将我的应用程序发送到后台(即启动另一个应用程序),这个配置会被杀死吗?
    • 还有另一个问题:如果我按照你说的那样扩展服务,我需要一些特殊的东西来更新调用类 UI 吗?谢谢
    • 是的,如果您的服务运行良好并且您的 AsyncTask 编写正常,它将正确更新 UI。即使程序已关闭并且您打开另一个应用程序,您的服务也将在后台运行并完成工作.如果你扩展服务,你不需要做一些特别的事情,它是相同的,AsyncTask 会更新 Ui,所以你可以从那里进行调用。
    • 我正在考虑在 Asyntask 中进入 UI 线程,而不是在服务中,以便尝试服务,这对我来说看起来很复杂。
    【解决方案2】:

    首先,您需要使用Handler 来操作计时器,但请查看这篇精彩的帖子,看看是否有帮助:

    How to set a timer in android

    Android 开发人员资源也涉及此主题:

    http://developer.android.com/resources/articles/timed-ui-updates.html

    【讨论】:

      【解决方案3】:

      最简单的方法是使用定时器异步服务。您可以从这里下载源代码 (Android Countdown Timer Run In Background)

      服务类:

      package com.countdowntimerservice;
      
      
      import android.app.Service;
      import android.content.Intent;
      import android.content.SharedPreferences;
      import android.os.Handler;
       import android.os.IBinder;
      import android.preference.PreferenceManager;
      import android.support.annotation.Nullable;
      import android.util.Log;
      
      import java.text.SimpleDateFormat;
      import java.util.Calendar;
      import java.util.Date;
      import java.util.Timer;
      import java.util.TimerTask;
      import java.util.concurrent.TimeUnit;
      
      public class Timer_Service extends Service {
      
      public static String str_receiver = "com.countdowntimerservice.receiver";
      
      private Handler mHandler = new Handler();
      Calendar calendar;
      SimpleDateFormat simpleDateFormat;
      String strDate;
      Date date_current, date_diff;
      SharedPreferences mpref;
      SharedPreferences.Editor mEditor;
      
      private Timer mTimer = null;
      public static final long NOTIFY_INTERVAL = 1000;
      Intent intent;
      
      @Nullable
      @Override
      public IBinder onBind(Intent intent) {
          return null;
      }
      
      @Override
      public void onCreate() {
          super.onCreate();
      
          mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
          mEditor = mpref.edit();
          calendar = Calendar.getInstance();
          simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
      
          mTimer = new Timer();
          mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
          intent = new Intent(str_receiver);
      }
      
      
      class TimeDisplayTimerTask extends TimerTask {
      
          @Override
          public void run() {
              mHandler.post(new Runnable() {
      
                  @Override
                  public void run() {
      
                      calendar = Calendar.getInstance();
                      simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                      strDate = simpleDateFormat.format(calendar.getTime());
                      Log.e("strDate", strDate);
                      twoDatesBetweenTime();
      
                  }
      
              });
          }
      
      }
      
      public String twoDatesBetweenTime() {
      
      
          try {
              date_current = simpleDateFormat.parse(strDate);
          } catch (Exception e) {
      
          }
      
          try {
              date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
          } catch (Exception e) {
      
          }
      
          try {
      
      
              long diff = date_current.getTime() - date_diff.getTime();
              int int_hours = Integer.valueOf(mpref.getString("hours", ""));
      
              long int_timer = TimeUnit.HOURS.toMillis(int_hours);
              long long_hours = int_timer - diff;
              long diffSeconds2 = long_hours / 1000 % 60;
              long diffMinutes2 = long_hours / (60 * 1000) % 60;
              long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
      
      
              if (long_hours > 0) {
                  String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
      
                  Log.e("TIME", str_testing);
      
                  fn_update(str_testing);
              } else {
                  mEditor.putBoolean("finish", true).commit();
                  mTimer.cancel();
              }
          }catch (Exception e){
              mTimer.cancel();
              mTimer.purge();
      
      
          }
      
          return "";
      
      }
      
      @Override
      public void onDestroy() {
          super.onDestroy();
          Log.e("Service finish","Finish");
      }
      
      private void fn_update(String str_time){
      
          intent.putExtra("time",str_time);
          sendBroadcast(intent);
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-01
        • 1970-01-01
        相关资源
        最近更新 更多