【问题标题】:Firebase notifications stop working on AndroidFirebase 通知停止在 Android 上运行
【发布时间】:2019-01-15 04:15:40
【问题描述】:

我已经阅读了很多关于 Android 上 Firebase 通知的答案,但没有一个能解决我的问题。

我有一个安装了 Firebase 的 Android 应用程序,并且创建并配置了 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 文件。

如果我去云消息传递并发送一个新的通知,它永远不会到达......

最奇怪的是,当我尝试这个教程时:

https://www.youtube.com/watch?v=u9vWzCC0JKU

通知工作正常,但即使我重新启动整个项目,它们也会停止工作......

我们将不胜感激。

提前致谢。

【问题讨论】:

  • 您没有在接收推送通知消息的“onMessageReceived”方法中创建任何通知

标签: android firebase firebase-cloud-messaging


【解决方案1】:

您可以使用以下代码创建推送通知。用你的改变密钥对值

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

【讨论】:

  • 我不知道我做错了什么......您的代码有效,但只有在我打开和关闭应用程序时才会收到通知......
  • 我建议在您的推送通知对象中使用 getData() 而不是 getNotification()。在 getData() 中,无论应用程序处于前台/后台,都会收到并显示通知。
【解决方案2】:

希望您了解基于主题和 InstanceId 的消息传递。

我相信出于测试目的,您正在尝试使用基于主题的广播消息。

所以,请确保您已在 Activity 或 Application 中订阅主题。

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

【讨论】:

  • 我必须把这段代码放在哪里?在 onNewTokenMethod 中?谢谢
  • 创建一个扩展 Application 的类并在 Manifest 文件中定义它。重写onCreate方法,把上面的代码和你要发布消息的主题放在一起。
【解决方案3】:

在阅读了数天的教程和数百个 stackoverflow 线程后,我注意到我没有将我的应用包含在手机的受保护应用列表中......操作系统正在杀死我的应用。

现在一切正常!

谢谢大家!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多