如何在 Android 的服务中运行 CountDownTimer? [英] How to run CountDownTimer in a Service in Android?

查看:24
本文介绍了如何在 Android 的服务中运行 CountDownTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个运行 CountDownTimer 的服务,并且在每个滴答声中我都想在 Activity 中显示倒计时,并在一段时间后播放声音.

I want a service which runs a CountDownTimer and in every tick I want to show the countdown in a Activity and after some interval play a sound.

所有过程在单个活动中都进行得很好,但在来电期间倒计时不起作用,这就是我想使用服务来做到这一点的原因.

All the process are going fine in a single Activity but during incoming call the countdown not working that's why I want to do this using a Service.

有人可以帮我吗?

提前致谢.

更新...

mCountDownTimer = new CountDownTimer(mTimerDuration, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (mTimerDuration > 0) {
                    mDurationCount += 1000;
                    showCountDown(
                            ActivityA.this,
                            (mSimpleDateFormat.format(mTimerDuration
                                    - mDurationCount)));
                    if (mDurationCount == mTimerDuration) {
                        if (mRepeatTime > 1) {
                            startRepeatTimer();
                        }
                        finishTimer();
                    }
                }
            }

            @Override
            public void onFinish() {
            }
        }.start();

推荐答案

最简单的方法可能是在您的活动中创建一个广播接收器,并让服务向接收器发送广播.这是带有简化 CountDownTimer 的服务类的完整列表.

The easiest way is probably to create a broadcast receiver in your activity and have the service send broadcasts to the receiver. Here's a full listing for a service class with a simplified CountDownTimer.

package com.example.cdt;

import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;

public class BroadcastService extends Service {

    private final static String TAG = "BroadcastService";

    public static final String COUNTDOWN_BR = "your_package_name.countdown_br";
    Intent bi = new Intent(COUNTDOWN_BR);

    CountDownTimer cdt = null;

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

            Log.i(TAG, "Starting timer...");

            cdt = new CountDownTimer(30000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                    Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
                    bi.putExtra("countdown", millisUntilFinished);
                    sendBroadcast(bi);
                }

                @Override
                public void onFinish() {
                    Log.i(TAG, "Timer finished");
                }
            };

            cdt.start();
        }

        @Override
        public void onDestroy() {

            cdt.cancel();
            Log.i(TAG, "Timer cancelled");
            super.onDestroy();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {       
            return super.onStartCommand(intent, flags, startId);
        }

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

以下是主要活动的相关行:

And here are the relevant lines from a main activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    startService(new Intent(this, BroadcastService.class));
    Log.i(TAG, "Started service");
}

private BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {            
        updateGUI(intent); // or whatever method used to update your GUI fields
    }
};

@Override  
public void onResume() {
    super.onResume();        
    registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
    Log.i(TAG, "Registered broacast receiver");
    }

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(br);
    Log.i(TAG, "Unregistered broacast receiver");
}

@Override
public void onStop() {
    try {
        unregisterReceiver(br);
    } catch (Exception e) {
        // Receiver was probably already stopped in onPause()
    }
    super.onStop();
}
@Override
public void onDestroy() {        
    stopService(new Intent(this, BroadcastService.class));
    Log.i(TAG, "Stopped service");
    super.onDestroy();
}

private void updateGUI(Intent intent) {
    if (intent.getExtras() != null) {
        long millisUntilFinished = intent.getLongExtra("countdown", 0);
        Log.i(TAG, "Countdown seconds remaining: " +  millisUntilFinished / 1000);            
    }
}

您还需要在清单文件中的开始/结束应用程序标记之间定义服务.

You'll also need to define the service between the start/end application tags in your manifest file.

<service android:name=".BroadcastService" />

这篇关于如何在 Android 的服务中运行 CountDownTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