2016-12-14 90 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>