应用程序正在模拟器中定位,但在实际的 android 设备中运行时没有

Posted

技术标签:

【中文标题】应用程序正在模拟器中定位,但在实际的 android 设备中运行时没有【英文标题】:App is taking location in the emulator, but not when running in an actual android device 【发布时间】:2021-11-01 21:51:56 【问题描述】:

该应用类似于 Pokemon Go 应用。它在模拟器中运行良好,但是在我的安卓手机中运行时,我的位置没有显示。 这是我使用地图的活动:

package com.example.catchem

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
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.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.example.catchem.databinding.ActivityDisplayBinding
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import java.lang.Exception

class Display : AppCompatActivity(), OnMapReadyCallback 

    var usr_name=""
    var myPower=0.0
    var c=0;
    var current_lat:Double=0.0
    var current_long: Double=0.0
    private lateinit var mMap: GoogleMap
    private lateinit var binding: ActivityDisplayBinding

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)

        usr_name=intent.getStringExtra(Data.usr_name).toString()
        binding = ActivityDisplayBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
        checkPermission()
    

    var accessLocation=123

    fun checkPermission() 
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED) 
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),accessLocation)
            return
        
        getLocation()
    

    fun getLocation() 
        var myLocation=MyLocation()
        var locationManager=getSystemService(Context.LOCATION_SERVICE) as LocationManager
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3, 3f, myLocation)
        var myThread=updateThread()
        myThread.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, "Cannot access your location", Toast.LENGTH_LONG).show()
            
        
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    

    override fun onMapReady(googleMap: GoogleMap) 
        mMap = googleMap

        // Add a marker in Sydney and move the camera

    

    var currentLocation: Location?=null

    inner class MyLocation: LocationListener 
        constructor() 
            currentLocation= Location("start")
            currentLocation!!.latitude=0.0
            currentLocation!!.longitude=0.0
        
        override fun onLocationChanged(location: Location) 
            currentLocation=location
            current_lat=currentLocation!!.latitude
            current_long=currentLocation!!.longitude
            c++;
            if(c==1)
                loadPokemons()
        

    

    var old_Locattion: Location?=null

    inner class updateThread: Thread 
        constructor(): super() 
            old_Locattion= Location("start")
            old_Locattion!!.longitude=0.0
            old_Locattion!!.latitude=0.0
        
        override fun run() 
            while (true) 
                try 
                    if(old_Locattion!!.distanceTo(currentLocation)==0f)
                        continue
                    old_Locattion=currentLocation
                    runOnUiThread() 
                        //my location
                        mMap!!.clear()

                        val sydney = LatLng(currentLocation!!.latitude, currentLocation!!.longitude)
                        Log.i("me", "lat: $currentLocation!!.latitude    long: $currentLocation!!.longitude")
                        mMap.addMarker(MarkerOptions().position(sydney).title(usr_name).snippet("Current power is: $myPower").icon(BitmapDescriptorFactory.fromResource(R.drawable.ash1)))
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,16f))

                        //pokemon location
                        for(i in 0..poke_list.size-1) 
                            var new_poke = poke_list[i]
                            val sydney = LatLng(new_poke.loc_poke!!.latitude, new_poke.loc_poke!!.longitude)
                            mMap.addMarker(MarkerOptions().position(sydney).
                            title(new_poke.name!!).
                            snippet("Type: $new_poke.type!!    Power: $new_poke.power").
                            icon(BitmapDescriptorFactory.fromResource(new_poke.img!!)))
                            Log.i("$new_poke.name", "lat: $new_poke.loc_poke!!.latitude long: $new_poke.loc_poke!!.longitude")

                            if (currentLocation!!.distanceTo(new_poke.loc_poke!!)<50) 
                                myPower+=new_poke.power!!
                                new_poke.loc_poke!!.latitude=rand_lat()
                                new_poke.loc_poke!!.longitude=rand_long()
                                poke_list[i]=new_poke

                                Toast.makeText(applicationContext, "Your caught a $new_poke.name Your current power is $myPower", Toast.LENGTH_LONG).show()
                            

                        
                    
                    Thread.sleep(2000)
                catch (e:Exception) Log.i("Exception: ", "$e")
            
        
    

    var poke_list=ArrayList<Pokemons>()

    fun loadPokemons() 
        poke_list.add(Pokemons("Bulbasaur", "Grass", 20.0, rand_lat(), rand_long(),R.drawable.bulbasaur))
        poke_list.add(Pokemons("Charmander", "Fire", 21.0, rand_lat(), rand_long(),R.drawable.charmander))
        poke_list.add(Pokemons("Darkrai", "Dark", 37.0, rand_lat(), rand_long(),R.drawable.darkrai))
        poke_list.add(Pokemons("Eevee", "Normal", 22.0, rand_lat(), rand_long(),R.drawable.eevee))
        poke_list.add(Pokemons("Pikachu", "Electric", 22.0, rand_lat(), rand_long(),R.drawable.pikachu))
        poke_list.add(Pokemons("Raichu", "Electric", 32.0, rand_lat(), rand_long(),R.drawable.raichu))
        poke_list.add(Pokemons("Squirtle", "Water", 20.0, rand_lat(), rand_long(),R.drawable.squirtle))
        poke_list.add(Pokemons("Umbreon", "Dark", 33.0, rand_lat(), rand_long(),R.drawable.umbreon))
    

    fun rand_lat(): Double 
        var x:Int=(Math.random()*10).toInt()
        var y=(Math.random()/100)
        if(x%2==0)
            return (current_lat+y)
        else
            return (current_lat-y)
    

    fun rand_long(): Double 
        var x:Int=(Math.random()*10).toInt()
        var y=(Math.random()/100)
        if(x%2==0)
            return (current_long+y)
        else
            return (current_long-y)
    

这是我的 AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.catchem" >

    <!--
         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.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/logo_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Catchem" >

        <!--
             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=".Display"
            android:exported="true"
            android:label="@string/title_activity_display" />
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是我的活动 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_
    android:layout_
    tools:context=".Display" />

另外,这是我在手机上运行应用程序时出现的错误:

Run Screenshot

【问题讨论】:

您应该提及您遇到的异常/错误!并且 Logcat 行应该作为文本发布。同样在标题中,因为那是您的问题。 【参考方案1】:

终于找到问题了!!!!

使用NETWORK_PROVIDER 而不是GPS_PROVIDER,它的工作原理就像一个魅力!

【讨论】:

以上是关于应用程序正在模拟器中定位,但在实际的 android 设备中运行时没有的主要内容,如果未能解决你的问题,请参考以下文章

Iphone上的滑块崩溃程序,但在模拟器上工作

HealthKit 授权已授予并在模拟器上工作,但不在实际设备上

React-Native,Pdf 在 android 模拟器上显示,但在实际的 android 设备上出现错误

HealthKit 会不断更新模拟器上的样本数据,但不会更新 Apple Watch 上的实际数据

我的应用程序正在模拟器上运行并完全运行,但在物理设备上崩溃

启动远程程序时出错:正在启动或挂起