我试图让我的应用程序定期发送通知(下面的代码设置为30秒进行测试,但我会将其更改为每月工作一次)。
我正在跟踪另一篇文章的代码。
代码运行时没有错误,但没有发送任何通知。有人能告诉我为什么这不管用吗?
下面是我的活动代码(REQUEST_CODE设置为0):
private void handleNotification() {
Log.d(TAG, "jjjj3: " + "one" );
Intent intent = new Intent(HomePage.this, ClassReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(HomePage.this, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(alarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30 * 1000, pendingIntent);
Log.d(TAG, "jjjj4: " + "two" );
}
这是我的接受者课:
public class ClassReciever extends BroadcastReceiver {
private static final String TAG = "Receiver";
@Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
public void showNotification(Context context) {
int reqCode = 0;
Log.d(TAG, "jjjj5: " + "three" );
Intent intent = new Intent(context, AddBudget.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, reqCode, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon2)
.setContentTitle("Title")
.setContentText("Some text");
builder.setContentIntent(pendingIntent);
builder.setDefaults(Notification.DEFAULT_SOUND);
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(reqCode, builder.build());
Log.d(TAG, "jjjj6: " + "four" );
}
}
清单:
<receiver android:name= ".ClassReciever" />
</application>
发布于 2021-05-18 06:43:06
你的密码没问题。这并没有什么问题。但是,如果您想以Android 8.0
及以上的设备(即API 26+
)为目标设备,则必须在传递通知之前创建通知通道。
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.channel_name) // this will be displayed in app settings name it wisely
val descriptionText = getString(R.string.channel_description) // this will be displayed in app settings name it wisely
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
创建通道后,请使用该CHANNEL_ID
来传递通知,如下所示:
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true)
有关此代码或java代码的更多信息,请检查此创建通知。
https://stackoverflow.com/questions/67538657
复制相似问题