我尝试制作一个在特定时间显示Notification
的项目,即使应用程序未打开也会显示。但它在特定时间以及在给定时间之后显示消息。此外,当应用关闭时,Notification
无效。
如何在给定时间后永久停止并在后台运行?
代码如下。
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);
}
接收器已添加到清单。
答案 0 :(得分: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);