Уведомление Android в определенное время, почему оно повторяется при каждом запуске приложения

Я хотел бы, чтобы приложение отправляло уведомление в определенное время дня, мне нужно использовать диспетчер тревог с уведомлением, как описано в этом руководстве.

Код работает хорошо и отправляет уведомление в указанное время, даже если приложение не запущено, однако уведомление отправляется также всякий раз, когда я запускаю приложение, что очень странно... ниже приведен код, спасибо за любую подсказку.

внутри onCreate() в MainActivity

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.MONTH, Calendar.MAY);
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.DAY_OF_MONTH, 27);

calendar.set(Calendar.HOUR_OF_DAY,10);
calendar.set(Calendar.MINUTE, 33);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.AM); 

Intent myIntent = new Intent(this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,0);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

MyReceiver.java

public class MyReceiver extends BroadcastReceiver
{

@Override
public void onReceive(Context context, Intent intent)
{
   Intent service1 = new Intent(context, MyAlarmService.class);
   context.startService(service1);

}

}

MyAlarmService

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"})
   @Override
   public void onStart(Intent intent, int startId)
   {

       mManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);




       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

      PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_ONE_SHOT);

      NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Today 27-5-2014")
            .setContentText(" You have your last final exam ")
            .setContentIntent(pendingNotificationIntent);


       mManager.notify(0, mBuilder.build());


    }

    @Override
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

}

РЕДАКТИРОВАТЬ:

обратите внимание, что мое требование - отправлять уведомления в определенное время, например, в 10:00 утра. Приведенный выше код успешно отправляет уведомление в 10:00 утра. Моя проблема заключается в том, что уведомление по-прежнему срабатывает при каждом запуске приложения, даже если если это не 10:00 утра

2 ответа

Попробуйте следующий код..

public class MainActivity extends Activity {

Calendar calendar;
private PendingIntent alarmIntent;

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

    calendar = Calendar.getInstance();
    Long time = new GregorianCalendar().getTimeInMillis()+60*06*24*1000;

    Intent intentAlarm = new Intent(this, AlarmReceiver.class);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmIntent=PendingIntent.getBroadcast(this, 1, intentAlarm, 0);

    alarmManager.set(AlarmManager.RTC_WAKEUP,time, alarmIntent);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),1000 * 60*60*24, alarmIntent);
}
}

AlarmReceiver.java

открытый класс AlarmReceiver extends BroadcastReceiver{

private static final int MY_NOTIFICATION_ID=1;
Intent in;
PendingIntent pendingIntent;
Notification mBuilder;

@Override
public void onReceive(Context context, Intent intent)
{
    in=new Intent(context,MainActivity.class);
    in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    pendingIntent=PendingIntent.getActivity(context, 0, in, 0);

    mBuilder=new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Your Title")
        .setContentText("Your Text")
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .build();

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

    mNotificationManager.notify(1, mBuilder);
    mNotificationManager.notify(MY_NOTIFICATION_ID, mBuilder);
}
}

Включите следующий код в файл манифеста

 <application>
    ....
    <receiver android:name=".AlarmReceiver"/> 
  </application>

Простое руководство по AlarmManager здесь...

Я попробовал код ниже, чтобы выдавать тревогу каждые 24 часа. Он работает нормально, но при первом запуске приложения вы увидите уведомление. Но позже он не выдаст уведомление при открытии приложения.

pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_NO_CREATE);

        boolean testval = (pendingIntent == null);

        if(testval)
        {
            pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

        }
Другие вопросы по тегам