我正在尝试创建一个简单的应用程序,以每天在特定时间发出通知,但是不知何故,它在所有代码中均不返回错误:
按下通知后开始通知的按钮:
setRenider.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,18);
calendar.set(Calendar.MINUTE,14);
calendar.set(Calendar.SECOND,0);
Intent intent = new Intent(getApplicationContext(),Notification_reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
});
然后这是通知类:
public class Notification_reciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context,ReaptingActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_free_breakfast_black_24dp)
.setContentTitle("Water Time").setContentText("Drink Water").setAutoCancel(true);
notificationManager.notify(100,builder.build());
}
}
,然后创建一个简单的空活动,命名为ReaptingActivity 然后在清单中输入这些代码:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
<receiver android:name=".Notification_reciever"/>
</application>
基于我遵循的教程,它应该可以运行,但是还没有。请注意,我输入的时间是正确的,但没有任何通知!!!
答案 0 :(得分:0)
我只需要它在通知类onRecieve方法上添加一个频道。这是我创建频道的方式:
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
然后在通知兼容性构建器上,我需要它来传递频道
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)