Android每5秒安排一次工作

时间:2018-08-04 12:16:38

标签: android

在Android应用程序中,我想在Logcat中显示简单消息或显示简单通知,我实现的Alarm Manager一次只能正常工作一次,此后停止,并且在{{ 1}}

我的活动:

Logcat

@Override public void onResume() { super.onResume(); scheduleNotification(getNotification("5 second delay"), 5000); } private void scheduleNotification(Notification notification, int delay) { Intent notificationIntent = new Intent(this, NotificationPublisher.class); notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1); notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); long futureInMillis = SystemClock.elapsedRealtime() + delay; AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 2000,1000 * 5,pendingIntent); } } private Notification getNotification(String content) { Log.e("getNotification: ", content); Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle("Scheduled Notification"); builder.setContentText(content); builder.setSmallIcon(R.mipmap.ic_launcher_round); return builder.build(); } 类:

NotificationPublisher
Android清单中的

public class NotificationPublisher extends BroadcastReceiver { public static String NOTIFICATION_ID = "13789641254784001"; public static String NOTIFICATION = "notification"; public void onReceive(Context context, Intent intent) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = intent.getParcelableExtra(NOTIFICATION); int id = intent.getIntExtra(NOTIFICATION_ID, 0); notificationManager.notify(id, notification); Log.e("aaa", " ......."); } }

receiver

1 个答案:

答案 0 :(得分:-1)

尝试

Intent intent = new Intent(this, MyReceiver.class);
    intent.putExtra("key", "Alert");
    pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar calendar=Calendar.getInstance();


    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*1000, pendingIntent);