首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Firebase的Android通知

使用Firebase的Android通知
EN

Stack Overflow用户
提问于 2016-12-14 08:02:40
回答 1查看 1.5K关注 0票数 1

我正在开发一个android应用程序,不同的用户将使用它。当另一个用户做一些活动时,我需要给用户一些通知。我计划用防火墙云消息(FCM)来做这件事。但我不知道怎么检测相关的设备。

EN

回答 1

Stack Overflow用户

发布于 2016-12-14 10:51:25

步骤1:向Firebase开发人员注册控制台

为了使用FCM,您需要登录到控制台。您应该在右边选择是创建一个新项目,还是将一个现有的Google应用程序导入Firebase。

单击App,然后复制google-services.json文件,该文件将被下载到yourapp/ dir中。此文件包括连接到Firebase所需的项目信息和API密钥。确保保留文件名,因为它将在下一步中使用。

最后,将Google服务添加到根build.gradle文件的类路径:

代码语言:javascript
复制
buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:3.0.0'
  }
}

在文件末尾添加到现有的应用程序/build.gradle中:

代码语言:javascript
复制
apply plugin: 'com.google.gms.google-services'

步骤2-下载Google服务

首先,让我们下载并设置Google服务SDK。打开工具->Android->SDK管理器,检查是否已经下载了Extras部分下的Google服务。确保更新到最新版本,以确保Firebase包可用。

步骤3-添加Google

另外,打开Tools ->Android->,然后单击SDK Tools选项卡。确保在“支持库”下安装了。如果忘记此步骤,则不太可能在下一步中包括Firebase消息传递库。

步骤4-更新到SDK工具

还要确保升级到SDK工具25.2.2。使用较低的SDK工具版本,您可能会遇到Firebase身份验证问题。

步骤6-导入Firebase消息传递库

将以下内容添加到Gradle文件中:

代码语言:javascript
复制
dependencies {
   compile 'com.google.firebase:firebase-messaging:9.4.0'
}

步骤7-实现注册意图服务

您将希望实现意图服务,它将作为后台线程执行,而不是绑定到活动的生命周期。通过这种方式,您可以确保在进行此注册过程时,如果用户从活动中导航,您的应用程序就可以接收推送通知。

首先,您需要创建一个RegistrationIntentService类,并确保它是在AndroidManifest.xml文件和应用程序标记中声明的:

代码语言:javascript
复制
<service android:name=".RegistrationIntentService" android:exported="false"/>

在这个类中,您需要从Google请求一个实例ID,这将是唯一标识设备和应用程序的方法。假设此请求成功,也应该生成一个可以用于向应用程序发送通知的令牌。

代码语言:javascript
复制
public class RegistrationIntentService extends IntentService {

    // abbreviated tag name
    private static final String TAG = "RegIntentService";

    public RegistrationIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Make a call to Instance API
        FirebaseInstanceId instanceID = FirebaseInstanceId.getInstance();
        String senderId = getResources().getString(R.string.gcm_defaultSenderId);
        try {
            // request token that will be used by the server to send push notifications
            String token = instanceID.getToken();
            Log.d(TAG, "FCM Registration Token: " + token);

            // pass along this data
            sendRegistrationToServer(token);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}

您将希望记录令牌是否已发送到服务器,并可能希望将令牌存储在您的共享首选项中:

代码语言:javascript
复制
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 Services检查,它可能要求启动您的活动以显示对话框错误消息,这就是为什么它是在活动中而不是在应用程序中启动的。

代码语言:javascript
复制
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的官方文档,实例ID服务器定期(即6个月)发出回调请求,请求应用程序刷新其令牌。为了支持这种可能性,我们需要从InstanceIDListenerService进行扩展以处理令牌刷新更改。我们应该创建一个名为MyInstanceIDListenerService.java的文件,该文件将覆盖这个基本方法,并为RegistrationIntentService启动一个意图服务以获取令牌:

代码语言:javascript
复制
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文件中:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
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());
    }

}

我们需要在AndroidManifest.xml中用FCM注册接收类,标记push的请求类型(类别):

代码语言:javascript
复制
<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>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41137519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档