0

我正在制作一个应用程序,我希望用户在共享首选项中指定时间,然后我将使用该时间来启动通知,无论他们是否在应用程序中,例如user-defined alarm notification.

我已经尝试了一切,但我不知道如何使它工作。如果首选项(复选框)为真,则通知应每天在该特定时间出现。

4

2 回答 2

4

在首选项中设置余数

    public static void setReminder(Context context,Class<?> cls,int hour, int min) {
        Calendar calendar = Calendar.getInstance();
        Calendar setcalendar = Calendar.getInstance();
        setcalendar.set(Calendar.HOUR_OF_DAY, hour);
        setcalendar.set(Calendar.MINUTE, min);
        setcalendar.set(Calendar.SECOND, 0);
        // cancel already scheduled reminders
        cancelReminder(context,cls);

        if(setcalendar.before(calendar))
            setcalendar.add(Calendar.DATE,1);

        // Enable a receiver
        ComponentName receiver = new ComponentName(context, cls);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 
                                     DAILY_REMINDER_REQUEST_CODE, intent1,           
                                      PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP,setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
 }

触发警报

public class AlarmReceiver extends BroadcastReceiver {

    String TAG = "AlarmReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        //Trigger the notification
        NotificationScheduler.showNotification(context, MainActivity.class,
                "You have 5 unwatched videos", "Watch them now?");
    }
}

显示通知

public static void showNotification(Context context,Class<?> cls,String title,String content)
    {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Intent notificationIntent = new Intent(context, cls);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(cls);
        stackBuilder.addNextIntent(notificationIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(
                     DAILY_REMINDER_REQUEST_CODE,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        Notification notification = builder.setContentTitle(title)
                .setContentText(content).setAutoCancel(true)
                .setSound(alarmSound).setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentIntent(pendingIntent).build();

        NotificationManager notificationManager = (NotificationManager) 
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(DAILY_REMINDER_REQUEST_CODE, notification);
    }

显示时间选择器对话框。

private void showTimePickerDialog(int h, int m) 
 {

    LayoutInflater inflater = getLayoutInflater();
    View view = inflater.inflate(R.layout.timepicker_header, null);

    TimePickerDialog builder = new TimePickerDialog(this, R.style.DialogTheme,
             new TimePickerDialog.OnTimeSetListener() {
             @Override
             public void onTimeSet(TimePicker timePicker, int hour, int min) {
                   Log.d(TAG, "onTimeSet: hour " + hour);
                   Log.d(TAG, "onTimeSet: min " + min);
                   localData.set_hour(hour);
                   localData.set_min(min);
                   tvTime.setText(getFormatedTime(hour,min));
                   NotificationScheduler.setReminder(MainActivity.this,AlarmReceiver.class,
                                                     localData.get_hour(),localData.get_min());
                }
            }, h, m, false);
        builder.setCustomTitle(view);
        builder.show();
    } 
于 2017-12-26T13:54:11.250 回答
0

最后我发现了如何做到这一点。对于任何可能需要相同的人,我将发布代码:

这是在适当的时候在活动中调用通知的方法:

 public void notifyAtTime() {
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    long time = sharedPref.getLong("Timepref", 0);
    SimpleDateFormat formatter = new SimpleDateFormat("HH", Locale.UK);
    SimpleDateFormat formatter1 = new SimpleDateFormat("mm", Locale.UK);

    Date date = new Date(time);
    Date date1 = new Date(time);
    long hour = Long.parseLong(formatter.format(date));
    long minute = Long.parseLong(formatter1.format(date1));

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
    notificationIntent.addCategory("android.intent.category.DEFAULT");

    PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, (int) hour);
    cal.set(Calendar.MINUTE, (int) minute);
    cal.set(Calendar.SECOND,0);
    if (alarmManager != null) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, broadcast);
    }
}

这是接收器

public class AlarmReceiver extends BroadcastReceiver {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
    Intent notificationIntent = new Intent(context, TicketActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(TicketActivity.class);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String ringer = sharedPreferences.getString("key_notifications_new_message_ringtone","");
    boolean vibrate = sharedPreferences.getBoolean("Vibrate",true);
    Uri ringtone = Uri.parse(ringer);

    Notification notification = builder.setContentTitle(context.getResources().getString(R.string.notific))
            .setContentText(context.getResources().getString(R.string.notific))
            .setTicker(context.getResources().getString(R.string.notific))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setSound(ringtone)
            .setContentIntent(pendingIntent).build();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (notificationManager != null) {
        notificationManager.notify(0, notification);
    }
}}
于 2017-12-27T19:18:45.950 回答