没有收到关于未来时间的通知

Not getting notification on future time

即使用户关闭应用程序,我也想向用户显示通知。但是我没有收到未来时间的通知,就像我想每天在特定时间通知用户一样。

    **Here what i have tried**

    >  Calendar c = Calendar.getInstance(); 
       int hour = c.get(Calendar.HOUR_OF_DAY);

       Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
if(hour == 18) {
       pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

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

** Here is my service 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")
   @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 设置 Repeating。

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
        
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*10, pendingIntent);

是否要停止闹钟

public void stopAlarmManager()
{          
    if(alarmManager != null)
       alarmManager.cancel(pendingIntent);
}

记住不要忘记在清单文件中注册 Receiver

<receiver android:name=".AlarmBroadcastReceiver" >
        </receiver>

这对你有帮助。