首页 > 解决方案 > 服务中 CountDownTimer 的 onTick 方法未执行

问题描述

我有一个使用部分唤醒锁定的倒计时计时器,它应该在onTick()设定的分钟数后以方法发送短信。它在模拟器上运行良好,但在真实设备上却不行。它onTick()在服务启动时几乎执行,但我需要延迟后发送 SMS,这就是为什么我需要设置一个布尔值 skip来检查它,但它不会onTick()在它应该再次执行时再次执行。我给了onFinish()额外的 15 秒,只是为了确保onTick()有足够的时间,但什么也没发生。
这是我的代码,在这种情况下去掉了无关的杂乱:

public class SMSService extends Service {

    private PowerManager.WakeLock mWakeLock = null;
    private boolean skip = true;
    SmsManager mSmsManager;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mSmsManager = SmsManager.getDefault();
        SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.acquire();

        timer(minutes, true);

        if (Build.VERSION.SDK_INT >= 26) {
            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Notification mNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle(getString(R.string.notification_title))
                    .setContentText(getString(R.string.notification_text))
                    .setSmallIcon(R.drawable.ic_local)
                    .setContentIntent(mPendingIntent)
                    .build();

            startForeground(1, mNotification);
        }
        return START_NOT_STICKY;
    }

    void timer(final int minutes, final boolean close) {

        CountDownTimer cdt = new CountDownTimer(minutes * 60 * 1000 + 15000, minutes * 60 * 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (!skip) {
                    mSmsManager.sendTextMessage(number, null, sms_body, null, null);
                }
                skip = false;
            }
            @Override
            public void onFinish() {
                if (!close) {
                    skip = true;
                    timer(minutes, true);
                }
                else {
                    stopSelf();
                }
            }
        };
        cdt.start();
    }
}

标签: androidservicecountdowntimerandroid-wake-lock

解决方案


推荐阅读