android - 安排通知安卓

标签 android notifications alarmmanager

我见过一个简单的应用程序,可以在按下按钮 5 秒后安排通知。但我真正想做的是将通知安排到特定时间(例如通知显示在 00:00)但我真的不知道如何及时设置那个时刻(因为现在我正在使用“延迟”)。 这是代码:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_5:
            scheduleNotification(getNotification("5 second delay"), 5000);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void scheduleNotification(Notification notification, int delay) {

    Intent notificationIntent = new Intent(this, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long futureInMillis = SystemClock.elapsedRealtime() + delay;
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}

private Notification getNotification(String content) {
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle("Scheduled Notification");
    builder.setContentText(content);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    return builder.build();
}

}

和 NotificationPublisher 类

public class NotificationPublisher extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);

}
}

如果我知道如何安排通知以便每天 00:00 出现通知,那就更好了

最佳答案

我以前遇到过这个问题。因此,我很乐意为您提供帮助,这样您就不会像我一样浪费太多时间我会尽量做到简单明了。

  • 从系统中获取报警服务。
  • 做一个未决的 Intent ,传入广播接收器类的 姓名。
  • 制作一个日历对象并将其时间设置为上午 8 点。
  • 检查当前时间是否超过 8 点。如果是,则再添加一天
  • 调用AlarmManager类的set repeating方法。

相同的示例代码:

alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(context of current file, AlarmReceiver1.class); // AlarmReceiver1 = broadcast receiver

pendingIntent = PendingIntent.getBroadcast(  Menu.this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmIntent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
alarmManager.cancel(pendingIntent);

Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 8);
alarmStartTime.set(Calendar.MINUTE, 00);
alarmStartTime.set(Calendar.SECOND, 0);
if (now.after(alarmStartTime)) {
       Log.d("Hey","Added a day");
       alarmStartTime.add(Calendar.DATE, 1);
}

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("Alarm","Alarms set for everyday 8 am.");

来到广播接收器类。您需要在 list 中注册您的广播接收器。这将使您收到时钟事件。

覆盖此广播接收器的 onReceive 方法并在那里自己发出通知,或者制作一个单独的通知构建服务并在那里构建和显示您的通知。

list 代码 fragment :

<receiver android:name="AlarmReceiver1"  android:enabled="true">

广播接收器代码 fragment :

    public class AlarmReceiver1 extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
          Intent service1 = new Intent(context, NotificationService1.class);
      service1.setData((Uri.parse("custom://"+System.currentTimeMillis())));
                  context.startService(service1);
    }

通知构建服务代码 fragment :

    public class NotificationService1 extends IntentService{

        private NotificationManager notificationManager;
        private PendingIntent pendingIntent;
        private static int NOTIFICATION_ID = 1;
        Notification notification;
    @Override
        protected void onHandleIntent(Intent intent) {
    Context context = this.getApplicationContext();
               notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
     Intent mIntent = new Intent(this, Activity to be opened after clicking on the notif);
                Bundle bundle = new Bundle();
                bundle.putString("test", "test");
                mIntent.putExtras(bundle);
                pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);    

                Resources res = this.getResources();
                NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                notification = new NotificationCompat.Builder(this)
                            .setContentIntent(pendingIntent)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
                            .setTicker("ticker value")
                            .setAutoCancel(true)
                            .setPriority(8)
                            .setSound(soundUri)
                            .setContentTitle("Notif title")
                            .setContentText("Text").build();
                notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
                notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
                notification.ledARGB = 0xFFFFA500;
                notification.ledOnMS = 800;
                notification.ledOffMS = 1000;
                notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(NOTIFICATION_ID, notification);
                Log.i("notif","Notifications sent.");

        }

    }

有关代码的帮助可在此处获得:http://www.singhajit.com/schedule-local-notification-in-android/ 给你。就是这样。 希望这会有所帮助。

关于android - 安排通知安卓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163680/

相关文章:

java - AlarmManager 不会启动服务

java - 订阅和取消订阅每个发出的项目

java - 从 StringBuilder 中删除重复项

java - 向适配器添加新数据会影响初始值

android - 如何在 Android 中制作类似 "Notification"类的类?

Android,从远程服务器启动应用程序

c# - Xamarin.Android中如何获取AlarmManager系统服务

android - 2D 标记与 3D 对象 : How to optimize re-localizing with ADF using Google Tango?

ios - 使用 Firebase iOS Swift 将通知从特定设备推送到特定设备

android - 屏幕锁定后MediaPlayer无法播放声音