简体   繁体   English

利用AlarmManager触发通知

[英]Utilizing AlarmManager to trigger Notification

Im trying to create a part of a fitness application that will remind a user to do their daily exercises at a chosen time. 我试图创建健身应用程序的一部分,该应用程序会提醒用户在选定的时间进行日常锻炼。 This is utilising the AlarmManager to create a daily alarm which will create a notification that will appear at the chosen time. 这是利用AlarmManager创建每日警报,该警报将创建一个在选定时间显示的通知。

When the alarm time comes, no notification comes through. 当警报时间到来时,没有通知通过。 I've tested the notification, and it will appear if placed on the action click of a button. 我已经测试了通知,如果将其放置在按钮的操作单击上,它将显示出来。

Should I be using extends BroadcastReceiver instead of extends Service ? 我应该使用扩展BroadcastReceiver而不是扩展Service吗?

Creating the alarm: 创建警报:

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 to create notification: 创建通知的类:

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);
    }
}

} }

According to official Android docs of Service component: 根据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. 服务是一种应用程序组件,代表应用程序执行长时间运行的操作而不与用户交互或提供功能供其他应用程序使用的愿望。

In your case, triggering a simple notification is not considered a long-running operation, so you should use BroadcastReceiver which is designed to run for a simple task at a specific conditions. 在您的情况下,触发简单通知不被认为是一项长时间运行的操作,因此您应使用BroadcastReceiver ,它旨在在特定条件下为简单任务运行。

To implement this using a BroadcastReceiver you should first change your service to a BroadcastReceiver : 要使用BroadcastReceiver实现此功能,您应该首先将服务更改为BroadcastReceiver

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

Then pass your receiver to AlarmManager like this: 然后像这样将您的接收器传递给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);
   ...
}

Don't forget to declare your receiver in AndroidManifest.xml : 不要忘记在AndroidManifest.xml声明您的接收者:

<receiver android:name=".NotifyReceiver"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM