我正在尝试创建一个应用,我在其中安排通知 但每当我尝试打开应用程序时,通知就会出现..... 它会在正确的时间出现,但也会在应用程序打开时出现。 这是代码............
主要活动.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.HOUR_OF_DAY,16);
Calendar_Object.set(Calendar.MINUTE,18);
Calendar_Object.set(Calendar.SECOND,00);
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,
0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar_Object.getTimeInMillis(),120000,pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, NotificationService.class);
context.startService(myIntent);
}
}
NotificationService.java
public class NotificationService extends Service {
private NotificationManager mManager;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@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);
@SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.images,
"xys", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_ONE_SHOT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(),
"xyz", "abcd",
pendingNotificationIntent);
notification.flags|= Notification.FLAG_AUTO_CANCEL;
mManager.notify(0, notification);
stopSelf();
}
答案 0 :(得分:0)
警报再次触发,因为在通知您正在调用您再次设置警报的MainActivity。尝试在不同的活动中设置闹钟。如果活动在通知后开始,则阻止警报设置。