【发布时间】:2015-06-04 13:48:09
【问题描述】:
我创建了一个在特定时间显示的通知,但问题是每次我关闭应用程序(在前缀时间之后)都会显示通知。我该如何解决这个问题?
这是我的代码: Home.class(是一个片段)
Calendar calend = Calendar.getInstance();
calend.setTimeInMillis(System.currentTimeMillis());
calend.set(Calendar.HOUR_OF_DAY, 9);
calend.set(Calendar.MINUTE, 27);
calend.set(Calendar.SECOND, 0);
Intent myIntent = new Intent(getActivity(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calend.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
MyReceiver.class
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
MyAlarmService.class
public class MyAlarmService extends Service
{
private NotificationManager mManager;
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
@SuppressWarnings({ "static-access", "deprecation" })
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
【问题讨论】:
-
请提供您放置上述代码的位置。
-
你实际上在
alarmManager.setRepeating上创建了一个Alarm,它会重复它。当警报在Service上运行时关闭应用程序时取消它 -
“我该如何解决这个问题?”:离开应用时取消闹钟。
-
如果我取消闹钟,通知将不会显示?例如,如果我将闹钟设置在上午 10 点,并且在我离开应用程序时取消闹钟,如果用户没有打开应用程序通知将在上午 10 点显示后的第二天?
-
@Slaiv206 :抱歉,您没有很好地解释您的问题。请进一步解释您的应用程序的功能、通知的用途、您期望发生的事情以及实际发生的事情。你所做的只是说你的通知在不应该显示的时候显示,并发布了一些标准代码来设置一个不告诉我们任何东西的警报。
标签: android android-notifications android-alarms android-calendar