利用 AlarmManager 触发 Notification

Utilizing AlarmManager to trigger Notification

我正在尝试创建健身应用程序的一部分,提醒用户在选定的时间进行日常锻炼。这是利用 AlarmManager 创建一个每日警报,该警报将创建一个将在所选时间出现的通知。

当闹钟时间到来时,没有通知。我已经测试了通知,如果放置在按钮的操作上,它就会出现。

我应该使用 extends BroadcastReceiver 而不是 extends Service 吗?

正在创建闹钟:

public void SaveAlarm(View V) {

    Intent myIntent = new Intent(SetAlarm.this, NotifyService.class);
    AlarmManager mAlarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
    mPendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

    //Create Alarm Time in calendar
    Calendar mCalendar = Calendar.getInstance();
    mCalendar.setTimeInMillis(System.currentTimeMillis());
    mCalendar.set(Calendar.HOUR_OF_DAY, AlarmHour);
    mCalendar.set(Calendar.MINUTE, AlarmMinute);

    //Set alarm to repeat ever 24hrs
    mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, mPendingIntent);

    //Save Alarm to shared preferences
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("AlarmHour", AlarmHour);
    editor.putInt("AlarmMinute", AlarmMinute);
    editor.commit();

    //Notify user it's been saved
    Toast.makeText(this, "Alarm Saved", Toast.LENGTH_LONG).show();

    //Switch view
    Intent intent = new Intent(SetAlarm.this, Home.class);
    startActivity(intent);

}

Class 创建通知:

public class NotifyService extends Service {
@Override
public IBinder onBind(Intent Intent) {
    return null;
}

@Override
public void onCreate() {

    createNotificationChannel();

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "Workout")
            .setSmallIcon(R.drawable.common_google_signin_btn_text_light)
            .setContentTitle("Workout Time!")
            .setContentText("Time to do your daily workout.")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);


    notificationManager.notify(1, builder.build());
}

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 = "Workout";
        String description = "Workout";
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("Workout", 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);
    }
}

}

根据 Service 组件的官方 Android 文档:

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

在你的情况下,触发一个简单的通知不被认为是一个长时间的 运行ning 操作,所以你应该使用 BroadcastReceiver 设计用于 运行 的简单任务具体条件。

要使用 BroadcastReceiver 实现此功能,您应该首先将服务更改为 BroadcastReceiver:

public class NotifyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Notify user here
    }
}

然后像这样将接收器传递给 AlarmManager

public void SaveAlarm(View V) {
    Intent myIntent = new Intent(SetAlarm.this, NotifyReceiver.class);
    AlarmManager mAlarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
    mPendingIntent = PendingIntent.getBroadcast(SetAlarm.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
   ...
}

不要忘记在 AndroidManifest.xml:

中声明您的接收器
<receiver android:name=".NotifyReceiver"/>