所以我正在根据我所学的课程为Android创建一个简单的应用程序。 在我创建一个类和函数来检测 GPS 上的位置更改之前,地图显示得很好,现在每当活动打开并授予权限时,它只会在我的手机上显示黑屏,没有错误崩溃或任何东西,但除了关闭应用程序之外什么都做不了(我使用真实设备模拟(。 我已经在 xml 上添加了 api 密钥
这是我的代码
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
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.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
var accessLocation = 123
var location : Location? = null
var name : String = "We"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
name = intent.getStringExtra("name")
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
getPermission()
}
fun getPermission(){
if(Build.VERSION.SDK_INT >= 23){
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),accessLocation)
return
}
}
getLocation()
}
fun getLocation(){
Toast.makeText(this, "Location access permision granted", Toast.LENGTH_LONG).show()
var myLocationListener = MapListener()
var locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3,3f,myLocationListener)
var locationTrack = locationThread()
locationTrack.start()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode){
accessLocation -> {
if(grantResults[0]==PackageManager.PERMISSION_GRANTED) getLocation()
else Toast.makeText(this,"Location access is Needed",Toast.LENGTH_LONG).show()
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
inner class MapListener : LocationListener {
constructor(){
location = Location("Start")
location!!.latitude = 0.0
location!!.longitude = 0.0
}
override fun onLocationChanged(position: Location?) {
location = position
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
// TODO("not implemented")
}
override fun onProviderEnabled(provider: String?) {
// TODO("not implemented")
}
override fun onProviderDisabled(provider: String?) {
// TODO("not implemented")
}
}
inner class locationThread : Thread {
constructor() : super()
override fun run() {
while (true){
try {
runOnUiThread{
mMap.clear()
val located= LatLng(location!!.latitude, location!!.longitude)
mMap.addMarker(MarkerOptions()
.position(malang)
.title("$name are Here")
.snippet("have a nice day")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mario)))
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(located,14f))
Thread.sleep(1000)
}
}catch (ex : Exception){
}
}
}
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
}
}
这是清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.furis.sid.pokemon">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key"/>
<activity
android:name=".MapsActivity"
android:label="Map">
</activity>
</application>
</manifest>
这就是当应用程序变黑时出现在 logcat 中的内容(真的不知道在这里显示哪一个,所以我只是截屏它变黑时弹出的内容( 日志猫
提前致谢
我发现了黑屏的原因,因为由于类 locationThread 而无法完成活动中的 onCreate,所以我添加了一个变量来存储旧的定位并更改了线程类,以便它并不总是调用函数 位置未更改为此时的每一秒:
inner class locationThread : Thread {
constructor() : super(){
oldLocation = Location("Start")
oldLocation!!.latitude = 0.0
oldLocation!!.longitude = 0.0
}
override fun run() {
while (true){
try {
if(location!!.distanceTo(oldLocation)==0f) continue
oldLocation = location
runOnUiThread{
mMap.clear()
val located= LatLng(location!!.latitude, location!!.longitude)
mMap.addMarker(MarkerOptions()
.position(malang)
.title("$namae are Here")
.snippet("Have a nice day")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mario)))
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(located,14f))
Thread.sleep(1000)
}
}catch (ex : Exception){
}
}
}
}