Nice programing

기기에서 Firebase 클라우드 메시징 알림을받지 못함

nicepro 2021. 1. 9. 11:36
반응형

기기에서 Firebase 클라우드 메시징 알림을받지 못함


장치에서 토큰을 받고 Google Firebase 알림 콘솔을 통해 알림 테스트를 보내는 FireBase 클라우드 메시징에 문제가 있지만 알림이 Android 가상 장치에 기록되거나 푸시되지 않습니다. FCM에 대한 문서는 아래에있는 코드와 거의 동일하며, firebase에서 푸시 알림을 받기 위해 수행해야하는 다른 작업은 거의 없습니다. 설명서에 지정된대로 모든 설정 정보 (build.gradle 추가, Google Play 서비스 설치 등)를 검토했지만 여전히 메시지가 생성되지 않습니다. 'I / FA : 태그 관리자를 찾을 수 없으므로 사용할 수 없습니다'라는 알림을 푸시 한 직후 일회성 오류가 표시됩니다. 그러나 이것이 출력되는 유일한 데이터이며 Google에서 태그 관리자 요구 사항 및 FCM과 관련된 것을 찾지 못했습니다. logcat 또는 장치로 푸시 알림을받지 못한다는 코드에 어떤 문제가 있습니까? 도움이 될만한 추가 정보가 있으면 알려주세요. 감사.

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

}

AndroidManifest.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>


애플리케이션 태그 외부에 서비스를 배치했습니다. 하단을 이것으로 변경하십시오.

<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>

"또한 Firebase 콘솔에서 보낸 메시지를 받으려면 앱이 백그라운드에 있어야하며 시작되지도 않고 숨겨져도 안됩니다." --- @Laurent Russier의 의견에 따르면.

앱을 백그라운드로 전환 할 때까지 Firebase에서 메시지를받지 못했습니다.

이것은 에뮬레이터의 USB 연결에서만 적용되며 전경에서도 알림을받습니다.


super.OnMessageReceived()Overriden 메서드를 호출 합니다. 이것은 나를 위해 일했습니다! 드디어!


기기에서 수신하지 못하는 Firebase 클라우드 메시징과 동일한 문제에 직면했습니다.

제 경우에는 Firebase 콘솔 프로젝트에 정의 된 패키지 이름이 Android 프로젝트의 Manifest 및 Gradle에 정의 된 이름과 다릅니다.

결과적으로 토큰을 올바르게 받았지만 메시지가 전혀 없습니다.

요약하자면 Firebase 콘솔 패키지 이름과 Manifest 및 Gradle이 반드시 일치해야합니다.

또한 Firebase 콘솔에서 보낸 메시지를 받으려면 앱이 백그라운드에 있어야하며 시작되거나 숨겨져 있지 않아야합니다.


나는 같은 문제에 직면했지만 이전 GCM의 매니페스트에 여전히 파편이 남아있었습니다. 내 매니페스트에서 다음 권한을 가져 왔을 때 오류가 수정되었습니다. com.google.android.c2dm.permission.RECEIVE


비슷한 문제가 있었지만 제 경우에는 Gradle 빌드에서 google-services플러그인 이 누락되었습니다 (기존 프로젝트에 Firebase를 추가했습니다).

내 루트에 다음을 추가했습니다 build.gradle.

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

그리고 내 app수준 의 끝에 다음이 있습니다 build.gradle.

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

그런 다음 google-services.jsonFirebase 콘솔에서 파일 을 다운로드하고 (원래 기존 Google Cloud 프로젝트를 가져 왔음) 내 app디렉토리에 복사해야했습니다 .


기존 앱에 FCM을 방금 추가 한 경우이 onTokenRefresh()호출되지 않습니다. 앱을 제거하고 다시 설치하여 실행했습니다.


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

 <?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>

    <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>

제 경우에는 mergedmanifest에 수신기가 없다는 것을 알았습니다. 그래서 다음을 포함해야했습니다.

 <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>

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

기기 토큰을 복사 할 때 공간을 복사 할 수 있습니다. 올바른 토큰을 복사했는지 다시 확인하세요.


나는 메시지를받지 못하는 문제를 해결하지 못한 채 튜토리얼 비디오뿐만 아니라이 전체 게시물과 다른 게시물을 통해 작업 해 왔지만 등록 토큰은 작동했습니다.

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


앱이 24 개가 넘는 버전에서도 실행되도록하려면 다음을 따르세요.

1. strings.xml에 추가하십시오.

<string name = "default_notification_channel_id"translatable = "false"> fcm_default_channel

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

<meta-data android : name = "com.google.firebase.messaging.default_notification_channel_id"android : value = "@ string / default_notification_channel_id"/>

3. 알림 (이미지 포함)을 생성하려면 알림을 처리하는이 메서드를 사용하고, 직접 firebasemessaging 서비스에 추가하거나 일부 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);
    }

다음 단계를 따르면 알림 트레이에 알림이 표시됩니다.


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

enter image description here


아마도 연결에서 이더넷에서 무선으로 연결을 변경했는데 다른 작업을 수행하지 않고도 작동했습니다.

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

반응형