我一直在研究如何在Android上显示通知,但我不知道为什么它根本不显示通知。
在主要活动的onCreate()中调用此方法
private void scheduleNotification(){
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, NotificationObject.class);
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Date date = new Date();
long timestamp = date.getTime();
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, timestamp + 5000, alarmPendingIntent);
}
这是我的通知对象
@Override
public void onReceive(Context context, Intent intent) {
createNotification(context, intent);
}
private void createNotification(Context context, Intent fromIntent) {
NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Weather Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
nm.createNotificationChannel(notificationChannel);
}
Log.d("NOTIFICATION", "I'm in notification");
WeatherApiCall weatherApiCall = new WeatherApiCall();
String weatherInfo = weatherApiCall.getWeatherInfo("weather", "Iasi,ro", "metric");
String temperatureText = null;
JSONObject weatherApiResult;
try {
weatherApiResult = new JSONObject(weatherInfo);
temperatureText = "Temperature: " + weatherApiResult.getJSONObject("main").getDouble("temp") + " \u00B0C";
Log.d("NOTIFICATION", temperatureText);
} catch (JSONException e) {
e.printStackTrace();
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.sun)
.setWhen(System.currentTimeMillis())
.setContentTitle(temperatureText)
.setContentText(temperatureText)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
nm.notify(NOTIFICATION_ID, notificationBuilder.build());
}