CountDownTimer的onFinish触发通知时setWhen传参报错如何解决
错误原因
你调用了onFinish()方法本身作为setWhen()的参数,但你当前重写的onFinish()是无返回值(void)的方法,自然不符合setWhen()要求传入long类型时间戳的参数规则。同时该写法还会造成递归调用,就算类型匹配也会直接触发栈溢出。
解决方案
setWhen()方法用于设置通知栏显示的通知触发时间,单位为毫秒,你需要倒计时结束时显示当前时间,直接传入系统当前时间戳System.currentTimeMillis()即可。
修正后的代码示例:
CountDownTimer cdt = viewHolder.myCounter; if (cdt == null) { // 注意:如果getDaysUntilWater返回的是天数,需要将60000替换为86400000(1天的毫秒数) cdt = new CountDownTimer(plant.getDaysUntilWater()*60000, 60000) { @Override public void onTick(long millisUntilFinished) { plant.setDaysUntilWater((int) ceil(millisUntilFinished/60000.0)); button.setText(Integer.toString((int) ceil(millisUntilFinished/60000.0))); } @Override public void onFinish() { button.setText(R.string.needwater); button.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY); Notification notification = new Notification.Builder(context) .setContentTitle(plant.getName()) .setContentText("I need water") // 替换为系统当前时间戳 .setWhen(System.currentTimeMillis()) // 必须补充小图标,否则通知无法正常展示 .setSmallIcon(R.mipmap.ic_launcher) .build(); // 补充发送通知的逻辑,否则通知不会弹出 NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Android 8.0及以上需要先创建通知通道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("water_remind_channel", "植物浇水提醒", NotificationManager.IMPORTANCE_HIGH); notificationManager.createNotificationChannel(channel); } // 用植物id作为通知id避免覆盖 notificationManager.notify(plant.getId(), notification); } }; cdt.start(); }
内容的提问来源于stack exchange,提问作者Farhan Fadhilah
相关产品推荐
相关产品推荐

