android - 服务中 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();
}
}
解决方案
推荐阅读
- vue.js - TinyMCE 仅加载到 vue js 应用程序一次
- python - 返回句子中某个字符串的索引号
- angular - 我如何运行 file.JAR 使用控制器 RESTFUL ( Spring Framework ) 传递动态参数
- android - Android Studio:无法在可绘制文件夹中使用资源文件
- git - 迁移到 LFS 后存储库仍然很大
- excel - Excel 2016。如何从工作表中显示 Userform1 的特定值?
- c# - 如何在 MongoDB C# 聚合管道中使用 Addfields
- python - Python,部分程序独立运行
- android - 当 DAO 方法需要更改参数时,如何使用 LiveData?
- firebase - ServiceWorker:离线插件和 Firebase