Firebase Cloud Messaging android 项目不发送推送通知
Firebase Cloud Messaging android project doesn't send push notifications
我正在尝试开发一个应用程序,其中服务器必须每 5 秒向所有 android 设备 运行 发送通知给该应用程序。我决定使用 (Google) Firebse Cloud Messaging 发送通知,所以我先尝试了指南的示例项目
https://firebase.google.com/docs/notifications/android/console-audience
但我无法让它工作。我遵循了所有的指示。我已经发布了我使用的代码。我还做了 文件 --> 项目结构 --> 通知 --> 选中了框 Google 云消息传递 。我在 android 5 设备上试用了该应用程序。
当我打开 Firebase 控制台并发送通知时,我在日志中看到刷新的令牌(来自 MyFirebaseInstanceIDService
class,方法 onTokenRefresh()
),但是当我 运行 再次,并通过复制和粘贴令牌向单个设备发送通知,没有任何反应。此外,当我从控制台向 user segment 发送通知时,什么也没有发生。
我还尝试了来自同一网站的 Firebase 的相应 ios 示例项目,它在 iphone(所有通知已发送)上运行良好。我在这里遗漏了什么吗?
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}
MyFirebaseMessagingService :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
//Toast.makeText(getApplicationContext(),"FROM "+remoteMessage.getFrom(),Toast.LENGTH_LONG).show();
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
//Toast.makeText(getApplicationContext(),"MESSAGE: "+remoteMessage.getData(),Toast.LENGTH_LONG).show();
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
//MainActivity.TestMethod();
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
//Toast.makeText(getApplicationContext(),"MESSAGE: "+remoteMessage.getData(),Toast.LENGTH_LONG).show();
}
// 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());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.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.ic_stat_ic_notification)
.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());
}
}
主要activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
subscribeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// [START subscribe_topics]
FirebaseMessaging.getInstance().subscribeToTopic("news");
// [END subscribe_topics]
// Log and toast
String msg = getString(R.string.msg_subscribed);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
logTokenButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get token
String token = FirebaseInstanceId.getInstance().getToken();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
和build.gradle(项目消息):
// Top-level build file where you can add configuration options commonto `all sub-projects/modules.`
buildscript {
repositories {
jcenter()
mavenLocal()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
mavenLocal()
}
}
和 build.gradle(模块应用):
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.google.firebase.quickstart.fcm"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'LICENSE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Testing dependencies
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'
androidTestCompile 'com.android.support.test:runner:0.2'
androidTestCompile 'com.android.support:support-annotations:24.2.0'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.google.firebase:firebase-core:9.4.0'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.android.support:design:24.2.0'
}
apply plugin: 'com.google.gms.google-services'
...这是清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.firebase.quickstart.fcm">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- [START firebase_service] -->
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<activity
android:name=".ResultActivity"
android:label="@string/title_activity_result"
android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
可能是您正在尝试在应用程序处于前台时接收通知。请确保它在后台,然后重试。否则,您需要按照程序在您的应用处于前台时获得通知。
来自 Firebase 文档:
https://firebase.google.com/docs/cloud-messaging/android/receive
Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you’ll need to write code to handle the onMessageReceived callback.
正在发送通知消息:https://firebase.google.com/docs/cloud-messaging/android/first-message
Send a notification message
- Install and run the app on the target device.
- Make sure the app is in the background on the device.
- Open the Notifications tab of the Firebase console and select New Message.
- Enter the message text.
- Select Single Device for the message target.
- In the field labeled FCM Registration Token, enter the registration token you obtained in a previous section of this guide.
我终于找到问题所在了。似乎 json 文件不适合您在 Firebase 控制台创建项目的示例 project.When,它会生成一个 json 文件,应该下载并放置到应用程序文件夹。当我为自己的应用程序(而不是示例项目)创建项目并重新执行所有操作(并将控制台生成的 json 文件放在应用程序文件夹中)时,它工作正常。
我正在尝试开发一个应用程序,其中服务器必须每 5 秒向所有 android 设备 运行 发送通知给该应用程序。我决定使用 (Google) Firebse Cloud Messaging 发送通知,所以我先尝试了指南的示例项目
https://firebase.google.com/docs/notifications/android/console-audience
但我无法让它工作。我遵循了所有的指示。我已经发布了我使用的代码。我还做了 文件 --> 项目结构 --> 通知 --> 选中了框 Google 云消息传递 。我在 android 5 设备上试用了该应用程序。
当我打开 Firebase 控制台并发送通知时,我在日志中看到刷新的令牌(来自 MyFirebaseInstanceIDService
class,方法 onTokenRefresh()
),但是当我 运行 再次,并通过复制和粘贴令牌向单个设备发送通知,没有任何反应。此外,当我从控制台向 user segment 发送通知时,什么也没有发生。
我还尝试了来自同一网站的 Firebase 的相应 ios 示例项目,它在 iphone(所有通知已发送)上运行良好。我在这里遗漏了什么吗?
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}
MyFirebaseMessagingService :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
//Toast.makeText(getApplicationContext(),"FROM "+remoteMessage.getFrom(),Toast.LENGTH_LONG).show();
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
//Toast.makeText(getApplicationContext(),"MESSAGE: "+remoteMessage.getData(),Toast.LENGTH_LONG).show();
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
//MainActivity.TestMethod();
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
//Toast.makeText(getApplicationContext(),"MESSAGE: "+remoteMessage.getData(),Toast.LENGTH_LONG).show();
}
// 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());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.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.ic_stat_ic_notification)
.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());
}
}
主要activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
subscribeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// [START subscribe_topics]
FirebaseMessaging.getInstance().subscribeToTopic("news");
// [END subscribe_topics]
// Log and toast
String msg = getString(R.string.msg_subscribed);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
logTokenButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get token
String token = FirebaseInstanceId.getInstance().getToken();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
和build.gradle(项目消息):
// Top-level build file where you can add configuration options commonto `all sub-projects/modules.`
buildscript {
repositories {
jcenter()
mavenLocal()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
mavenLocal()
}
}
和 build.gradle(模块应用):
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.google.firebase.quickstart.fcm"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'LICENSE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Testing dependencies
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'
androidTestCompile 'com.android.support.test:runner:0.2'
androidTestCompile 'com.android.support:support-annotations:24.2.0'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.google.firebase:firebase-core:9.4.0'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.android.support:design:24.2.0'
}
apply plugin: 'com.google.gms.google-services'
...这是清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.firebase.quickstart.fcm">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- [START firebase_service] -->
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<activity
android:name=".ResultActivity"
android:label="@string/title_activity_result"
android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
可能是您正在尝试在应用程序处于前台时接收通知。请确保它在后台,然后重试。否则,您需要按照程序在您的应用处于前台时获得通知。
来自 Firebase 文档: https://firebase.google.com/docs/cloud-messaging/android/receive
Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you’ll need to write code to handle the onMessageReceived callback.
正在发送通知消息:https://firebase.google.com/docs/cloud-messaging/android/first-message
Send a notification message
- Install and run the app on the target device.
- Make sure the app is in the background on the device.
- Open the Notifications tab of the Firebase console and select New Message.
- Enter the message text.
- Select Single Device for the message target.
- In the field labeled FCM Registration Token, enter the registration token you obtained in a previous section of this guide.
我终于找到问题所在了。似乎 json 文件不适合您在 Firebase 控制台创建项目的示例 project.When,它会生成一个 json 文件,应该下载并放置到应用程序文件夹。当我为自己的应用程序(而不是示例项目)创建项目并重新执行所有操作(并将控制台生成的 json 文件放在应用程序文件夹中)时,它工作正常。