До того, как на моем телефоне появился android 9, я работал на Java, сегодня решил снова начать работу с проектом, но продолжить с Kotlin.
По какой-то причине голубая точка и круг вокруг моего текущего места не отображаются (хотя раньше он работал с синтаксисом Java).
Приложение центрирует мою текущую позицию, и "показать мое местоположение"показывает в правом верхнем углу (если я нажимаю его, ничего не происходит)
Вот мой код.
package com.example.activitymap
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.places.GeoDataClient
import com.google.android.gms.location.places.PlaceDetectionClient
import com.google.android.gms.location.places.PlaceLikelihood
import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse
import com.google.android.gms.location.places.Places
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private val TAG = MapsActivity::class.java.simpleName
private var mMap: GoogleMap? = null
private var mCameraPosition: CameraPosition? = null
// The entry point to the Fused Location Provider.
private var mFusedLocationProviderClient: FusedLocationProviderClient? = null
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private val mDefaultLocation = LatLng(-33.8523341, 151.2106085)
private val DEFAULT_ZOOM = 15
private val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1
private var mLocationPermissionGranted: Boolean = false
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private var mLastKnownLocation: Location? = null
// Keys for storing activity state.
private val KEY_CAMERA_POSITION = "camera_position"
private val KEY_LOCATION = "location"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION)
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION)
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps)
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
// Build the map.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(map: GoogleMap) {
mMap = map
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap?.setInfoWindowAdapter(object : GoogleMap.InfoWindowAdapter {
override// Return null here, so that getInfoContents() is called next.
fun getInfoWindow(arg0: Marker): View? {
return null
}
override fun getInfoContents(marker: Marker): View {
// Inflate the layouts for the info window, title and snippet.
val infoWindow = layoutInflater.inflate(
R.layout.custom_info_contents,
findViewById<FrameLayout>(R.id.map), false
)
val title = infoWindow.findViewById(R.id.title) as TextView
title.text = marker.title
val snippet = infoWindow.findViewById(R.id.snippet) as TextView
snippet.text = marker.snippet
return infoWindow
}
})
mMap?.setOnMapClickListener { latLng ->
mMap?.addMarker(
MarkerOptions()
.position(latLng)
)
openAddActivity(latLng)
}
// Prompt the user for permission.
getLocationPermission()
// Turn on the My Location layer and the related control on the map.
updateLocationUI()
// Get the current location of the device and set the position of the map.
getDeviceLocation()
}
private fun getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
val locationResult = mFusedLocationProviderClient?.lastLocation
locationResult?.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.result
mMap?.moveCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(
mLastKnownLocation!!.latitude,
mLastKnownLocation!!.longitude
), DEFAULT_ZOOM.toFloat()
)
)
mMap?.isMyLocationEnabled = true
mMap?.uiSettings?.isMyLocationButtonEnabled = true
} else {
Log.d(TAG, "Current location is null. Using defaults.")
Log.e(TAG, "Exception: %s", task.exception)
mMap?.moveCamera(
CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM.toFloat())
)
mMap?.uiSettings?.isMyLocationButtonEnabled = false
}
}
}
} catch (e: SecurityException) {
Log.e("Exception: %s", e.message)
}
}
/**
* Prompts the user for permission to use the device location.
*/
private fun getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(
this.applicationContext,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
mLocationPermissionGranted = true
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION
)
}
}
/**
* Handles the result of the request for location permissions.
*/
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
mLocationPermissionGranted = false
when (requestCode) {
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true
}
}
}
updateLocationUI()
}
private fun openAddActivity(latlng: LatLng) {
val intent = Intent(this, AddActivity::class.java)
val args = Bundle()
args.putParcelable("latLng", latlng)
intent.putExtra("bundle", args)
this@MapsActivity.startActivity(intent)
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private fun updateLocationUI() {
if (mMap == null) {
return
}
try {
if (mLocationPermissionGranted) {
mMap?.isMyLocationEnabled = true
mMap?.uiSettings?.isMyLocationButtonEnabled = true
} else {
mMap?.isMyLocationEnabled = false
mMap?.uiSettings?.isMyLocationButtonEnabled = false
mLastKnownLocation = null
getLocationPermission()
}
} catch (e: SecurityException) {
Log.e("Exception: %s", e.message)
}
}
}
Build.Gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.activitymap"
minSdkVersion 23
targetSdkVersion 27
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
debuggable true
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.android.gms:play-services:12.0.1'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:mediarouter-v7:27.1.1'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:multidex:1.0.3'
}