位置不停地显示并持续更新。

huangapple go评论76阅读模式
英文:

Location Doesn't Stop Showing And Keep On Updating

问题

以下是您提供的代码的翻译部分:

package com.example.mymap;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    LocationManager locationManager;
    LocationListener locationListener;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // 获取 SupportMapFragment 并在地图准备就绪时收到通知。
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                mMap.clear();
                LatLng Helsinki = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.addMarker(new MarkerOptions().position(Helsinki).title("Here!").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(Helsinki));
                Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                try {
                    List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                    if (addressList != null && addressList.size() > 0) {
                        String address = "";
                        if (addressList.get(0).getThoroughfare() != null) {
                            address += addressList.get(0).getThoroughfare() + " ";
                        }

                        if (addressList.get(0).getLocality() != null) {
                            address += addressList.get(0).getLocality() + " ";
                        }

                        if (addressList.get(0).getPostalCode() != null) {
                            address += addressList.get(0).getPostalCode() + " ";
                        }

                        if (addressList.get(0).getAdminArea() != null) {
                            address += addressList.get(0).getAdminArea();
                        }

                        Toast.makeText(MapsActivity.this, address, Toast.LENGTH_SHORT).show();
                        Log.i("Address", address);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        if (Build.VERSION.SDK_INT <= 23) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                mMap.clear();
                LatLng Helsinki = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
                mMap.addMarker(new MarkerOptions().position(Helsinki).title("Here!").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(Helsinki));
            }
        }
    }
}

希望这对您有所帮助!如果您有任何进一步的问题,请随时问我。

英文:

I Made An App That Gets The User's Location And Shows Information About The Location.
But The Problem Is That It Doesn't Stop Showing Location And It's Keep On Updating On The Same Location.
I Made A Toast And Once The App Runs Then The Toast Also Doesn't Go Off The Screen.
It's Like The Location Is Running An Infinite Loop Or Something But I Just Can't Figure It Out.

    package com.example.mymap;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
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;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
mMap.clear();
LatLng Helsinki = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(Helsinki).title(&quot;Here!&quot;).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Helsinki));
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List&lt;Address&gt; addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addressList != null &amp;&amp; addressList.size() &gt; 0) {
String address = &quot;&quot;;
if (addressList.get(0).getThoroughfare() != null) {
address += addressList.get(0).getThoroughfare() + &quot; &quot;;
}
if (addressList.get(0).getLocality() != null) {
address += addressList.get(0).getLocality() + &quot; &quot;;
}
if (addressList.get(0).getPostalCode() != null) {
address += addressList.get(0).getPostalCode() + &quot; &quot;;
}
if (addressList.get(0).getAdminArea() != null) {
address += addressList.get(0).getAdminArea();
}
Toast.makeText(MapsActivity.this, address, Toast.LENGTH_SHORT).show();
Log.i(&quot;Address&quot;, address);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
if (Build.VERSION.SDK_INT &lt;= 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.clear();
LatLng Helsinki = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(Helsinki).title(&quot;Here!&quot;).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Helsinki));
}
}
}
}

Debugging Details But The Debugger Was Manually Stopped As It Was Updating The Same Location Infinitely.

I/zygote: Do partial code cache collection, code=29KB, data=27KB
I/zygote: After code cache collection, code=29KB, data=28KB
I/zygote: Increasing code cache capacity to 128KB
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/OpenGLRenderer: HWUI GL Pipeline
I/zygote: Do partial code cache collection, code=61KB, data=44KB
I/zygote: After code cache collection, code=61KB, data=44KB
Increasing code cache capacity to 256KB
D/: HostConnection::get() New Host Connection established 0xa3fb3f80, tid 8221
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, 
retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xa6b870a0: maj 2 min 0 rcv 2
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
D/EGL_emulation: eglMakeCurrent: 0xa6b870a0: ver 2 0 (tinfo 0xa6b83900)
D/: HostConnection::get() New Host Connection established 0xa405d6c0, tid 8218
D/EGL_emulation: eglMakeCurrent: 0xa6b870a0: ver 2 0 (tinfo 0xa6b83900)
D/EGL_emulation: eglCreateContext: 0x91663780: maj 1 min 0 rcv 1
D/EGL_emulation: eglMakeCurrent: 0x91663780: ver 1 0 (tinfo 0x9111b310)
D/EGL_emulation: eglMakeCurrent: 0xa6b870a0: ver 2 0 (tinfo 0xa6b83900)
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
D/EGL_emulation: eglMakeCurrent: 0xa6b870a0: ver 2 0 (tinfo 0xa6b83900)
I/zygote: Do full code cache collection, code=123KB, data=120KB
After code cache collection, code=102KB, data=81KB
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:6
Selected remote version of com.google.android.gms.googlecertificates, version &gt;= 6
W/zygote: Skipping duplicate class check due to unrecognized classloader
D/EGL_emulation: eglMakeCurrent: 0xa6b870a0: ver 2 0 (tinfo 0xa6b83900)
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
D/EGL_emulation: eglMakeCurrent: 0xa6b870a0: ver 2 0 (tinfo 0xa6b83900)
I/zygote: Do partial code cache collection, code=122KB, data=97KB
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France
I/zygote: After code cache collection, code=122KB, data=97KB
Increasing code cache capacity to 512KB
I/Address: Avenue de Suffren Paris 75007 &#206;le-de-France

答案1

得分: 0

if (Build.VERSION.SDK_INT <= 23) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 100, locationListener);
} else {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 100, locationListener);
        Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        mMap.clear();
        LatLng Helsinki = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
        mMap.addMarker(new MarkerOptions().position(Helsinki).title("Here!").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(Helsinki));
    }
}

上面的代码中值发生了变化。
只需将更新时间从0分钟和0米更改为像5分钟和100米这样的值。这将解决所有问题。

代码中的单行示例:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 200, locationListener);
英文:
if (Build.VERSION.SDK_INT &lt;= 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 100, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 100, locationListener);
Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.clear();
LatLng Helsinki = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(Helsinki).title(&quot;Here!&quot;).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Helsinki));
}
}
}

The Above Code Has Changement In The Values.
Just Have To Change The Time Of Updating From 0 Minutes And 0 Meters To Some Value Like 5 Minute And 100 Meters. And It Will Solve Everything.

Single Line Example From The Code Itself:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 200, locationListener);

huangapple
  • 本文由 发表于 2020年9月21日 22:49:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63994735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定