2016-09-15 71 views
-1

我試圖做一個項目,將在特定時間顯示Notification甚至應用程序未打開它會顯示它。但它在特定時間和特定時間之後顯示消息。此外,應用程序關閉時Notification不起作用。如何使用AlarmManager創建提醒?

如何在給定時間後永久停止並在後臺運行?

代碼如下。

private PendingIntent pendingIntent; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Calendar calendar = Calendar.getInstance(); 

    calendar.set(Calendar.MONTH, Calendar.SEPTEMBER); 
    //calendar.set(Calendar.YEAR, 2016); 
    calendar.set(Calendar.DAY_OF_MONTH, 15); 

    calendar.set(Calendar.HOUR_OF_DAY, 14); 
    calendar.set(Calendar.MINUTE, 24); 
    calendar.set(Calendar.SECOND, 05); 
    //calendar.set(Calendar.AM_PM,Calendar.PM); 

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

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

    Intent into = new Intent(this, AlarmReceiver.class); 
    PendingIntent ppendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1253, into, 0); 
    AlarmManager alarmManag = (AlarmManager) getSystemService(ALARM_SERVICE); 
    alarmManag.cancel(ppendingIntent); 
    ppendingIntent.(); 
} 

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

} 

Receiver已被添加到清單。

回答

0
Calendar calendar = Calendar.getInstance(); 

    calendar.set(Calendar.MONTH, Calendar.SEPTEMBER); 
    calendar.set(Calendar.DAY_OF_MONTH, 15); 
    calendar.set(Calendar.HOUR_OF_DAY, 14); 
    calendar.set(Calendar.MINUTE, 24); 
    calendar.set(Calendar.SECOND, 00); 


AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

final int id = (int) System.currentTimeMillis(); 
Intent intentAlarm = new Intent(this, AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT); 


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