Невозможно получить push-уведомление Baidu в Android Pie - PullRequest
0 голосов
/ 13 июня 2019

Я реализовал Baidu push notifications в своем приложении для Android. Push-уведомления работали нормально до старых версий Android, независимо от того, запущено приложение или нет. Тем не менее, в Android Pie (Android-9) я могу получать push-уведомления только в приложении на переднем плане или в фоновом стеке.

Если приложение удаляется из фонового стека приложений, приложение не получает уведомления.

Я использую последнюю версию Baidu Push SDK, скачанную с: https://push.baidu.com/sdk/push_client_sdk_for_android

Я попробовал образец, присутствующий в официальном пакете Baidu Push SDK на Android Pie. Но я сталкиваюсь с той же проблемой. Если приложение находится в фоновом или фоновом стеке, мы получаем уведомление, в противном случае мы не получаем уведомление.

Ниже приведен мой класс получателя push-уведомлений:

public class BaiduPushReceiver extends PushMessageReceiver {

    Context mContext;
    public static final int NOTIFICATION_ID = 1;
    NotificationCompat.Builder builder;
    private NotificationManager mNotificationManager;

    @Override
    public void onBind(Context context, int errorCode, String appid,
                       String userId, String channelId, String requestId){
        Log.d("MY_APP","----*-*-*-*-*-* ChannelID:"+channelId+"*-*-*-*-*-------");
        Log.d("MY_APP","ErrorCode:"+errorCode+"  AppId:"+appid+"   UserId:"+userId+"  ChannelId:"+channelId+"  RequestId:"+requestId);

        SharedPreferencesManager.storeValue(SharedPreferencesManager.DEVICE_TOKEN, channelId);
    }
    private void sendNotification(String msgContent, Context context)
    {
        Bundle extra = new Bundle();
        extra.putString("message_data",msgContent);
        String message="";
        String type;
        String id;
        try{
            JSONObject jsob = new JSONObject(msgContent);
            String description = jsob.getString("description");
            jsob = new JSONObject(description);
            message = jsob.getString("message");
            type = jsob.getString("type");
            id = jsob.getString("id");
            Log.d("MY_APP","Message:"+message);
            Log.d("MY_APP","Type:"+type);
            Log.d("MY_APP","Id:"+id);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


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

        Intent intent;

        if(SharedPreferencesManager.isEmpty(SharedPreferencesManager.TOKEN))
            intent = new Intent(context, poiuy.class);
        else
            intent = new Intent(context, asdf.class);

        intent.putExtras(extra);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        try {
            message = java.net.URLDecoder.decode(message, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        //contentIntent.put("NotificationMessage", notificationMessage);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("MY_APP_CHANNEL_1", "my app Channel", NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setVibrationPattern(new long[]{500, 500, 500, 500});
            mNotificationManager.createNotificationChannel(notificationChannel);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,"MY_APP_CHANNEL_1")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(context.getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                    .setContentText(message)
                    .setVibrate(new long[]{500, 500, 500, 500})
                    .setSound(alarmSound)
                    .setAutoCancel(true)
                    .setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }
        else
        {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(context.getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                    .setContentText(message)
                    .setVibrate(new long[]{500, 500, 500, 500})
                    .setSound(alarmSound)
                    .setAutoCancel(true)
                    .setContentIntent(contentIntent);

            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }
    }
        @Override
    public void onUnbind(Context context, int i, String s) {

    }

    @Override
    public void onSetTags(Context context, int i, List<String> list, List<String> list1, String s) {

    }

    @Override
    public void onDelTags(Context context, int i, List<String> list, List<String> list1, String s) {

    }

    @Override
    public void onListTags(Context context, int i, List<String> list, String s) {

    }

    @Override
    public void onMessage(Context context, String s, String s1) {
        Log.d("MY_APP","OnMessage Called......"+"\nS="+s+"\ns1="+s1);
        sendNotification(s,context);
    }

    @Override
    public void onNotificationClicked(Context context, String s, String s1, String s2) {
        Log.d("BAIDU_PUSH","OnNotificationClicked called......");
    }

    @Override
    public void onNotificationArrived(Context context, String s, String s1, String s2) {
        Log.d("BAIDU_PUSH","onNotificationArrived called......");
    }
}

В приведенном выше коде сам метод обратного вызова onMessage(...) не вызывается, если приложение не запущено (передний план или фон).

P.S. обратите внимание, что это не относится к Notification Channels, который был введен в Oreo, так как я уже обрабатывал это в моем приложении, и то же самое обрабатывается и в образце Push SDK.

Любое исправление / обходной путь для решения этой проблемы в Android Oreo и Pie будет очень полезным.

Спасибо.

...