安卓定时通知

3

我看过一个简单的应用程序,可以在按下按钮后5秒钟安排通知。但是我真正想做的是根据特定时间安排通知(例如,在00:00显示通知),但我不知道如何设置这个时间点(因为现在我正在使用“延迟”)。

以下是代码:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_5:
            scheduleNotification(getNotification("5 second delay"), 5000);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

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);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}

private Notification getNotification(String content) {
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle("Scheduled Notification");
    builder.setContentText(content);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    return builder.build();
}

}

还有NotificationPublisher类

public class NotificationPublisher extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
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);

}
}

如果我知道如何安排通知,每天在00:00出现一条通知就更好了。

3个回答

3

我之前遇到过这个问题。因此,我很乐意帮助您,以便您不会像我一样浪费太多时间。我将尽可能简单和简洁地解释。

  • 从系统获取闹钟服务。
  • 创建一个待处理intent,并传递广播接收器类的名称。
  • 创建一个日历对象,并将其时间设置为上午8点。
  • 检查当前时间是否已经超过了8点。如果是,则将其添加到另一天。
  • 调用AlarmManager类的set repeating方法。

以下是示例代码:

alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(context of current file, AlarmReceiver1.class); // AlarmReceiver1 = broadcast receiver

pendingIntent = PendingIntent.getBroadcast(  Menu.this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmIntent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
alarmManager.cancel(pendingIntent);

Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 8);
alarmStartTime.set(Calendar.MINUTE, 00);
alarmStartTime.set(Calendar.SECOND, 0);
if (now.after(alarmStartTime)) {
       Log.d("Hey","Added a day");
       alarmStartTime.add(Calendar.DATE, 1);
}

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("Alarm","Alarms set for everyday 8 am.");

接下来是广播接收器类。您需要在清单文件中注册广播接收器。这将导致您接收时钟事件。

覆盖此广播接收器的onReceive方法,并在其中创建通知,或创建一个单独的通知构建服务,在那里构建和显示您的通知。

清单文件代码片段:

<receiver android:name="AlarmReceiver1"  android:enabled="true">

广播接收器代码片段:

以下是广播接收器的代码片段:

    public class AlarmReceiver1 extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
          Intent service1 = new Intent(context, NotificationService1.class);
      service1.setData((Uri.parse("custom://"+System.currentTimeMillis())));
                  context.startService(service1);
    }

通知建立服务代码片段:

    public class NotificationService1 extends IntentService{

        private NotificationManager notificationManager;
        private PendingIntent pendingIntent;
        private static int NOTIFICATION_ID = 1;
        Notification notification;
    @Override
        protected void onHandleIntent(Intent intent) {
    Context context = this.getApplicationContext();
               notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
     Intent mIntent = new Intent(this, Activity to be opened after clicking on the notif);
                Bundle bundle = new Bundle();
                bundle.putString("test", "test");
                mIntent.putExtras(bundle);
                pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);    

                Resources res = this.getResources();
                NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                notification = new NotificationCompat.Builder(this)
                            .setContentIntent(pendingIntent)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
                            .setTicker("ticker value")
                            .setAutoCancel(true)
                            .setPriority(8)
                            .setSound(soundUri)
                            .setContentTitle("Notif title")
                            .setContentText("Text").build();
                notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
                notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
                notification.ledARGB = 0xFFFFA500;
                notification.ledOnMS = 800;
                notification.ledOffMS = 1000;
                notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(NOTIFICATION_ID, notification);
                Log.i("notif","Notifications sent.");

        }

    }

如果需要关于代码的帮助,可以在这里找到:http://www.singhajit.com/schedule-local-notification-in-android/ 就是这样,希望能帮到你。


还需要将服务添加到清单文件中(使用更改后的类名): <service android:name="com.changethis.NotificationService1" android:exported="false" > </service> - omanosoft

2
你需要的是 RTC_WAKEUP。
不要使用延迟,可以按照以下方法操作:
Calendar calendar = Calendar.getInstance();

calendar.setTimeInMillis(System.currentTimeMillis());  
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0); // For 00:00

alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

您可以在这里找到更多信息:https://developer.android.com/training/scheduling/alarms.html。该网页提供了有关如何在Android应用程序中使用警报的详细信息,包括如何设置、触发和取消警报。它还解释了不同类型的警报以及如何选择最适合您应用程序需求的警报类型。

2

以下是相同代码:

public static void setNotificationScheduler(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, NotificationPublisher.class);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 999999, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Set the alarm to start at 00:00
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
}

不适用于尚未运行应用程序的 O+ 设备 https://developer.android.com/about/versions/oreo/background#broadcasts - Yuri Misyac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接