How to handle FirebaseInstanceId.getInstance().getToken() = null

前端 未结 7 2148
情书的邮戳
情书的邮戳 2020-12-05 15:43

I have just migrated to FCM. I have added my class that extends from FirebaseInstanceIdService to receive a refreshedToken as and when appropriate.

My question is sp

7条回答
  •  天命终不由人
    2020-12-05 16:07

    • if your device have no connection to the internet onTokenRefresh() is never called and you should notify to user his/her device has no internet connection
    • firebase has its own network change listener and when a device connected to the internet then try to get token and return it, at this time you can tell your main activity by sending a local broadcast receiver that registration token is received.

    use below codes:

        @Override
    public void onTokenRefresh() {
    
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    
        Log.d("FCN TOKEN GET", "Refreshed token: " + refreshedToken);
    
        final Intent intent = new Intent("tokenReceiver");
        // You can also include some extra data.
        final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
        intent.putExtra("token",refreshedToken);
        broadcastManager.sendBroadcast(intent);
    
    
    }
    

    in your main activity:

        public class MainActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
       LocalBroadcastManager.getInstance(this).registerReceiver(tokenReceiver,
                new IntentFilter("tokenReceiver"));
    
    }
    
    BroadcastReceiver tokenReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String token = intent.getStringExtra("token");
            if(token != null)
            {
                //send token to your server or what you want to do
            }
    
        }
    };
    
    }
    

提交回复
热议问题