programing

장치에서 Firebase 클라우드 메시징 알림을 수신하지 않음

oldcodes 2023. 7. 8. 11:08
반응형

장치에서 Firebase 클라우드 메시징 알림을 수신하지 않음

장치에서 토큰을 가져와 Google FireBase 알림 콘솔을 통해 알림 테스트를 전송하는 FireBase Cloud Messaging에 문제가 있지만 알림이 Android 가상 장치에 기록되거나 푸시되지 않습니다.FCM에 대한 문서는 거의 정확하게 아래에 나와 있는 코드이며 파이어베이스에서 작동하는 푸시 알림을 받기 위해 수행해야 하는 다른 작업은 거의 없습니다.설명서에 명시된 모든 설정 정보(빌드.그래들 추가, 구글 플레이 서비스 설치 등)를 살펴보았지만 여전히 메시지가 생성되지 않습니다."I/FA: Tag Manager를 찾을 수 없으므로 사용할 수 없습니다."라는 알림을 누른 직후 일회성 오류가 발생하지만 출력되는 데이터는 이 오류뿐이며 Google에서 Tag Manager 요구 사항 및 FCM과 관련된 내용을 찾지 못했습니다.로그캣 또는 장치에 대한 푸시 알림을 받지 못하는 코드의 문제는 무엇입니까?도움이 될 만한 추가 정보가 있으면 알려주시기 바랍니다.감사해요.

알림Genie.java

public class NotificationGenie extends FirebaseMessagingService {

private static final String TAG = "Firebase_MSG";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO(developer): Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
    sendNotification(remoteMessage.getNotification().getBody());
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}

private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, PostLoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.tf2spyprofile)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}

Android Manifest.xml

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

<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".DashBoardActivity"
        android:label="@string/title_activity_dash_board"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity
        android:name=".NewOrderActivity"
        android:label="@string/title_activity_dash_board"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity
        android:name=".PostLoginActivity"
        android:label="@string/title_activity_dash_board"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>
</application>

<service
    android:name=".NotificationGenie">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

"Firebase Console에서 보낸 메시지를 받으려면 앱이 백그라운드에 있어야 하며 숨기지 않고 시작되어서는 안 됩니다." --- @Laurent Russier의 설명에 따르면.

앱을 백그라운드에 배치하기 전까지는 파이어베이스에서 메시지를 받은 적이 없습니다.

이것은 에뮬레이터에 대한 USB 연결에서만 해당되며 포그라운드에서도 알림이 표시됩니다.

응용 프로그램 태그 외부에 서비스를 배치했습니다.아래쪽을 이것으로 바꿔주세요.

<service
    android:name=".NotificationGenie">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

</application>

동일한 문제가 발생했으며 이 문제는 사용하도록 정의하고 서비스에서 true로 내보냄으로써 해결됩니다.

  <service
            android:name=".MyFirebaseMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

super.OnMessageReceived()오버라이드 방식으로.나한테 효과가 있었어요!드디어!

Firebase 클라우드 메시징이 장치에서 수신되지 않는 동일한 문제에 직면했습니다.

제 경우 Firebase Console Project에 정의된 패키지 이름이 Android Project의 Manifest & Gradle에 정의된 패키지 이름과 다릅니다.

그 결과 토큰은 정확하게 도착했지만 메시지는 전혀 오지 않았습니다.

요약하려면 Firebase Console 패키지 이름과 Manifest & Gradle이 일치해야 합니다.

또한 Firebase Console에서 보낸 메시지를 받으려면 앱이 백그라운드에 있어야 하며 숨김 없이 시작되어서는 안 됩니다.

저는 같은 문제에 직면했지만, 이전 GCM의 잔해가 여전히 제 매니페스트에 남아 있었습니다.매니페스트에서 다음 권한을 제거했을 때 오류.com.google.android.c2dm.permission을 수정했습니다.받다

저도 비슷한 문제가 있었지만, 저의 경우 Gradle 빌드에서 플러그인이 누락되었습니다(기존 프로젝트에 Firebase를 추가하고 있었습니다).

