我有这种方法。问题是当我锁定手机时它不起作用。它只显示通知,如果手机屏幕打开,如果我阻止它,我只在5分钟后激活它(晚上9点,我在晚上9点05分把它打开),没有任何反应。我读过this个问题,但我不知道如何在特定时间启动它。提前致谢,请不要将此问题视为this问题
的副本public void startBroucast(int a,int b) {
int minutes=a;
int hours=b;
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR,hours);
c.add(Calendar.MINUTE,minutes);
Timer time = new Timer();
time.schedule(new TimerTask() {
@Override
public void run() {
showNotification();
}
},c.getTime());
}
答案 0 :(得分:0)
您应该使用AlarmManager来安排将来的任务。以下是您可以这样做的方法:
public void startBroucast(int minutes,int hours) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,hours);
c.set(Calendar.MINUTE,minutes);
long timeInMillis = c.getTimeInMillis();
Intent notificationIntent = new Intent(getContext(),NotificationReceiver.class);
mNotificationId = 123; //the id of the notification - you can use it to
//change the notification later
PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(getContext(),mNotificationId,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,timeInMillis,pendingNotificationIntent);
}
现在,您需要创建NotificationReceiver类。
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
createNotification(); //this is where you create and schedule your notification
}
}
您还需要在AndroidManifext.xml中注册BroadcastReceiver
<receiver
android:name=".util.NotificationReceiver"
android:enabled="true"
android:exported="false" />