未解析的引用:loop;未解析的引用:applicationContext

时间:2018-07-01 06:01:18

标签: java android kotlin

我有3个未解决的引用

  1. anko
  2. loop
  3. applicationContext

对于anco,我添加了

implementation "org.jetbrains.anko:anko-commons:$anko_version"
 implementation "org.jetbrains.anko:anko-sdk25:$anko_version"
implementation "org.jetbrains.anko:anko-sdk25-listeners:$anko_version" 

    ext.anko_version='0.10.1'

我还需要为其他2项未解决的问题添加什么?

我必须添加

 sourceSets {
    main.kotlin.srcDirs += 'src/main/myKotlin'
}

我的Java代码和kotlin代码位于src / main / java / com / example / root / xyz /下的同一目录中。我已添加

sourceSets {
    main.kotlin.srcDirs += 'src/main/java/com/example/root/securityalert/'
}

出现错误->无法获得类型为org.gradle.api.internal.tasks.DefaultSourceSet的源集“ main”的未知属性“ kotlin”

我正在尝试从Android中的Java代码调用kotlin代码。我从Internet获得了代码。我收到错误消息

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
        at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:16)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:429)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:390)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:274)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:233)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        ... 32 more

我的Build.gradle(Project:xyz)文件是->

buildscript {
    ext.kotlin_version = '1.2.50'

    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
// Top-level build file where you can add configuration options common to all sub-projects/modules.

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

我的build.gradle(Module:App)文件是->

/*plugins {
    id "org.jetbrains.kotlin.jvm" //version "1.2.50"

}*/
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.root.securityalert"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildToolsVersion '27.0.3'
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.android.support:design:26.1.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.16'
    implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    compile 'com.android.support:support-annotations:27.1.1'
}
repositories {
    mavenCentral()
}

代码

package com.example.root.securityalert

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.os.Build
import android.support.annotation.RequiresApi
import com.loop.toolkit.kotlin.Utils.extensions.applicationContext
import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.bluetoothManager

class BleScannerFlowable private constructor(
        private val adapter: BluetoothAdapter,
        private val stopCallback: ((BluetoothDevice) -> Boolean)? = null,
        private val scanFilter: Array<out ScanFilter>? = null,
        private val scanSettings: ScanSettings? = null
): FlowableOnSubscribe<BluetoothDevice> {

    override fun subscribe(e: FlowableEmitter<BluetoothDevice>) {
        if (isAboveLollipop()) {
            setupSubscriber21(e)
        } else {
            setupSubscriber(e)
        }
    }

    private fun setupSubscriber(emitter: FlowableEmitter<BluetoothDevice>) {
        adapter.startLeScan { device, rssi, scanRecord ->
            if (stopCallback?.invoke(device) == true) {
                adapter.stopLeScan { device, rssi, scanRecord ->
                    emitter.onComplete()
                }
            }
            emitter.onNext(device)
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun setupSubscriber21(emitter: FlowableEmitter<BluetoothDevice>) {
        val isFilterSet = scanFilter?.isNotEmpty() == true
        val filters = if (isFilterSet) scanFilter!!.toMutableList() else mutableListOf()
        adapter.bluetoothLeScanner?.startScan(filters, scanSettings, ScanCaller(emitter))
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private inner class ScanCaller(private val emitter: FlowableEmitter<BluetoothDevice>) : ScanCallback() {
        override fun onScanFailed(errorCode: Int) {
            emitter.onError(Throwable("Scan failed with code $errorCode"))
        }

        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            if (result != null && result.device != null) {
                if (stopCallback?.invoke(result.device) == true) {
                    adapter.bluetoothLeScanner?.stopScan(this)
                    emitter.onComplete()
                } else {
                    emitter.onNext(result.device)
                }
            }
        }
    }

    class Builder(private val adapter: BluetoothAdapter) {
        private var scanFilter: Array<out ScanFilter>? = null
        private var stopCallback: ((BluetoothDevice) -> Boolean)? = null
        private var settingsBuilder: ScanSettings.Builder? = null
        private var scanSettings: ScanSettings? = null

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        fun setFilterByName(name: String) : Builder {
            setScanFilters(ScanFilter.Builder()
                    .setDeviceName(name)
                    .build())
            return this
        }

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        fun setScanFilters(vararg scanFilter: ScanFilter) : Builder{
            this.scanFilter = scanFilter
            return this
        }

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        fun setScanMode(scanMode: ScanModes) : Builder{
            getSettingsBuilder().setScanMode(scanMode.settingId)
            return this
        }

        fun setStopCallback(function: (BluetoothDevice) -> Boolean) : Builder {
            this.stopCallback = function
            return this
        }

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        fun setScanSettings(scanSettings: ScanSettings) : Builder {
            this.scanSettings = scanSettings
            return this
        }

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        fun build(): Flowable<BluetoothDevice> =
                Flowable.create(BleScannerFlowable(adapter,
                        stopCallback,
                        scanFilter,
                        scanSettings ?: settingsBuilder?.build()),
                        BackpressureStrategy.LATEST)

        fun buildLower(): Flowable<BluetoothDevice> =
                Flowable.create(BleScannerFlowable(adapter, stopCallback),
                        BackpressureStrategy.LATEST)

        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        private fun getSettingsBuilder() : ScanSettings.Builder {
            if (settingsBuilder == null) {
                settingsBuilder = ScanSettings.Builder()
            }
            return settingsBuilder!!
        }
    }

}


@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
enum class ScanModes(val settingId: Int) {
    LOW_LATENCY(ScanSettings.SCAN_MODE_LOW_LATENCY),
    LOW_POWER(ScanSettings.SCAN_MODE_LOW_POWER),
    BALANCED(ScanSettings.SCAN_MODE_BALANCED),
    OPPORTUNISTIC(ScanSettings.SCAN_MODE_BALANCED)
}

fun startScanning() {
    val adapter = applicationContext.bluetoothManager.adapter ?: return
    val bleScanner = if (isAboveLollipop()) {
        BleScannerFlowable.Builder(adapter)
                .setScanMode(ScanModes.BALANCED)
                .setStopCallback { it.name == "MyBleDevice" }
                .build()
    } else {
        BleScannerFlowable.Builder(adapter)
                .setStopCallback { it.name == "MyBleDevice" }
                .buildLower()
    }

    bleScanner
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                // do something with the bluetooth device
            }, {
                // handle error
                it.printStackTrace()
            }, {
                // do on finish scan
            })
}

fun isAboveLollipop() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP

1 个答案:

答案 0 :(得分:0)

您的Gradle文件中的android块是在com.android.application插件中实现的。您需要取消注释该行

apply plugin: com.android.application

可以使用它。您应该为此取消两个apply plugin语句的注释。它们是必需的。