在更新文本视图时在服务中使用倒数计时器和 运行

Using Countdown timer and running it in a service while updating a textview

如标题所示,我在我的应用程序中使用了倒数计时器,我希望用户能够在后台有倒数计时器 运行 的同时退出应用程序并相应地更新文本视图。我假设需要一项服务,但我不知道如何在我的应用程序中为倒数计时器实施服务。下面提供的代码块将说明我在评论中遇到的问题。

更新

public class CountDownService extends Service {

    TextView timeTextView;
    int data;


    public  String hms;
    public CountDownAct countDownAct;
    public CountDownTime countDownTimer;

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

    }

    @Override
    public void onCreate() {
        super.onCreate();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

      data = intent.getIntExtra("the", 0);
        countDownTimer = new CountDownTime(data,1000 );
        countDownTimer.start();


        return START_STICKY; 


    }

    @Override
    public boolean stopService(Intent name) {

        Log.i("CountDownService", "Stop Service");
        return super.stopService(name);

    }

    @Override
    public void onDestroy() {

        countDownTimer.cancel();

    }

    public class CountDownTime extends CountDownTimer {


        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountDownTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {



            long millis = millisUntilFinished;

            // this is the format which reads the time data from the user and makes it readable
            hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));


            //the textview is updated with each tick that goes by and contains the current time that is left
            // I want this text to be updated even if the user exits the app. The textview has to be updated with the current time left until finishing

//            countDownAct.timeTextView.setText(hms);
            CountDownAct.timeTextView.setText(hms);
            Log.i("CountDownService", hms);

        }

        @Override
        public void onFinish() {
            Intent goBack = new Intent(getApplicationContext(), alarmtimefinished.class);
            goBack.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            goBack.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(goBack);

        }




    }

}

分类目录

07-24 18:27:41.629  19054-19054/com.personalproject.peter.timerapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.personalproject.peter.timerapp.CountDownService$CountDownTime.onTick(CountDownService.java:79)
            at android.os.CountDownTimer.handleMessage(CountDownTimer.java:124)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4867)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)

我最近一直在使用服务,它非常简单,只需制作一个扩展服务的 class,检查一下:http://developer.android.com/guide/components/services.html

将您的代码放在 onStartCommand 方法中

你为什么不在服务中创建一个定时器的对象class

如果您希望您的服务重复执行某些操作,请使用:

Handler mHandler;
private void doSomething() {


    scheduleNext(10*1000); // time in m seconds 
    //your code here



}

private void scheduleNext(int time) {
    mHandler.postDelayed(new Runnable() {
        public void run() {

            doSomething();

        }
    },time); 

希望对您有所帮助