Android应用关闭时重复通知不起作用

huangapple go评论95阅读模式
英文:

Android Repeated Notifications not working When App is Closed

问题

我想在特定时间每天发送通知当应用程序打开时代码可以正常工作但是当应用程序关闭并移除时通知不会显示我已经使用了广播接收器和服务来实现这个功能以下是代码

**Manifest 文件**

```xml
<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);
        }
    }
}

Activity.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);

<details>
<summary>英文:</summary>
I want to send notification everyday on a particular time. The code is working when the app is opened. But when it closed and remove, the notifications are not showing. I have used broadcast receiver and service to this. The code is given below. Can anyone help to clear this issue.
**Manifest File**
&lt;receiver
android:name=&quot;.MyReceiver&quot;
android:enabled=&quot;true&quot;
android:exported=&quot;true&quot; /&gt;
&lt;service
android:name=&quot;.MyService&quot;
android:enabled=&quot;true&quot;
android:exported=&quot;true&quot; /&gt;
**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 = &quot;Channel01&quot;;
private void createNotification() {
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name =  preferences.getString(&quot;name&quot;, &quot;User&quot;);
name = name.split(&quot; &quot;)[0];
String namee = &quot;Remainder&quot;;
String description = &quot;Remainder to update Wallet&quot;;
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(&quot;Remainder&quot;)
.setContentText(&quot;Hey &quot; + name + &quot;, Let&#39;s update your wallet&quot;)
.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);
}
}}
**Activity.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);
</details>
# 答案1
**得分**: 0
你不应该使用应用程序的任何部分来执行此操作。服务、JobScheduler 或 Work Manager 迟早会被系统杀死,以防止耗电。
在我看来,发送重复通知的最佳方法是使用触发外部定时任务的 Firebase Cloud Messaging(FCM)(例如在 Firebase Functions 上使用 PHP 的方式)。
还要确保将通知传递给**系统托盘,而不是应用程序**。为此,请使用 FCM 数据消息。数据消息将传递到系统托盘,并始终会显示 - 即使服务未运行。
<details>
<summary>英文:</summary>
You shouldn&#39;t use any part of application to do that. Services, JobScheduler, or Work Manager sooner or later will be killed by the system to prevent battery drain.
In my opinion the best way to send repeated notifications is to use firebase cloud messaging triggered with external cron job (e.g. php on firebase functions).
Also make sure to deliver the notification **to the system tray not to the application**. To do that use FCM DataMessages. Data messages are delivered to system tray and are always display - even if service is not running.
</details>

huangapple
  • 本文由 发表于 2020年9月26日 20:58:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64077956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定