Android Studio - 如何安排通知?

发布于 2025-01-12 18:14:21 字数 4508 浏览 0 评论 0原文

我已在主活动的 onCreate 方法中使用此代码,为我当前正在处理的项目创建了示例通知。 我还有一个 TimePicker Fragment 类,顾名思义,它打开一个时间选择器对话框,允许用户设置一天中的特定时间。然后,小时分钟存储在DataSite.class中,其中包含许多 get 和 set 方法。下面是 TimePicker.class 的代码:

public class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        DataSite ds = new DataSite();
        ds.setHour(hourOfDay);
        ds.setMinute(minute);
    }
}

简而言之,我想根据小时安排 Main Activity 上的 createNotificationChannel(); 方法调用用户选择的分钟。正如我所说,时间信息存储在DataSite中。

我已经让时间选择器正常工作,并且通知按预期显示。我现在需要的只是一种将这两种功能结合起来的方法。据我从其他论坛帖子中得知,我将不得不使用警报管理器,但我在其他地方读到的任何内容都不适合我。

编辑:我尝试使用AlarmManager。下面您可以看到我目前拥有的完整代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_initial_screen);
        .
        .
        .
        .
        .
        Intent intent = new Intent(this, InitialScreen.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "reflectnotification")
                .setSmallIcon(R.drawable.app_icon_background)
                .setContentTitle("Reflect Reminder")
                .setContentText("Time to Reflect on your selected Goal!")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Time to Reflect on your selected Goal!"))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        createNotificationChannel();
//        notificationManager.notify(200, builder.build());

        hour = ((DataSite)getApplication()).getHour();
        minute = ((DataSite)getApplication()).getMinute();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);

        Toast.makeText(getApplicationContext(),"Picked time: "+ hour +":"+minute, Toast.LENGTH_LONG).show();

        alarmMgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        Intent intent2 = new Intent(getApplicationContext(), InitialScreen.class);
        alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 200, intent2, 0);

        alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
    }
    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Reflect Reminder";
            String description = "Time to Reflect on your selected Goal!";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("reflectnotification", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

I have created a sample notification for a project I am currently working on, using this code in the onCreate method of my Main Activity.
I have also got a TimePicker Fragment class, which as the name suggests, opens up a time picker dialogue which allows the user to set a specific time of day. Then, the hour and minutes are stored in DataSite.class, which holds a number of get and set methods. Below is the code for TimePicker.class:

public class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        DataSite ds = new DataSite();
        ds.setHour(hourOfDay);
        ds.setMinute(minute);
    }
}

In short, I would like to schedule the createNotificationChannel(); method call on the Main Activity, according to the hour and minutes the user has selected. As I said, the time information is stored in DataSite.

I have gotten the time picker working, and the notification shows as expected. All that I need now is a way to combine these two functionalities. As far as I can tell from other forum posts, I will have to use the Alarm Manager, but nothing I have read elsewhere works for me.

Edit: I have attempted to utilize the AlarmManager. Below you can see the full code I currently have so far:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_initial_screen);
        .
        .
        .
        .
        .
        Intent intent = new Intent(this, InitialScreen.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "reflectnotification")
                .setSmallIcon(R.drawable.app_icon_background)
                .setContentTitle("Reflect Reminder")
                .setContentText("Time to Reflect on your selected Goal!")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Time to Reflect on your selected Goal!"))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        createNotificationChannel();
