使用Firebase的Android通知
我正在开发一个android应用程序,不同的用户将使用它。使用Firebase的Android通知,android,notifications,Android,Notifications,我正在开发一个android应用程序,不同的用户将使用它。 当另一个用户执行某些活动时,我需要向用户发出一些通知。我计划用firebase云消息传递(FCM)实现这一点。但我不知道如何检测相关设备。步骤1:向Firebase开发者控制台注册 要使用FCM,您需要登录到。您应该在右侧选择是创建新项目还是将现有的Google应用程序导入Firebase 单击Add App,然后复制google-services.json文件,该文件将下载到yourapp/dir中。此文件包括连接到Firebase所
当另一个用户执行某些活动时,我需要向用户发出一些通知。我计划用firebase云消息传递(FCM)实现这一点。但我不知道如何检测相关设备。步骤1:向Firebase开发者控制台注册 要使用FCM,您需要登录到。您应该在右侧选择是创建新项目还是将现有的Google应用程序导入Firebase 单击Add App,然后复制google-services.json文件,该文件将下载到yourapp/dir中。此文件包括连接到Firebase所需的项目信息和API密钥。确保保留文件名,因为它将在下一步中使用 最后,将Google服务添加到根build.gradle文件的类路径:
buildscript {
dependencies {
// Add this line
classpath 'com.google.gms:google-services:3.0.0'
}
}
添加到文件末尾的现有app/build.gradle:
apply plugin: 'com.google.gms.google-services'
第2步-下载Google Play服务
首先,让我们下载并设置Google Play Services SDK。打开工具->安卓->SDK管理器,检查您是否已经在附加部分下载了Google Play服务。确保更新至最新版本,以确保Firebase软件包可用
步骤3-添加谷歌存储库
同时打开工具->Android->SDK管理器并单击SDK工具选项卡。确保在Support Repository下安装了Google存储库。如果您忘记了此步骤,则很可能无法在下一步中包括Firebase消息传递库
步骤4-更新SDK工具
还要确保升级到SDK Tools 25.2.2。较低版本的SDK工具可能存在Firebase身份验证问题
步骤6-导入Firebase消息库
将以下内容添加到Gradle文件:
dependencies {
compile 'com.google.firebase:firebase-messaging:9.4.0'
}
步骤7-实施注册意向服务
您需要实现一个意图服务,它将作为后台线程执行,而不是绑定到活动的生命周期。通过这种方式,您可以确保当用户在注册过程中离开活动时,您的应用程序可以接收推送通知
首先,您需要创建RegistrationIntentService类,并确保在AndroidManifest.xml文件和应用程序标记中声明该类:
<service android:name=".RegistrationIntentService" android:exported="false"/>
<service
android:name="com.example.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
您需要记录令牌是否已发送到服务器,并可能希望将令牌存储在共享首选项中:
public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer";
public static final String FCM_TOKEN = "FCMToken";
@Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Fetch token here
try {
// save token
sharedPreferences.edit().putString(FCM_TOKEN, token).apply();
// pass along this data
sendRegistrationToServer(token);
} catch (IOException e) {
Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
sharedPreferences.edit().putBoolean(SENT_TOKEN_TO_SERVER, false).apply();
}
}
private void sendRegistrationToServer(String token) {
// send network request
// if registration sent was successful, store a boolean that indicates whether the generated token has been sent to server
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putBoolean(SENT_TOKEN_TO_SERVER, true).apply();
}
您需要确保在启动主要活动时发送此注册意图服务。Google Play服务检查可能需要启动您的活动才能显示对话框错误消息,这就是为什么在活动中而不是在应用程序中启动它
public class MyActivity extends AppCompatActivity {
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
@Override
protected void onCreate() {
if(checkPlayServices()) {
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
}
步骤8-创建InstanceID ListenerService
根据此Google官方文档,instance ID服务器定期(即6个月)发出回调请求应用程序刷新其令牌。为了支持这种可能性,我们需要从InstanceIDListenerService扩展来处理令牌刷新更改。我们应该创建一个名为MyInstanceIDListenerService.java的文件,该文件将覆盖此基本方法,并为RegistrationIntentService启动一个intent服务以获取令牌:
public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
// Fetch updated Instance ID token and notify of changes
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
您还需要将服务添加到应用程序标记内的AndroidManifest.xml文件中:
<service android:name=".RegistrationIntentService" android:exported="false"/>
<service
android:name="com.example.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
步骤9-侦听推送通知
让我们定义FCMMessageHandler.java,它从FirebaseMessagingService扩展而来,将处理接收到的消息:
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
public class FCMMessageHandler extends FirebaseMessagingService {
public static final int MESSAGE_NOTIFICATION_ID = 435345;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String from = remoteMessage.getFrom();
Notification notification = remoteMessage.getNotification();
createNotification(notification);
}
// Creates notification based on title and body received
private void createNotification(Notification notification) {
Context context = getBaseContext();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher).setContentTitle(notification.getTitle())
.setContentText(notification.getBody());
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
}
}
import com.google.firebase.messagingservice;
导入com.google.firebase.messaging.RemoteMessage;
导入android.app.NotificationManager;
导入android.content.Context;
导入android.os.Bundle;
导入android.support.v4.app.NotificationCompat;
公共类FCMMessageHandler扩展FirebaseMessagingService{
公共静态最终int消息通知ID=435345;
@凌驾
收到消息时公共无效(RemoteMessage RemoteMessage){
Map data=remoteMessage.getData();
String from=remoteMessage.getFrom();
通知通知=remoteMessage.getNotification();
创建通知(通知);
}
//根据收到的标题和正文创建通知
私有void createNotification(通知通知){
Context=getBaseContext();
NotificationCompat.Builder mBuilder=新建NotificationCompat.Builder(上下文)
.setSmallIcon(R.mipmap.ic_启动器).setContentTitle(notification.getTitle())
.setContentText(notification.getBody());
NotificationManager mNotificationManager=(NotificationManager)上下文
.getSystemService(上下文通知服务);
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID,mBuilder.build());
}
}
我们需要在AndroidManifest.xml中向FCM注册receiver类,标记推送的请求类型(类别):
<application
...>
<!-- ... -->
<activity
...>
</activity>
<service
android:name=".FCMMessageHandler"
android:exported="false" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
您必须获取每个设备的注册令牌,然后使用该注册令牌向特定设备发送通知。这是你开始学习的指南。你看过FB的文档吗?