Не дает вызвать функцию kotlin, просит ввести аргумент хотя в списке параметров нет ни одного!

Рейтинг: -2Ответов: 1Опубликовано: 13.02.2025

IDE Не дает вызвать функцию kotlin из java класса другого пакета, просит ввести аргумент, хотя в списке параметров нет ни одного!
Скажите, почему не дает вызвать функцию?

Ошибка:

error: method getFirebaseToken in class TokenProvider cannot be applied to given types;
String token = TokenProvider.getFirebaseToken().toString();

В классе котлина в другом пакете есть код по созданию этой функции:

suspend fun getTokenMy(): Any {
    val token = Firebase.messaging.token.await()

    return token.toString()
}

А в классе java другого пакета есть код, который вызывает функцию:

PushNotificationService PushNotificationService  = new PushNotificationService();
FCM_token2 = PushNotificationServicelUtil.getTokenMy().toString();

и компилятор показывает ошибку:

method getTokenMy in class PushNotificationService cannot be applied to given types;  
FCM_token2 = pushNotificationService.getTokenMy().toString();
                                            ^ 

И даже если создаю функцию другим способом, та же ошибка:

    object TokenProvider {
        @JvmStatic
        suspend fun getFirebaseToken(): String {
            return FirebaseMessaging.getInstance().token.await()
        }
    }

Вызываю в данном случае из Java класса вот так:

       String token = TokenProvider.getFirebaseToken().toString();
       System.out.println("Firebase Token: " + token);

Если же я вот так создаю функцию в котлине:

    @file:JvmName("PushNotificationServicelUtil")
    package fcmpushnotificationshttpv1

    import com.google.firebase.firestore.FieldValue
    import com.google.firebase.firestore.ktx.firestore
    import com.google.firebase.ktx.Firebase
    import com.google.firebase.messaging.FirebaseMessaging
    import com.google.firebase.messaging.FirebaseMessagingService
    import com.google.firebase.messaging.RemoteMessage
    import com.google.firebase.messaging.ktx.messaging
    import kotlinx.coroutines.tasks.await


    val tokenMy: Any
        get() {
            TODO()
        }

    class PushNotificationService: FirebaseMessagingService() {

        override fun onNewToken(token: String) {
            super.onNewToken(token)
            sendTokenToServer(token)
            // Update server
        }

        override fun onMessageReceived(message: RemoteMessage) {
            super.onMessageReceived(message)

            // Respond to received messages
        }

        suspend fun getTokenMy(): String {
            val token = Firebase.messaging.token.await()

            return token.toString()
        }
    }

Возникает другая ошибка:

Failed to execute the transaction: tId:-1294874029 ClientTransaction {                                                                                                         tId:-1294874029   transactionItems=[
  tId:-1294874029
  LaunchActivityItem {
    activityToken=android.os.BinderProxy@cb96ca2,
    intent=Intent { 
        act=android.intent.action.MAIN 
        cat=[android.intent.category.LAUNCHER] 
        flg=0x10000000 cmp=dem.corp.androidmessenger/.MainActivity
    },
    ident=54864729,
    info=ActivityInfo{dbde59c dem.corp.androidmessenger.MainActivity},
    curConfig={
        1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h923dp 420dpi nrml long port finger qwerty/v/v dpad/v 
        winConfig={ 
          mBounds=Rect(0, 0 - 1080, 2424) 
          mAppBounds=Rect(0, 0 - 1080, 2424) 
          mMaxBounds=Rect(0, 0 - 1080, 2424)
          mDisplayRotation=ROTATION_0 
          mWindowingMode=fullscreen 
          mActivityType=undefined 
          mAlwaysOnTop=undefined 
          mRotation=ROTATION_0
        } 
        as.3 s.54 
        fontWeightAdjustment=0
    }
...
}
                                                                              tId:-1294874029     Target activity: dem.corp.androidmessenger.MainActivity

Подскажите почему?

Обнолвение: Я сделал как сказал Влад, но не помогло:

object TokenProvider {
    @OptIn(DelicateCoroutinesApi::class)
    @JvmStatic
    suspend fun getFirebaseToken(): Any? = GlobalScope.future {
        return@future FirebaseMessaging.getInstance().token.await()
    }
}

и так ошибка

object TokenProvider {
    @OptIn(DelicateCoroutinesApi::class)
    @JvmStatic
    suspend fun getFirebaseToken(): CompletableFuture<String> = GlobalScope.future {
        return@future FirebaseMessaging.getInstance().token.await()
    }
}

Ответы

▲ 0

вот как надо из Java вызывать функцию котлин и создавать в котлине функцию (в данном примере название функции в котлине saveMyToken ) для Джава, если эта функция с ожиданием: Создает функцию в котлине:

@file:JvmName("PushNotificationServicelUtil")
package fcmpushnotificationshttpv1

import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.firebase.messaging.ktx.messaging
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.future.future
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import java.util.Objects
import java.util.concurrent.CompletableFuture


class PushNotificationService: FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        sendTokenToServer(token)
        // Update server
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)

        // Respond to received messages
    }

    suspend fun getTokenMy(): String {
        val token = Firebase.messaging.token.await()

        return token.toString()
    }







    suspend fun saveMyToken() {

        val token = Firebase.messaging.token.await()

        // Check whether the retrieved token matches the one on your server for this user's device

        // Example shown below with Firestore
        // Add token and timestamp to Firestore for this user
        val deviceToken = hashMapOf(
            "token" to token,
            "timestamp" to FieldValue.serverTimestamp(),
        )

        // Get user ID from Firebase Auth or your own server
        Firebase.firestore.collection("fcmTokens").document("myuserid")
            .set(deviceToken).await()
    }

    fun saveTokenFromJava() {
        GlobalScope.launch {
            saveMyToken()
        }
    }

}








/**
 * my Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM registration token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private fun sendTokenToServer(token: String?) {
    // If you're running your own server, call API to send token and today's date for the user

    // Example shown below with Firestore
    // Add token and timestamp to Firestore for this user
  //  val uid = Objects.requireNonNull(FirebaseAuth.getInstance().currentUser)
    val deviceToken = hashMapOf(
        "token" to token,
    //    "uid" to uid,
        "timestamp" to FieldValue.serverTimestamp(),
    )

    //ChatUtil.createChat("ZqnkGaeyk3UkRLRJH8Qh1tQiF7d2");
    // FirebaseDatabase.getInstance().getReference().child("Users").child("mdlfnx5Bo4dbpKOjwmUxaiyJzAY2")
    //       .child("chats").setValue(chatsUpd);
   // val uid = Objects.requireNonNull(FirebaseAuth.getInstance().currentUser)
    // Get user ID from Firebase Auth or your own server

    val uid = Objects.requireNonNull(FirebaseAuth.getInstance().currentUser)

    Firebase.firestore.collection("fcmTokens").document("uid".toString())
        .set(deviceToken)


}

object TokenProvider {
    @OptIn(DelicateCoroutinesApi::class)
    @JvmStatic
    suspend fun getFirebaseToken(): CompletableFuture<String> = GlobalScope.future {
        return@future FirebaseMessaging.getInstance().token.await()
    }



}

и вызываем из Java функцию Kotlin просто очень, вот так:

     fcmpushnotificationshttpv1.PushNotificationService pushNotificationService = new fcmpushnotificationshttpv1.PushNotificationService();
       // TokenManager tokenManager = new TokenManager();
        pushNotificationService.saveTokenFromJava();