getLastLocation返回俄罗斯中部的随机位置

问题描述

我竭力尝试通过SMS向用户发送最后知道的位置,但是lastKnownLocation()总是在俄罗斯沿海无处中间返回null或随机位置,因此不胜感激! 我之前尝试通过最初运行的LocationManager来获取getLocation,但后来每次都重新调整为null。 我正在按照文档中给出的步骤 https://developer.android.com/training/location/retrieve-current

package com.r30.wec_task;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;


import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class SosActivity extends AppCompatActivity {
    private static final int REQUEST_LOCATION = 1;
    private static final int REQUEST_SMS = 1;
    private FusedLocationProviderClient fusedLocationClient;

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users").child(user.getUid());
   // LocationManager locationManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sos2);
        ActivityCompat.requestPermissions( this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);


    }
    String emergencyContactNo;
    @Override
    protected void onStart() {
        super.onStart();
        ImageButton sosBtn = findViewById(R.id.sosButton);
        //Get Emergency Contact from DataBase
        userRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                emergencyContactNo = snapshot.child("eContact").getValue(String.class).toString();
                Toast.makeText(SosActivity.this,emergencyContactNo,Toast.LENGTH_SHORT);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(SosActivity.this,"Error getting your emergency contact",Toast.LENGTH_SHORT);
            }
        });
        //Button Click sends SOS signal + GPS Co-ordinates
        sosBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //get Location of user
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    OnGPS();
                } else {
                    sendLocation();
                }
            }
        });
    }
    private void OnGPS() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("Yes",new  DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog,int which) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        }).setNegativeButton("No",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog,int which) {
                dialog.cancel();
            }
        });
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
    String ans;
    private void sendLocation() {
        if (ActivityCompat.checkSelfPermission(
                SosActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                SosActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
        } else {
            fusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this,new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Logic to handle location object
                                ans=location.getLongitude()+","+location.getLongitude();
                                Intent intent=new Intent(SosActivity.this,SosActivity.class);
                                PendingIntent pi=PendingIntent.getActivity(getApplicationContext(),intent,0);
                                //Get the SmsManager instance and call the sendTextMessage method to send message
                                SmsManager sms=SmsManager.getDefault();
                                sms.sendTextMessage(emergencyContactNo,null,"SOS my location is http://maps.google.com/maps?q="+ans,pi,null);
                                Toast.makeText(getApplicationContext(),"Message Sent successfully!"+emergencyContactNo,Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        }
    }
}

解决方法

您两次使用经度:

ans=location.getLongitude()+","+location.getLongitude();

应该是:

ans=location.getLatitude()+","+location.getLongitude();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...