는 제 루트에 했습니다.build.gradle:

classpath 'com.google.gms:google-services:3.1.0'

그리고 다음은 내 끝까지.app - 준의 수의build.gradle:

apply plugin: 'com.google.gms.google-services'

그리고 나서 나는 다운로드해야 했습니다.google-services.jsonConsole에서 Google 프로젝트를 ).app디렉터리'입니다.

제 경우, 병합된 매니페스트에 수신기가 없다는 것을 알게 되었습니다.그래서 저는 다음을 포함해야 했습니다.

 <receiver
            android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
 </receiver>

앱에 한 지 되지 않은 , FCM을 추가한 경우,onTokenRefresh()호출되지 않습니다.저는 앱을 제거하고 다시 설치하여 실행할 수 있게 되었습니다.

이 문제에 대해 몇 시간을 소비한 후에 저는 마침내 "google-services.json"의 형식을 의도적으로 손상시켰을 때 문제를 깨달았고 제 빌드는 여전히 성공했습니다.IDE(Android Studio)에서 이 파일의 변경 내용을 인식하지 못합니다."디스크에서 다시 로드", Gradle 작업 "cleanBuildCache", 새 가상 장치, 앱 제거/재설치 등 여러 가지를 시도했지만 아무 것도 되지 않았습니다.

은 나게해결은에 .AndroidStudio -> Build -> Clean Project그리고.Build -> Rebuild Project

PS: 또한 "google-services.json"이 "app" 폴더에 있는지 확인합니다.

저 같은 경우에는 에뮬레이터에서 와이파이와 모바일 데이터를 켰는데 그게 매력적으로 작동했습니다.

장치 토큰을 복사할 때 공간이 복사될 수 있습니다. 올바른 토큰을 복사했는지 다시 확인하십시오.

아래 매니페스트 코드를 따라야 합니다(매니페스트에 서비스가 있어야 함).

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="soapusingretrofitvolley.firebase">
        <uses-permission android:name="android.permission.INTERNET"/>
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <service
                android:name=".MyFirebaseMessagingService">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                </intent-filter>
            </service>

            <service
                android:name=".MyFirebaseInstanceIDService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
                </intent-filter>
            </service>
        </application>

    </manifest>

저는 이 문제가 있었고, 제 코드를 확인했습니다.저는 여기서 언급된 모든 것을 고치려고 노력했습니다.마지막으로 문제는 너무 멍청했습니다.의 내장Sync꺼졌습니다. 그것이 제가 예상대로 알림을 받지 못한 유일한 이유였습니다.

enter image description here

private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    int requestCode = 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
    NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText(message)
            .setColor(getResources().getColor(R.color.colorPrimaryDark))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, noBuilder.build());
    <activity android:name=".activity.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!-- Firebase Notifications -->
    <service android:name=".service.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".service.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

저는 메시지를 받지 못하는 문제를 해결하지 못한 채 튜토리얼 영상뿐만 아니라 이 게시물 등을 모두 처리해 왔지만 등록 토큰은 효과가 있었습니다.

그때까지 저는 에뮬레이터에서만 앱을 테스트하고 있었습니다.실제 전화기에서 사용해 본 후 프로젝트에 대한 사전 변경 없이 즉시 작동했습니다.

앱이 24 버전 이상에서도 실행되기를 원하는 것처럼 다음을 참조하십시오.

1.strings.xml에 추가합니다.

< string name="default_notification_channel_id" 변환 가능="false"> fcm_default_channel

  1. 매니페스트 파일에 이 메타데이터를 추가합니다.

< 메타데이터 안드로이드:name="com.google.firebase.firebase.fire.default_notification_channel_id" 안드로이드:value="@string/default_notification_channel_id" />

