我需要在特定日期收到通知。这是我到目前为止所做的。
这是我的主要活动。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, calendar.MAY);
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.DAY_OF_MONTH, 4);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 24);
calendar.set(Calendar.SECOND, 19);
Intent intent = new Intent(MainActivity.this, AlarmBroadcastReceiver.class);
PendingIntent pintent =
PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pintent);
}
}
这是我的接收器。
public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
notificationStatus(context);
}
/**
* To show notification for the alarm on time that is set as reminder
* @param context
*/
private void notificationStatus(Context context) {
final NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
final int icon = R.drawable.ic_launcher;
final CharSequence tickerText = context.getString(R.string.event);
final long when = System.currentTimeMillis();
final Notification notification = new Notification(
icon, "Happy Birthday", when);
final Intent notificationIntent = new Intent(
context.getApplicationContext(), MainActivity.class);
final PendingIntent contentIntent = PendingIntent.getActivity(
context.getApplicationContext(), 0, notificationIntent, 0);
notification.setLatestEventInfo(context, tickerText,
"Happy Birthday", contentIntent);
mNotificationManager.notify(1, notification);
}
}
一切正常。我会在需要时准确地收到通知,但每次打开应用程序时都会显示通知。我的代码中的问题是什么。
提前致谢。
答案 0 :(得分:0)
因为您已将notification
代代码放在应用程序的onCreate()方法中,所以每次打开activity
时都会调用它。所以制作一种创建notification
的方法,并在想要生成notification
时调用它。