"(null)"想给您发送通知

更改如图所示:便好!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Service可以通过使用Android系统提供的AlarmManager来实现定时发送通知的功能。具体步骤如下: 1. 在Service中创建一个PendingIntent对象,用于在触发时启动一个广播。 2. 使用AlarmManager的set方法来设置定时器,指定触发时间和要启动的广播。 3. 在广播接收器中实现发送通知的逻辑。 4. 在AndroidManifest.xml文件中注册Service和广播接收器。 下面是一个简单的示例代码,演示如何实现每天定时发送通知: ``` public class MyService extends Service { private static final int NOTIFICATION_ID = 1; private static final long INTERVAL_DAY = 24 * 60 * 60 * 1000; @Override public int onStartCommand(Intent intent, int flags, int startId) { // 创建PendingIntent对象,用于在触发时启动一个广播 Intent alarmIntent = new Intent(this, MyReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0); // 获取AlarmManager对象,并设置定时器 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, getTriggerTime(), INTERVAL_DAY, pendingIntent); return super.onStartCommand(intent, flags, startId); } // 计算定时器触发时间 private long getTriggerTime() { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 8); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); if (calendar.getTimeInMillis() < System.currentTimeMillis()) { calendar.add(Calendar.DAY_OF_MONTH, 1); } return calendar.getTimeInMillis(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 发送通知 NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("定时通知") .setContentText("今天是新的一天,加油哦!") .setAutoCancel(true); Notification notification = builder.build(); notificationManager.notify(NOTIFICATION_ID, notification); } } <service android:name=".MyService" /> <receiver android:name=".MyReceiver" /> ``` 这段代码会在每天早上8点定时发送一条通知。在实际开发中,可以根据要修改触发时间、通知内容等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值