当应用程序关闭时,Android重复通知不起作用



我想每天在特定时间发送通知。打开应用程序时,代码正在工作。但当它关闭并删除时,通知不会显示。我已经使用了广播接收机和服务。代码如下所示。有人能帮忙解决这个问题吗。

清单文件

<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" />
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />

MyReceiver.java

public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent = new Intent(context, MyService.class);
context.startService(intent);
}}

MyService.java

public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotification();
return Service.START_STICKY;
}
private static final String NOTIFICATION_CHANNEL_ID = "Channel01";
private void createNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name =  preferences.getString("name", "User");
name = name.split(" ")[0];
String namee = "Remainder";
String description = "Remainder to update Wallet";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, namee, importance);
notificationChannel.setDescription(description);
Intent notifyIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, notifyIntent, 0);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("Remainder")
.setContentText("Hey " + name + ", Let's update your wallet")
.setSmallIcon(R.drawable.wallet)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.wallet_new))
.setContentIntent(pendingIntent)
.build();
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
// Issue the notification.
notificationManager.notify(1 , notification);
}
}}

活动.java

Intent notifyIntent = new Intent(getApplicationContext(), MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, notifyIntent, 0);
alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeMilli, timeInterval, pendingIntent);

您不应该使用应用程序的任何部分来实现这一点。服务、JobScheduler或Work Manager迟早会被系统终止,以防止电池耗尽。

在我看来,发送重复通知的最佳方式是使用由外部cron作业触发的firebase云消息(例如,firebase函数上的php(。

还要确保将通知发送到系统托盘,而不是发送到应用程序。为此,请使用FCM数据消息。即使服务未运行,数据消息也会传送到系统托盘并始终显示。

相关内容

  • 没有找到相关文章

最新更新