Почему звук не звонит, когда приложение находится в фоновом режиме (Push-уведомление Firebase в приложении Android)? - PullRequest
0 голосов
/ 02 июля 2019

Когда приходит push-уведомление, звук и вибрация работают только при открытом приложении. Но когда я убиваю свое приложение или сворачиваю его, тогда только звук уведомления и вибрация приходят, если я отправляю его из консоли Firebase. Но если я получаю уведомление от php-сервера, то нет звука и вибрации. Я устал от многих кодов, но возникает та же проблема. И я также пробовал в разных версиях Android OS телефона.

Это мой код, который я использую для создания уведомления.

public void createNotification( String title, String message,Intent intent, Uri alarmSound) 
{
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel androidChannel = new NotificationChannel(CHANNEL_ID,
                title, NotificationManager.IMPORTANCE_HIGH);
        // Sets whether notifications posted to this channel should display notification lights
        androidChannel.enableLights(true);
        // Sets whether notification posted to this channel should vibrate.
        androidChannel.enableVibration(true);
        // Sets the notification light color for notifications posted to this channel
        androidChannel.setLightColor(R.color.app_theme_color);
        //androidChannel.setSound(null, null);

        // Sets whether notifications posted to this channel appear on the lockscreen or not
        androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        getManager().createNotificationChannel(androidChannel);

        NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                .setSmallIcon(R.mipmap.logo)
                .setContentTitle(title)
                .setContentText(message)
                .setTicker(title)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setSound(defaultUri)
                .setSound(alarmSound, STREAM_NOTIFICATION)
                .setAutoCancel(true)
                .setContentIntent(contentIntent);

        getManager().notify(NOTIFICATION_ID, notification.build());

    } else {
        try {

            playNotificationSound();

            @SuppressLint({"NewApi", "LocalSuppress"}) NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.logo))
                    .setSmallIcon(R.mipmap.logo)
                    .setContentTitle(title)
                    .setTicker(title)
                    .setContentText(message)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                    .setContentIntent(contentIntent)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setSound(alarmSound, STREAM_NOTIFICATION)
                    .setLights(0xFF760193, 300, 1000)
                    .setAutoCancel(true)
                    .setVibrate(new long[]{200, 400});


            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(NOTIFICATION_ID/* ID of notification */, notificationBuilder.build());

        } catch (SecurityException se) {
            se.printStackTrace();
        }
    }
}


private NotificationManager getManager() {
    if (mManager == null) {
        mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }
    return mManager;
}



// Playing notification sound
public void playNotificationSound() {
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

И я также дал разрешение в Манифесте.

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

Это мой php код.

public function pushSurveyorNotification($send_data){

    $requestJson = json_decode($send_data, true);

    if (empty($requestJson)) {
        generateServerResponse('0', '100');
    }

     $check_request_keys = array(
                '0' => 'message',
                '1' => 'regId',
                '2' => 'apikey',
                '3' => 'booking_details',
                '4' => 'notification_type'
            );

       // $notification_type  = '01';           
        $regId = trim($requestJson['Codruk']['regId']);
        $notification_type = trim($requestJson['Codruk']['notification_type']);
        $registrationId = ''; // set variable as array

        // get all ids in while loop and insert it into $regIDS array
        $deviceIds = explode(",", $regId);

        foreach ($deviceIds as  $devid) { 
            $registrationId .= $devid.",";
        }

        $message  = trim($requestJson['Codruk']['message']);            
        $apikey   = trim($requestJson['Codruk']['apikey']);
        $booking_details  = trim($requestJson['Codruk']['booking_details']);

        $url = 'https://android.googleapis.com/gcm/send'; 

        $fields = array(
                        'to'  => rtrim($registrationId,","),

                        'notification' => array(
                                "title" => "Codruk",
                                "body"  => $message
                        ),
                        'data' => array(
                            "notification_type" => $notification_type,
                            "booking_details" =>json_decode($booking_details, true)
                        ),
                        'priority' => "high"
                    ); 

        $headers = array( 
                            'Authorization: key=' . $apikey,
                            'Content-Type: application/json'
                        );

       $data = json_encode( $fields );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

        // Execute post
        $result = curl_exec($ch);

        // Close connection
        curl_close($ch);

        return $result;
}

1 Ответ

0 голосов
/ 02 июля 2019

Если вы отправляете уведомление с консоли Firebase и ваше приложение работает в фоновом режиме, метод onMessageReceived не будет вызываться внутри класса MessagingService.

Firebase будет обрабатывать его в Backend. Он отправит это Уведомление в систему для отображения Уведомления в области уведомлений. И не будет звука уведомлений, даже если вы включили / разрешили звук уведомлений для.

Обычно вам нужно изменить код уведомления на что-то вроде этого

{

 “to” : “bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1…”,

 “notification” : {

    “body” : “great match!”,

    “title” : “Portugal vs. Denmark”,

    “icon” : “myicon”,

    “sound” : “mySound”

    }

}

Подробнее о том, как это сделать, вы можете прочитать здесь: Пуш-уведомления для облачных сообщений Firebase. Учебник для Android

...