Firebase通知在Android设备上无法正常运行

时间:2019-01-11 10:31:34

标签: android firebase firebase-cloud-messaging

我已经在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文件。

如果我去Cloud Messaging并发送新通知,它将永远不会到达...

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

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

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

任何帮助将不胜感激。

谢谢。

3 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分:0)

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

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

因此,请确保已在“活动”或“应用程序”中订阅了该主题。

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

答案 2 :(得分:0)

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

现在一切正常!

谢谢大家!