Уведомления Firebase перестают работать на Android

Я прочитал много ответов об уведомлениях Firebase на Android, но ни один из них не решил мою проблему.

У меня есть приложение для Android с установленным Firebase, и проект Firebase создан и настроен. Зависимости включены в мой проект, и у меня есть служба, но я не получаю никаких уведомлений.

Код моей службы:

package es.angelcasas.meteoferrolterra;

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN",s);
        // Get updated InstanceID token.
        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.

        //TODO: Send Token to Server
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d("MENSAJE", "From: " + remoteMessage.getFrom());
        // Check if message contains a data payload.
    }
}

Мой AndroidManifest:

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

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

    <application
        android:allowBackup = "true"
        android:icon = "@drawable/icono"
        android:label = "@string/app_name"
        android:roundIcon = "@drawable/icono"
        android:supportsRtl = "true"
        android:theme = "@style/AppTheme">
        <activity
            android:name = ".MenuPrincipal"
            android:screenOrientation = "portrait">
            >
            <intent-filter>
                <action android:name = "android.intent.action.MAIN" />

                <category android:name = "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name = ".Noticias" />
        <activity
            android:name = ".Radares" />
        <activity
            android:name = ".BuscarActivity" />
        <activity android:name = ".Radar" />
        <activity android:name = ".Avisos"></activity>

        <!-- [START firebase_service] -->
        <service android:name = ".MyFirebaseMessagingService" android:stopWithTask = "false">
            <intent-filter>
                <action android:name = "com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <!-- [END firebase_service] -->
    </application>

</manifest>

Мой build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "es.angelcasas.meteoferrolterra"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-iid:17.0.4'
}

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

Я также скачал файл google-services.json.

Если я перейду в Cloud Messaging и отправлю новое уведомление, оно никогда не придет ...

Самое странное, что когда я попробовал этот урок:

https://thewikihow.com/video_u9vWzCC0JKU

Уведомления работают нормально, но затем они перестают работать, даже когда я перезапускаю весь проект ...

Любая помощь будет оценена по достоинству.

Заранее спасибо.

вы не создали никакого уведомления в методе onMessageReceived, в котором вы получаете push-уведомление

Ali Ahsan 11.01.2019 11:35
0
1
256
3

Ответы 3

Вы можете создать push-уведомление, используя следующий код. измените значения пары ключей на свои

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d("MENSAJE", "From: " + remoteMessage.getFrom());

    // Prepare Notification.
    ShowNotification(remoteMessage);

}

void ShowNotification(RemoteMessage remoteMessage)
{
    String CHANNEL_ID = "my_channel_01";// The id of the channel.

NotificationCompat.Builder builder = new     NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.mipmap.ic_launcher_round);
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Random random = new Random();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), random.nextInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round));
builder.setContentTitle(remoteMessage.getData().get("title")); //the "title" value you sent in your notification
builder.setContentText(remoteMessage.getData().get("body"));
builder.setSubText(remoteMessage.getData().get("subTitle"));
builder.setAutoCancel(true);
builder.setChannelId(CHANNEL_ID);
builder.setDefaults(Notification.DEFAULT_ALL);
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

try
{
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
    r.play();
} catch (Exception e)
{
    e.printStackTrace();
}

NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{

    /* Create or update. */
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
            "title",
            NotificationManager.IMPORTANCE_DEFAULT);
    notificationManager.createNotificationChannel(channel);
}
//Creating unique id for each notification
int id = (int) System.currentTimeMillis();
notificationManager.notify(id, builder.build());
}

Я не знаю, что делаю не так ... ваш код работает, но уведомления приходят только тогда, когда я открываю и закрываю приложение ....

Angel Casas 11.01.2019 14:35

Я бы предложил использовать getData () вместо getNotification () внутри вашего объекта push-уведомления. В getData () уведомление принимается и отображается независимо от того, находится ли приложение на переднем или заднем плане.

Ali Ahsan 11.01.2019 15:41

Надеюсь, вы знаете об обмене сообщениями на основе тем и InstanceId.

Я считаю, что для целей тестирования вы пытаетесь использовать широковещательное сообщение на основе тем.

Итак, убедитесь, что вы подписались на тему в Activity или Application.

 FirebaseMessaging.getInstance().subscribeToTopic("Your_Topic");

Куда мне поместить этот код? В onNewTokenMethod? Спасибо

Angel Casas 11.01.2019 14:43

Создайте класс, расширяющий приложение, и определите его в файле манифеста. Переопределите метод onCreate и поместите приведенный выше код в тему, в которой вы хотите опубликовать сообщение.

Srinivasan 14.01.2019 07:31

После нескольких дней чтения руководств и сотен потоков stackoverflow я заметил, что не включил свое приложение в список защищенных приложений своего телефона ... ОС убивала мое приложение.

Теперь все работает!

Всем спасибо, ребята!

Другие вопросы по теме