【问题标题】:Android Push notifications not working when app is closed关闭应用程序时Android推送通知不起作用
【发布时间】:2021-10-20 11:04:18
【问题描述】:

我正在使用OkSse 订阅我的服务器发送事件。

每当服务器发送新消息时,无论应用程序处于前台、最小化还是完全关闭,都应显示通知。

通知在最小化或在前台时按预期工作,但在完全关闭时,这仅适用于某些设备品牌

研究了bit,发现:

此问题仅在小米等制造商的手机上出现, Oppo、一加、Vivo、联想、华为、三星等。

即使应用关闭,WhatsApp, Facebook, Slack, Gmail, etc.. 如何显示通知?

我不使用FCM,只需订阅Sse

我也有清单:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver android:name="com.goparty.communication.NotificationsAlarmReceiver">
    <intent-filter>
        <action android:name="android.media.action.DISPLAY_NOTIFICATION" />
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

我怎样才能做到这一点?

更新

我设法通过使用 IntentServiceBroadcastReceiver 使其工作,但对于 Oreo 版本,这会崩溃。

在更多reading之后我发现JobIntentServiceIntentService在定位Android O及以上时的替换。

JobIntentService 的转换非常简单,但是当我关闭应用程序时,我的解决方案再次不起作用。

通知的全部目的是即使在应用关闭时也能正常工作。

使用IntentService 在后台通过发送broadcast 与我的服务的新意图工作。

我正在对 JobIntentService 做同样的事情,但没有运气。

这是我的代码:

public class NotificationService extends JobIntentService {

    private static final int JOB_ID = 1;
    private NotificationManager notificationManager;

    public static void enqueueWork(Context context, Intent intent) {
        enqueueWork(context, NotificationService.class, JOB_ID, intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.logGoParty(getClass().getSimpleName() + "#onCreate");
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.logGoParty("Running in background.");
        sendBroadcast(new Intent(getApplicationContext(), NotificationService.class));
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        Logger.logGoParty(getClass().getSimpleName() + "#onHandleWork");
        Logger.logGoParty("Sse initialized");

        Request request = new Request.Builder().url("the sse url").build();
        OkSse okSse = new OkSse();

        ServerSentEvent sse = okSse.newServerSentEvent(request, new ServerSentEvent.Listener() {
            @Override
            public void onOpen(ServerSentEvent sse, Response response) {
                Logger.logGoParty(response.toString());
            }

            @Override
            public void onMessage(ServerSentEvent sse, String id, String event, String message) {
                Logger.logGoParty("Sse#onMessage: " + message);
                try {
                    JSONObject promoJson = new JSONObject(message);

                    sendNotification(...);

                } catch (JSONException e) {
                    Logger.logGoParty("JSONException: " + e.toString());
                }
            }
                // ...
        });
    }

    private void sendNotification(String promoImageUrl, String notificationContent, String title) {

        try {
            URL url = new URL(promoImageUrl);
            Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());


            NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
            style.bigPicture(bitmap);

            Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            Intent intent = new Intent(this, MapsActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra("page-to-open", "promotions");
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);


            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, GoParty.PROMO_CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setContentTitle(title)
                    .setAutoCancel(true)
                    .setSound(defaultSound)
                    .setContentText(notificationContent)
                    .setContentIntent(pendingIntent)
                    .setStyle(style)
                    .setLargeIcon(bitmap)
                    .setWhen(System.currentTimeMillis())
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE);

            notificationManager.notify(0, notificationBuilder.build());

            Log.i("GoParty", "Notification sent ----- ");

        } catch (MalformedURLException e) {
            Logger.logGoParty(e.toString());
        } catch (IOException e) {
            Logger.logGoParty(e.toString());
        }
    }
}

通知接收者:

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent notificationIntent = new Intent(context, NotificationService.class);
        NotificationService.enqueueWork(context, notificationIntent);
    }
}

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.goparty">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />


    <application
        android:name=".scopes.application.GoParty"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"
            android:screenOrientation="portrait">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.goparty.LoginActivity" />
        </activity>

        <service
            android:name=".jobs.NotificationService"
            android:permission="android.permission.BIND_JOB_SERVICE" />

        <receiver android:name=".receivers.NotificationReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

【问题讨论】:

  • 在android 6.0之后你应该使用NotificAION CHANNAL来获取pushnotification
  • 可以参考服务器端代码吗?
  • @MuhaiminurRahman 用代码更新问题。
  • WhatsApp、Facebook、Slack、Gmail 都使用 FCM 服务(Firebasemessagingservice)
  • 试着把你的问题分成两部分。首先确保您的 NotificationReceivers onReceive() 被调用(例如,将日志放在那里)。如果是,那么问题出在你的 NotificationService,如果不是,那么你需要调查 NotificationReceiver。

标签: android push-notification android-8.0-oreo server-sent-events


【解决方案1】:

这背后的主要原因是自动启动和电池优化 (MIUI) 设备尝试在电池设置中为您的应用更改不优化选项

 private void initOPPO() {
        try {

            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.floatwindow.FloatWindowListActivity"));
            startActivity(i);
        } catch (Exception e) {
            e.printStackTrace();
            try {

                Intent intent = new Intent("action.coloros.safecenter.FloatWindowListActivity");
                intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.floatwindow.FloatWindowListActivity"));
                startActivity(intent);
            } catch (Exception ee) {

                ee.printStackTrace();
                try {

                    Intent i = new Intent("com.coloros.safecenter");
                    i.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.sysfloatwindow.FloatWindowListActivity"));
                    startActivity(i);
                } catch (Exception e1) {

                    e1.printStackTrace();
                }
            }

        }
    }

    private static void autoLaunchVivo(Context context) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.iqoo.secure",
                    "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"));
            context.startActivity(intent);
        } catch (Exception e) {
            try {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.vivo.permissionmanager",
                        "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
                context.startActivity(intent);
            } catch (Exception ex) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.iqoo.secure",
                            "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager");
                    context.startActivity(intent);
                } catch (Exception exx) {
                    ex.printStackTrace();
                }
            }
        }
    }

用法

if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
                                initOPPO();
                            } else if (Build.MANUFACTURER.equalsIgnoreCase("vivo")) {
                                autoLaunchVivo(BaseSettingActivity.this);
                            } else if (Build.MANUFACTURER.equalsIgnoreCase("xiaomi")) {
                                try {
                                    Intent intent = new Intent();
                                    intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                                    startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

【讨论】:

  • 你能详细说明你的答案吗?
  • 转到设置>电池优化>选择你的应用>然后点击不优化/自动启动如果这解决了你的问题那么你需要使用这个代码进行相同的重定向
【解决方案2】:

您的方法:使用 OkSse 进行通知意味着需要一直运行后台服务。

问题一:Android后台服务限制link

JobIntentService 在内部将使用 JobService,它不会是一个继续运行的服务。它不会无动于衷地运行,因为将适用执行时间限制。它将停止并重新安排以稍后继续执行。所以在你的情况下,它不起作用。

问题 2:小米、OPPO、一加、Vivo、联想、华为、三星等设备都有电池优化检查,导致 JobIntentService 停止。

解决办法:

1) 运行丑陋的前台服务,不推荐

2) Firebase 高优先级通知link 强烈推荐

我已经在上面提到的设备上实现了它,即使应用程序设置为电池优化模式你也会收到通知。

【讨论】:

  • 所以如果我们想要这个功能,我们一定要使用 Firebase 吗?太烂了!
猜你喜欢
  • 1970-01-01
  • 2016-11-19
  • 2022-01-13
  • 2021-03-08
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多