简体   繁体   English

为什么当应用程序处于后台时声音不响(Android应用程序中的Firebase推送通知)?

[英]Why Sound is not ringing when app is in background(Firebase Push Notification in Android app)?

When push notification is coming then sound and vibration working only when app is open. 当推送通知到来时,声音和振动仅在打开应用程序时有效。 But when I kill my app or minimized it then only notification sound and vibrate coming if I send it from Firebase console. 但是,当我杀死我的应用程序或将其最小化时,如果我从Firebase控制台发送它,则只会发出通知声音和振动。 But if I am getting notification from php server then no sound and vibration.I have tired to many codes but same problem occur. 但是,如果我从php服务器收到通知,则没有声音和振动。我已经厌倦了很多代码,但同样会发生问题。 And I have also tried in different Android os versions phone. 而且我也尝试在不同的Android os版本的手机中使用。

This is my code which I am using to create notification. 这是我用来创建通知的代码。

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();
    }

}

And I have also given the permission in Manifest also. 我也已经在清单中给予了许可。

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

This is my php code. 这是我的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;
}

If you are sending notification from firebase console and your app is in background onMessageReceived method will not be called inside MessagingService class. 如果您是从Firebase控制台发送通知,而您的应用程序处于后台,则不会在MessagingService类内部调用onMessageReceived方法。

Firebase will handle it at Backend. Firebase将在后端处理它。 It will send this Notification to system for displaying Notification in Notification tray. 它将此通知发送到系统以在通知托盘中显示通知。 And there will be no Notification sound even if you have enabled/allowed Notification sound for. 即使已启用/允许了通知声音,也不会有通知声音。

Basically, you need to change your notifiction code to something like this 基本上,您需要将通知代码更改为如下所示

{

 “to” : “bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1…”,

 “notification” : {

    “body” : “great match!”,

    “title” : “Portugal vs. Denmark”,

    “icon” : “myicon”,

    “sound” : “mySound”

    }

} }

you can read more about how to do it here: Firebase Cloud Messaging Push Notifications Android tutorial 您可以在此处阅读有关操作的更多信息: Firebase Cloud Messaging推送通知Android教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当应用在后台时,Firebase推送通知不会播放声音 - Firebase Push notification is not playing sound when app is in background Android 仅当应用程序处于前台时才播放推送通知声音,但当应用程序处于后台时不播放声音 - Android Push notification sound is played only when app is in foreground but not playing sound when app is in background 应用程序在后台时,Android Firebase推送通知 - Android-Firebase Push Notification when app is in background Firebase 在 android 中从后台删除应用程序时未收到推送通知 - Firebase push notification not received when app remove from background in android Android:当应用未运行或在后台运行时,将Firebase推送通知保存到磁盘 - Android: saving a Firebase push notification to disk when the app is not running or in background 当应用程序在后台时更新Firebase推送通知 - Updating Firebase push notification when app is in background firebase 推送通知声音在 android 工作室中的 android 应用程序上不起作用 - firebase push notification sound not working on android app in android studio 当应用程序在Android TV上处于后台时推送通知 - Push notification when app is in the background on Android TV 推送通知声音未播放应用程序在后台 - Push notification sound is not playing app is in background 当应用程序在android中处于后台时,通知图标不可见(Gcm推送通知)? - Notification Icon not visible (Gcm Push notification) when app is in background in android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM