应用安装后立即发送FCM注册

时间:2018-11-13 03:22:48

标签: java php android mysql firebase

我有一个将FCM注册令牌存储到MySQL数据库的应用程序。最初安装该应用程序时,该应用程序将null发送到数据库,但是当第二次启动该应用程序时,该令牌将发送到数据库。

有没有一种方法可以在安装应用程序后立即发送令牌?

MainActivity

 FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(@NonNull Task<InstanceIdResult> task) {
                    if (task.isSuccessful()){

                        String recent_token = task.getResult().getToken();
                        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(getString(R.string.FCM_TOKEN), recent_token);

                        editor.commit();

                    }else{


                    }
                }
            });
    SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
    final String token=sharedPreferences.getString(getString(R.string.FCM_TOKEN),"");

1 个答案:

答案 0 :(得分:2)

FCM令牌是异步生成的。最像是您尚未通过struct ListNode { int value; ListNode* next = NULL; }; void insertRecList(ListNode* list, int value) { if(list->next == NULL) { ListNode* end = new ListNode; end->value = value; list->next = end; } else insertRecList(list->next, value); } void printList(ListNode* list) { std::cout << list->value << std::endl; while(list->next != NULL) { list = list->next; std::cout << list->value << std::endl; } } void reverseList(ListNode* list) { ListNode* next; ListNode* prev = NULL; ListNode* cur = list; while(cur != NULL) { if(cur->next == NULL) { cur->next = prev; break; } else { next = cur->next; cur->next = prev; prev = cur; cur = next; } } list = cur; std::cout << cur->value << " list:" << list->value << std::endl; } void testLinkedList() { srand(time(NULL)); ListNode nodes; nodes.value = 99; int val; for(int i = 0; i < 5; i++) { val = rand() % 30 + 1; insertRecList(&nodes, i); //insertList(&nodes, val); } printList(&nodes); reverseList(&nodes); printList(&nodes); } int main() { testLinkedList(); return 0; } 请求令牌时。为确保您在生成令牌后尽快获得令牌,monitor token generation as shown in the documentation

FirebaseInstanceId.getInstance().getInstanceId()

这可确保您始终在生成令牌时就被调用,令牌发生在安装后应用首次运行时发生,并且可能在此后的某些时刻发生。