完整的场景是我试图根据用户选择的时间显示通知,我正在使用TimePickerDialog,BroadcastReceiver类和Service类,每个工作正常工作也会在特定时间出现,但问题是当我打开时每次收到通知时关闭应用程序.
Activity.java
Intent myIntent = new Intent(ReminderActivity.this, MyBreakfastReciver.class);
System.out.println("getting Breakfast Reminder");
pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, 0, myIntent,0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
//bTimePart1 and bTimePart2 is the time choosen by user through time picker
calendar.set(Calendar.HOUR_OF_DAY, bTimePart1 );
calendar.set(Calendar.MINUTE, bTimePart2);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
BroadcastReciever
public class MyBreakfastReciver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyBreakfastAlarmService.class);
context.startService(service1);
}
}
Reciever class
private void showNotification(Context context) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notificationlogo)
.setContentTitle("DietGuru")
.setAutoCancel(true)
.setContentText("You haven't logged your BreakFast for today.")
.setSubText("Would you like to do it now?");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, CalorieMainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(CalorieMainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_CANCEL_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
//mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setDefaults(Notification.DEFAULT_ALL);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(1, mBuilder.build());
}
我只想在打开和关闭应用程序时停止通知.