在用户定义的时间显示多个通知

时间:2016-08-28 18:20:06

标签: android android-service android-notifications

我已经在Android上编程了一年多,但之前从未使用过通知,这是我的一个应用所需要的。

在应用程序中,可以在不同时间设置事件。显然,用户可以选择更改这些时间或添加/删除事件。

我计划在活动开始前5分钟使用通知来通知用户。

我已阅读了Building a NotificationServices的Android开发人员文档(我也是新手)。我决定使用Service,因为我认为即使应用程序没有运行,也需要显示通知。为了帮助我,我一直指的是一个特定的SO answer作为指导。

我开始尝试使用NotificationService类中的通知构建器类,如下所示:

public class NotificationService extends IntentService {

    private static final int NOTIFICATION_ID = 1;

    public NotificationService() {
        super(NotificationService.class.getSimpleName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        showNotification();
    }

    private void showNotification() {
        Intent intent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setContentTitle("Test notification")
                .setSmallIcon(R.drawable.ic_event_black_24dp)
                .setContentText("Test description")
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.build());
    }

}

我还使用以下内容在我的应用的启动画面中启动此Service

Intent serviceIntent = new Intent(this, NotificationService.class);
startService(serviceIntent);

要在特定时间显示通知,我主要通过SO questions like this one了解AlarmManager。我也知道要显示多个通知,我需要不同的通知ID(比如我的常量NOTIFICATION_ID)。

但是,我不确定的是动态更新每次添加,删除事件或更改时间时通知的显示时间。

有人可以就如何实现这一目标向我提供一些指导吗?

1 个答案:

答案 0 :(得分:0)

您实施通知部分。对于特定时间的通知用户,您应设置AlarmManager。我粘贴你需要的整个代码,然后解释每个部分:

public class AlarmReceiver extends WakefulBroadcastReceiver {

    AlarmManager mAlarmManager;
    PendingIntent mPendingIntent;

    @Override
    public void onReceive(Context context, Intent intent) {

        int mReceivedID = Integer.parseInt(intent.getStringExtra(AddReminderActivity.EXTRA_REMINDER_ID));

        // Get notification title from Reminder Database
        ReminderDatabase rb = new ReminderDatabase(context);
        ApiReminderModel reminder = rb.getReminder(mReceivedID);
        String mTitle = reminder.getName();

        // Create intent to open ReminderEditActivity on notification click

        // handling when you click on Notification what should happen
        Intent editIntent = YourActivity.createActivity(context, reminder.getChannelId(), reminder.getStartTime());
        PendingIntent mClick = PendingIntent.getActivity(context, mReceivedID, editIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        // Create Notification
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_logo))
                .setSmallIcon(R.drawable.ic_logo)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setTicker(mTitle)
                .setContentText(mTitle)
                .setContentIntent(mClick)
                .setSound(ringtoneUri)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true);

        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        nManager.notify(mReceivedID, mBuilder.build());
    }

    public void setAlarm(Context context, Calendar calendar, int ID) {
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        // Put Reminder ID in Intent Extra
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.putExtra(AddReminderActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
        mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        // Calculate notification time
        Calendar c = Calendar.getInstance();
        long currentTime = c.getTimeInMillis();
        long diffTime = calendar.getTimeInMillis() - currentTime;

        // Start alarm using notification time
        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, mPendingIntent);

        // Restart alarm if device is rebooted
        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }


    public void cancelAlarm(Context context, int ID) {
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        // Cancel Alarm using Reminder ID
        mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AlarmReceiver.class), 0);
        mAlarmManager.cancel(mPendingIntent);

        // Disable alarm
        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
}

如您所见,我们setAlarm会在特定时间通知用户。我还传递之前启动的日历实例(指定用户应该通知的时间)。

 Calendar mCalendar = Calendar.getInstance();
         mCalendar.add(Calendar.DAY_OF_YEAR, 7);// assume you want send notification 7 days later

        new AlarmReceiver().setAlarm(getApplicationContext(), mCalendar, id);

我们有另一种方法cancelAlarm。如果要删除Alaram,只需传递Alarm的唯一ID(已用于创建Alarm)。

不要忘记将此Service添加到您的AndroidManifest.xml

<receiver android:name=".service.AlarmReceiver" />

只剩下东西当您重启设备时,您应该再次设置AlarmsManager,这样您就需要BootRecivier服务。