Как разработчики Xamarin создают собственные библиотеки для C#? - PullRequest
0 голосов
/ 29 апреля 2020

Как разработчики Xamarin создают собственные библиотеки для C#?

Я могу видеть, что есть много сервисных библиотек Google, например: Xamarin.Firebase.Auth. Я java и Kotlin разработчик, я хотел использовать код Kotlin (модуль) от Android studio до Xamarin. Android. Я следовал этому учебнику , и я строю .aar без зависимостей и успешно импортирую в Xamarin android. Но проблема с зависимостями Gradle, такими как classpath 'com.google.gms:google-services:4.3.3', apply plugin: 'com.google.gms.google-services' Я получаю ошибки:

{Java.Lang.NoClassDefFoundError: com.companyname.mylibrary.Authenticate$auth$callbacks$1
  at Java.Interop.JniEnvironment+InstanceMethods.CallNonvirtualVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0008e] in <26521a5118b44c858c385715922b9d5d>:0 
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeNonvirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0001f] in <26521a5118b44c858c385715922b9d5d>:0 
  at Com.Companyname.Mylibrary.Authenticate.Auth () [0x00002] in C:\Users\duval\source\repos\LibraryTest\ClassLibrary1\obj\Debug\generated\src\Com.Companyname.Mylibrary.Authenticate.cs:72 
  at LibraryTest.Droid.MainActivity.OnCreate (Android.OS.Bundle savedInstanceState) [0x00042] in C:\Users\duval\source\repos\LibraryTest\LibraryTest\LibraryTest.Android\MainActivity.cs:27 
  at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x00011] in <4ccdb3137d974856b786e1aeebbfbab6>:0 
  at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.8(intptr,intptr,intptr)
  --- End of managed Java.Lang.NoClassDefFoundError stack trace ---
java.lang.NoClassDefFoundError: com.companyname.mylibrary.Authenticate$auth$callbacks$1
    at com.companyname.mylibrary.Authenticate.auth(Authenticate.kt:15)
    at crc641e1c496b96c0654c.MainActivity.n_onCreate(Native Method)
    at crc641e1c496b96c0654c.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:6904)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7406)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
}

Как они делают, чтобы убедиться, что импортировать также зависимости?

В моем приложении graddle У меня есть зависимость Google:

buildscript {
    ext.kotlin_version = '1.3.71'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        classpath 'com.google.gms:google-services:4.3.3' //The dependency

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

В моем модуле graddle:

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

apply plugin: 'com.google.gms.google-services' // the Google plugin

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.google.firebase:firebase-auth:19.3.1' // The firebase auth
}

Один класс модуля:

import android.util.Log
import com.google.firebase.FirebaseException
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthProvider
import java.util.concurrent.TimeUnit

class Authenticate(private val activity: Activity) {

    val TAG = "COM.Authenticate"

    fun auth(){
        val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            override fun onVerificationCompleted(credential: PhoneAuthCredential) {
                Log.d(TAG, "onVerificationCompleted:$credential")
            }

            override fun onVerificationFailed(e: FirebaseException) {
                Log.w(TAG, "onVerificationFailed", e)
            }

            override fun onCodeSent(
                verificationId: String,
                token: PhoneAuthProvider.ForceResendingToken
            ) {
                Log.d(TAG, "onCodeSent:$verificationId")
            }
        }

        PhoneAuthProvider.getInstance().verifyPhoneNumber(
            "+16505559999", // Phone number to verify
            60, // Timeout duration
            TimeUnit.SECONDS, // Unit of timeout
            activity, // Activity (for callback binding)
            callbacks) // OnVerificationStateChangedCallbacks
    }
}

Вызов его внутри действия:

Authenticate authenticate = new Authenticate(this);
authenticate.Auth();

Отредактировано

Я просто создаю новый пустой android студийный проект и импортирую свою aar-библиотеку (File -> new -> new module -> Import .jar/.aar package) в модуль приложения I. set implementation project(":my-library-name").

И когда я запускаю приложение, я получаю эту ошибку при вызове библиотеки:

2020-05-05 16:11:36.626 11752-11752/com.companyname.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.companyname.myapplication, PID: 11752
    java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/auth/PhoneAuthProvider$OnVerificationStateChangedCallbacks;
        at com.companyname.myapplication.MainActivity.onCreate(MainActivity.kt:13)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.auth.PhoneAuthProvider$OnVerificationStateChangedCallbacks" on path: DexPathList[[zip file "/data/app/com.companyname.myapplication-b6SAtovKWrC0PkwlBsVC8w==/base.apk"],nativeLibraryDirectories=[/data/app/com.companyname.myapplication-b6SAtovKWrC0PkwlBsVC8w==/lib/x86_64, /system/lib64, /system/product/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.companyname.myapplication.MainActivity.onCreate(MainActivity.kt:13) 
        at android.app.Activity.performCreate(Activity.java:7802) 
        at android.app.Activity.performCreate(Activity.java:7791) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
2020-05-05 16:11:36.643 11752-11752/com.companyname.myapplication I/Process: Sending signal. PID: 11752 SIG: 9
...