//        notificationManager.notify(200, builder.build());

        hour = ((DataSite)getApplication()).getHour();
        minute = ((DataSite)getApplication()).getMinute();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);

        Toast.makeText(getApplicationContext(),"Picked time: "+ hour +":"+minute, Toast.LENGTH_LONG).show();

        alarmMgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        Intent intent2 = new Intent(getApplicationContext(), InitialScreen.class);
        alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 200, intent2, 0);

        alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
    }
    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Reflect Reminder";
            String description = "Time to Reflect on your selected Goal!";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("reflectnotification", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如果需要发送通知的确切时间,您将需要使用 AlarmManager。请参阅 https://developer.android.com/training/scheduling/alarms

文档描述何时使用 AlarmManager 与其他 API:https://developer.android.com/guide/background#alarms

If there is an exact time that the notification needs to be sent, you will want to use AlarmManager. See https://developer.android.com/training/scheduling/alarms

The docs describe when to use AlarmManager vs. other APIs: https://developer.android.com/guide/background#alarms

别闹i 2025-01-19 18:14:21

好吧,经过太多的研究和斗争,我终于做到了
注意:这适用于Android O+版本
在 Activity 类

button.setOnClickListener(view -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Calendar calendar = Calendar.getInstance();
            //10 is for how many seconds from now you want to schedule also you can create a custom instance of Callender to set on exact time
            calendar.add(Calendar.SECOND, 10);
            //function for Creating [Notification Channel][1]
            createNotificationChannel();
            //function for scheduling the notification
            scheduleotification(calendar);
        }
    });

代码 createNotificationChannel()

@RequiresApi(api = Build.VERSION_CODES.O)
public void createNotificationChannel() {
    String id = "channelID";
    String name = "Daily Alerts";
    String des = "Channel Description A Brief";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    NotificationChannel channel = new NotificationChannel(id, name, importance);
    channel.setDescription(des);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
}

代码 ScheduleNotification(Calender calendar);

@RequiresApi(api = Build.VERSION_CODES.M)
public void scheduleNotification(Calendar calendar) {
    Intent intent = new Intent(getApplicationContext(), Notification.class);
    intent.putExtra("titleExtra", "Dynamic Title");
    intent.putExtra("textExtra", "Dynamic Text Body");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    Toast.makeText(getApplicationContext(), "Scheduled ", Toast.LENGTH_LONG).show();
}

通知.kt

    class Notification : BroadcastReceiver() 
{
    override fun onReceive(context: Context, intent: Intent) {
        message = intent.getStringExtra("textExtra").toString()
        title = intent.getStringExtra("titleExtra").toString()
        val notification =
            NotificationCompat.Builder(context, channelID).setSmallIcon(R.drawable.notification)
                .setContentText(message).setContentTitle(title).build()
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(notificationId, notification)
    }
}

Okay After too much research and fighting with this finally I did it
Note: this is suitable for Android O+ Versions
In Activity Class

button.setOnClickListener(view -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Calendar calendar = Calendar.getInstance();
            //10 is for how many seconds from now you want to schedule also you can create a custom instance of Callender to set on exact time
            calendar.add(Calendar.SECOND, 10);
            //function for Creating [Notification Channel][1]
            createNotificationChannel();
            //function for scheduling the notification
            scheduleotification(calendar);
        }
    });

code for createNotificationChannel()

@RequiresApi(api = Build.VERSION_CODES.O)
public void createNotificationChannel() {
    String id = "channelID";
    String name = "Daily Alerts";
    String des = "Channel Description A Brief";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    NotificationChannel channel = new NotificationChannel(id, name, importance);
    channel.setDescription(des);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
}

code for scheduleNotification(Calender calendar);

@RequiresApi(api = Build.VERSION_CODES.M)
public void scheduleNotification(Calendar calendar) {
    Intent intent = new Intent(getApplicationContext(), Notification.class);
    intent.putExtra("titleExtra", "Dynamic Title");
    intent.putExtra("textExtra", "Dynamic Text Body");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    Toast.makeText(getApplicationContext(), "Scheduled ", Toast.LENGTH_LONG).show();
}

Notification.kt

    class Notification : BroadcastReceiver() 
{
    override fun onReceive(context: Context, intent: Intent) {
        message = intent.getStringExtra("textExtra").toString()
        title = intent.getStringExtra("titleExtra").toString()
        val notification =
            NotificationCompat.Builder(context, channelID).setSmallIcon(R.drawable.notification)
                .setContentText(message).setContentTitle(title).build()
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(notificationId, notification)
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文