如何在Android中安排通知

时间:2016-04-27 23:30:28

标签: java android android-studio notifications android-notifications

我正试图在将来设置通知。 我有创建通知的代码,但我找不到安排它的选项。

如何安排通知?

2 个答案:

答案 0 :(得分:37)

不适用于OREO +(编辑)

上面的答案很好 - 但不考虑用户重启设备的可能性(它清除了AlarmManager安排的PendingIntent)。

您需要创建一个WakefulBroadcastReceiver,它将包含一个AlarmManager来安排发送PendingIntent。当WakefulBroadcastReceiver处理意图时 - 发布您的通知并通知WakefulBroadcastReceiver完成。

<强> WakefulBroadcastReceiver

boolean[] doors = new boolean[100];
for (int idx = 0, incr = 1; idx < doors.length; idx += (incr += 2))
    doors[idx] = true;
//print here

<强> BootReceiver

1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001

<强>的AndroidManifest.xml

    /**
     * When the alarm fires, this WakefulBroadcastReceiver receives the broadcast Intent
     * and then posts the notification.
     */
    public class WakefulReceiver extends WakefulBroadcastReceiver {
        // provides access to the system alarm services.
        private AlarmManager mAlarmManager;

        public void onReceive(Context context, Intent intent) {
            //// TODO: post notification
            WakefulReceiver.completeWakefulIntent(intent);
        }

        /**
         * Sets the next alarm to run. When the alarm fires,
         * the app broadcasts an Intent to this WakefulBroadcastReceiver.
         * @param context the context of the app's Activity.
         */
        public void setAlarm(Context context) {
            mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, WakefulReceiver.class);
            PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            //// TODO: use calendar.add(Calendar.SECOND,MINUTE,HOUR, int);
            //calendar.add(Calendar.SECOND, 10);

            //ALWAYS recompute the calendar after using add, set, roll
            Date date = calendar.getTime();

            mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, date.getTime(), alarmIntent);

            // Enable {@code BootReceiver} to automatically restart when the
            // device is rebooted.
            //// TODO: you may need to reference the context by ApplicationActivity.class
            ComponentName receiver = new ComponentName(context, BootReceiver.class);
            PackageManager pm = context.getPackageManager();
            pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);
        }

        /**
         * Cancels the next alarm from running. Removes any intents set by this
         * WakefulBroadcastReceiver.
         * @param context the context of the app's Activity
         */
        public void cancelAlarm(Context context) {
            Log.d("WakefulAlarmReceiver", "{cancelAlarm}");

            mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, WakefulReceiver.class);
            PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

            mAlarmManager.cancel(alarmIntent);

            // Disable {@code BootReceiver} so that it doesn't automatically restart when the device is rebooted.
            //// TODO: you may need to reference the context by ApplicationActivity.class
            ComponentName receiver = new ComponentName(context, BootReceiver.class);
            PackageManager pm = context.getPackageManager();
            pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
        }

答案 1 :(得分:28)

您需要使用d3.csv('Input/test_single.csv') .row(function (d) { return d }) .get(function (error, rows) { var chart = d3.select("#chart-div").data(rows).enter().append("svg").classed("chart", true).attr("width", width); chart.append("rect") .attr("x", function(d){return(parseInt(d.Start) + parseInt(spacer))}) .attr("y", 75) .attr("width", function(d){return(parseInt(d.End) - parseInt(d.Start))}) .attr("height", 50) .style("stroke", "rgb(255,0,0)") .style("stroke-width", 2) }); PendingIntent -

BroadCastReceiver

此外,您需要在接收器类中显示通知 -

public void scheduleNotification(Context context, long delay, int notificationId) {//delay is after how much time(in millis) from current time you want to schedule the notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentTitle(context.getString(R.string.title))
                .setContentText(context.getString(R.string.content))
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.app_icon)
                .setLargeIcon(((BitmapDrawable) context.getResources().getDrawable(R.drawable.app_icon)).getBitmap())
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

        Intent intent = new Intent(context, YourActivity.class);
        PendingIntent activity = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(activity);

        Notification notification = builder.build();

        Intent notificationIntent = new Intent(context, MyNotificationPublisher.class);
        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, notificationId);
        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        long futureInMillis = SystemClock.elapsedRealtime() + delay;
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    }

最后,使用适当的参数调用public class MyNotificationPublisher extends BroadcastReceiver { public static String NOTIFICATION_ID = "notification_id"; public static String NOTIFICATION = "notification"; @Override public void onReceive(final Context context, Intent intent) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = intent.getParcelableExtra(NOTIFICATION); int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0); notificationManager.notify(notificationId, notification); } } ,你就可以了!