0
我寫了一個應該顯示通知的代碼。我從TimePicker組件中選擇小時和分鐘(在給定時間每天彈出通知),然後爲Notification接收器創建一個意圖。數據庫用適當的信息進行更新,所有內容都使用AlarmManager進行設置。請求代碼(「代碼」變量)對於每個通知都是唯一的。我下面粘貼代碼片段:Android通知不顯示
SettingActivity類:
findViewById(R.id.buttonNotification).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
int hour, minute, id;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
calendar.set(Calendar.HOUR_OF_DAY,timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
Intent intent = new Intent(getApplicationContext(),Notifcation_receiver.class);
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
if(extra!=null){
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),extra.getInt("Code"),intent,PendingIntent.FLAG_UPDATE_CURRENT);
intent.putExtra("Code",extra.getInt("Code"));
db.updateNotification(hour,minute,extra.getInt("ID"));
}
else{
int code= Notification.getID();
intent.putExtra("Code",code);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),code,intent,PendingIntent.FLAG_UPDATE_CURRENT);
db.insertNotification(hour,minute);
}
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
startActivity(new Intent(SettingActivity.this, NotificationActivity.class));
}
});
}
通知接收器類:
public class Notifcation_receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int code = intent.getIntExtra("Code",0);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context,MainActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,code,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(false);
notificationManager.notify(code,builder.build());
}
}
我似乎無法找到問題,導致缺乏的計劃通知。感謝您的任何幫助。
你的targetSdkVersion是什麼?如果它大於25,則檢查此[問題](https://stackoverflow.com/questions/43093260/notification-not-showing-in-android-8-oreo/43093261)。 – Mehmed
在API 26(logcat日誌)上測試: 「E/NotificationService:找不到pkg = com.example.kuba.quizapp,channelId = null的通道」 –
感謝您提供一個好的提示! –