3.알림(이미지 포함)을 생성하는 경우 알림을 처리하는 경우 이 방법을 사용합니다. 직접적인 경우 Firebase Messaging Service에 추가하거나 일부 util 클래스를 사용하는 경우 해당 util 클래스에 추가합니다.

   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static void createBigNotification(Bitmap bitmap, int icon, String message, Uri alarmSound) {
        final int NOTIFY_ID = 0; // ID of notification
        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
        String id = mContext.getString(R.string.default_notification_channel_id); // default_channel_id
        String title = mContext.getString(R.string.app_name);
        Intent intent;
        NotificationCompat.Builder builder;
        if (notificationManager == null) {
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        PendingIntent resultPendingIntent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, title, importance);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notificationManager.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(mContext, id);
            intent = new Intent(mContext, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
            bigPictureStyle.setBigContentTitle(title);
            bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
            bigPictureStyle.bigPicture(bitmap);

            builder.setContentTitle(title)        // required
                    .setSmallIcon(R.drawable.app_icon)   // required
                    .setContentText(message) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setSound(alarmSound)
                    .setStyle(bigPictureStyle)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setTicker(title)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {
            builder = new NotificationCompat.Builder(mContext, id);
            intent = new Intent(mContext, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
            bigPictureStyle.setBigContentTitle(title);
            bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
            bigPictureStyle.bigPicture(bitmap);

            builder.setContentTitle(title)     // required
                    .setSmallIcon(R.drawable.app_icon)   // required
                    .setContentText(message) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setSound(alarmSound)
                    .setStyle(bigPictureStyle)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setTicker(title)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_HIGH);
        }
        Notification notification = builder.build();
        notificationManager.notify(NOTIFY_ID, notification);
    }

다음 단계를 수행하면 알림 트레이에 알림이 표시됩니다.

저의 경우, 구글 플레이 서비스를 수동으로 종료하고 잊어버렸습니다.

나중에 장치를 다시 시작해야 하고, 그 후에는 아무런 문제 없이 알림을 받을 수 있습니다.

저는 안드로이드 APP에 대한 알림 전송을 설정하기 위해 파이어베이스 웹사이트에 따라 모든 단계를 수행했습니다.여러 번 시도해 보았지만, Virtue 기기나 물리 기기에 관계없이 알림이 수신되지 않습니다.가상 장치와 물리적 장치에서 일부 설정(설정 섹션의 알림 수신에 대한 설정)을 변경한 후 가상 장치와 물리적 장치 모두 알림을 받기 시작했습니다.

제가 수정해야 할 실수가 2개 있었고, 그 후 문제가 해결되었습니다.

공식 문서를 참조하면 서브스크립션 상태를 확인하는 데 도움이 되는 이 좋은 정보가 제공됩니다.

 Firebase.messaging.subscribeToTopic(TOPIC)
                    .addOnCompleteListener { task ->
                        var topicSubscriptionStatus = "Subscribed"
                        if (!task.isSuccessful) {
                            topicSubscriptionStatus = "Subscribe failed"
                        }
                        Log.d(TAG, topicSubscriptionStatus)
                        Toast.makeText(baseContext, topicSubscriptionStatus, Toast.LENGTH_SHORT).show()
                    }
  1. 내 토픽 이름은 올바른 "/timeout/"이 아니라 "/timeout/"입니다.이 문제를 해결한 직후 서비스에서 메시지 수신을 시작했습니다.

  2. 보류 중에 "FLAG_IMTUBLE" 플래그를 추가해야 했습니다.의도(S에서 이것이 필요하다고 언급된 로그캣의 오류)

(나는 티라미수)

앱 매니페스트에 추가 문서 확인 https://firebase.google.com/docs/cloud-messaging/android/receive

<service
android:name=".java.MyFirebaseMessagingService"
android:exported="false">
 <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
 </intent-filter>
</service>

아마도 연결에서 이더넷에서 무선으로 연결을 변경했기 때문일 것입니다. 다른 작업 없이 작동했습니다.

언급URL : https://stackoverflow.com/questions/37351354/firebase-cloud-messaging-notification-not-received-by-device

반응형