2016-08-24 95 views

回答

0

首先,您需要轉到Firebase控制檯並創建一個應用。 (爲此,您需要登錄到您的谷歌帳戶),並按照這裏提供的步驟。 https://firebase.google.com/docs/

一旦做到這一點,你需要這些服務,您的Manifest.xml文件

<service 
    android:name=".firebase.FirebaseMessagingService"> 
    <intent-filter> 
     <action android:name="com.google.firebase.MESSAGING_EVENT"/> 
    </intent-filter> 
</service> 

<service 
    android:name=".firebase.FirebaseInstanceIDService"> 
    <intent-filter> 
     <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> 
    </intent-filter> 
</service> 

添加FirebaseInstanceIdService.class

public class FirebaseInstanceIDService extends FirebaseInstanceIdService { 
    private static final String TAG = "FirebaseInstanceIDService"; 

    @Override 
    public void onTokenRefresh() { 
     String token = FirebaseInstanceId.getInstance().getToken(); 
     Log.d(TAG, "OnTokenRefresh callback. Token received : " + token); 
    } 
} 

FirebaseMessagingService.class

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService { 

    private static final String TAG = "FirebaseMessagingService"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     Log.d(TAG,"onMessageReceived."); 
     showNotification(remoteMessage.getData().get("message")); 
    } 

    private void showNotification(String message) { 

     Intent i = new Intent(this, HomeActivity.class); 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT); 

     NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
       .setAutoCancel(true) 
       .setContentTitle("Slapr Notification Demo") 
       .setContentText(message) 
       .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark) 
       .setContentIntent(pendingIntent); 

     NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

     manager.notify(0,builder.build()); 
    } 
} 

現在你可以得到tokenId在你的活動中做下列事情

Log.d(TAG, "Recieved token : " + FirebaseInstanceId.getInstance().getToken()); 

這是我在開始時找到的最有用的教程。我希望它能幫助你。 https://www.youtube.com/watch?v=LiKCEa5_Cs8

https://www.youtube.com/watch?v=MYZVhs6T_W8

+0

我已經使用您所提供的代碼,但它顯示**「空」 **爲令牌 – Bhavesh

+0

請從我所共享的鏈接時經過一次教程 –

相關問題