android,FCM 是如何知道应该在何时向谁发送令牌的

android, how does FCM knows when and whom the token should be sent

为了测试 FCM,它只需要创建一个 FirebaseMessagingService 和 运行 应用程序,令牌将通过它的 onNewToken(String token) 传递给它。 (当然需要用FCM控制台创建一个项目,然后下载google-service.json)。

问题是 FCM 如何知道有一个应用程序刚开始 运行 并且 FCM 应该向它发送令牌(如何)?

测试项目只有一个mainActivity:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

和一项服务:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

  @SuppressLint("LongLogTag")
  @Override
  public void onNewToken(String token) {
    Log.d(TAG, "Refreshed token: " + token);
  }

  @SuppressLint("LongLogTag")
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    //...
  }
}

plus 添加了从 FCM 项目控制台获取的 google-services.json。并在相应的 build.gradle 中添加了应用插件,遵循 google FCM 站点说明:

apply plugin: 'com.google.gms.google-services'
dependencies {
        classpath 'com.google.gms:google-services:4.3.3'

并在清单中:

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

它实际上以相反的方式工作:当您的应用程序启动时,它会调用 FCM 服务并询问它们它拥有的令牌是否仍然有效。如果它不再有效,它会获得一个新令牌,然后调用此 onNewToken 处理程序。

因此 FCM 不会主动扫描需要更新的令牌,而是等待设备伸出并检查其令牌的状态。