2016-12-14 105 views
0

我正在开发一个Android应用程序,不同的用户将使用它。 当另一个用户做某些活动时,我需要给用户一些通知。我计划用firebase云消息传递(FCM)来实现。但我不知道如何检测相关设备。使用Firebase的Android通知

+0

你必须获取每个设备的**注册令牌**,然后使用该注册令牌向特定设备发送通知。 [这里是链接](https://firebase.google.com/docs/cloud-messaging/android/client),它指导你开始。 –

+0

你还见过FB的文档吗? – piotrpo

回答

1

步骤1:用火力地堡开发者控制台

注册为了使用流式细胞仪,您需要登录到console。您应该在右侧选择是创建新项目还是将现有Google应用导入Firebase。

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

最后,加入谷歌的服务,您的根文件的build.gradle的类路径:

buildscript { 
    dependencies { 
    // Add this line 
    classpath 'com.google.gms:google-services:3.0.0' 
    } 
} 

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

apply plugin: 'com.google.gms.google-services' 

第2步 - 下载Google Play服务

首先,让我们下载并安装Google Play服务SDK。打开工具 - > Android-> SDK管理器,并检查您是否已经下载了附加部分下的Google Play服务。确保更新到最新版本,以确保Firebase套件可用。

第3步 - 添加谷歌储存库

而且开放工具 - > Android-> SDK管理器,然后单击SDK工具选项卡上。确保在Support Repository下安装了Google Repository。如果您忘记了这一步,则不太可能在下一步中包含Firebase消息传递库。

第4步 - 更新到SDK工具

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

第6步 - 导入火力地堡信息库

以下内容添加到您的摇篮文件:

dependencies { 
    compile 'com.google.firebase:firebase-messaging:9.4.0' 
} 

第7步 - 实现一个注册意向服务

你会想实现一个Intent Service,它将作为后台线程执行,而不是绑定到一个Activity的生命周期。通过这种方式,如果用户在注册过程发生时从用户导航离开活动,则可以确保您的应用可以接收推送通知。

首先,您需要创建一个RegistrationIntentService类,并确保它在AndroidManifest中声明。XML文件和应用程序代码中:

<service android:name=".RegistrationIntentService" android:exported="false"/> 

这个类里面,你将需要请求从谷歌的实例ID,这将是一个方法来唯一地标识设备和应用。假设这个请求是成功的,那么也可以生成一个可用于向应用发送通知的令牌。

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. 
    } 
} 

您将要录制的令牌是否被发送到服务器,并不妨令牌存储在您共享偏好:

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步 - 创建一个实例id ListenerService

根据这个谷歌官方文档,实例ID服务器的问题定期回调(即6个月),要求应用程序来刷新自己的令牌。为了支持这种可能性,我们需要扩展InstanceIDListenerService以处理令牌刷新更改。我们要创建一个名为MyInstanceIDListenerService.java文件,将覆盖该基地的方法,并推出一个意图服务RegistrationIntentService获取令牌:

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="com.example.MyInstanceIDListenerService" 
    android:exported="false"> 
    <intent-filter> 
    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> 
    </intent-filter> 
</service> 

第9步 - 侦听推送通知

让我们定义FCMMessageHandler.java从FirebaseMessagingS延伸ervice将处理收到的消息:

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

} 

我们需要接收机类与FCM注册在AndroidManifest.xml标签的推请求(类别)类型:

<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>