java使用alarm manager在特定时间发送通知
我试图通过使用报警管理器和待定意图在特定时间发送通知,但什么也没有显示! 请帮忙
这是密码
主要活动类
public class MainActivity extends Activity {
DatePicker dp;
TimePicker tp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dp=findViewById(R.id.datePicker1);
tp=findViewById(R.id.datePicker);
}
public void go(View b){
Calendar now = Calendar.getInstance();
Log.d("hello","date now "+now.getTimeInMillis()+"");
Calendar startTIme= Calendar.getInstance();
startTIme.set(dp.getYear(),dp.getMonth(),dp.getDayOfMonth(),tp.getCurrentHour(),tp.getCurrentMinute(),0);
Log.d("hello","date chosen "+startTIme.getTimeInMillis()+"");
int k= (int) (startTIme.getTimeInMillis()-now.getTimeInMillis());
Log.d("hello",k+"");
scheduleNotification(getNotification("5 second delay"),k);
}
private void scheduleNotification(Notification notification, int delay) {
Intent notificationIntent = new Intent(this, MyReceiver.class);
notificationIntent.putExtra(MyReceiver.NOTIFICATION_ID, 1);
notificationIntent.putExtra(MyReceiver.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Scheduled Notification");
builder.setContentText(content);
builder.setSmallIcon(R.drawable.ic_launcher_background);
return builder.build();
}
}
广播接收机类
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
我在清单文件中添加了接收者,但没有显示通知
共 (0) 个答案