如何在Android Studio中获取当前应用的纬度、经度和地址信息。

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

How to get the Get Current Latitude, Longitude and Address for my app in Android Studio

问题

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

这是我的下面的编码,它给了我一个输出,但不是我的确切位置。(它给了我在美国某个位置的信息)。
我使用了融合定位提供程序 API 来实现获取用户当前位置的功能,并且还创建了意图服务来使用地理编码器从纬度和经度获取地址。
请帮我解决这个项目中的问题。
以下是我的编码:

这是我的主活动:

public class ContactDetails extends AppCompatActivity {
    private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;

    public TextView LatLong;
    ProgressBar pb;
    private ResultReceiver resultReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_details);
        resultReceiver = new AddressResultReceiver(new Handler());

        LatLong = (TextView) findViewById(R.id.latlong);
        pb = (ProgressBar) findViewById(R.id.progressBar);

        findViewById(R.id.buttonGetCurrentLocation).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(
                        getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(
                            ContactDetails.this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            REQUEST_CODE_LOCATION_PERMISSION
                    );
                } else {
                    getCurrentLocation();
                }
            }
        });

        // ... (省略其他代码)
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // ... (省略其他代码)
    }

    private void getCurrentLocation() {
        // ... (省略其他代码)
    }

    private void fetchAddressFromLatLong(Location location) {
        // ... (省略其他代码)
    }

    private class AddressResultReceiver extends ResultReceiver {
        // ... (省略其他代码)
    }
}

FetchAddressIntentService.java:

public class FetchAddressIntentService extends IntentService {
    private ResultReceiver resultReceiver;

    public FetchAddressIntentService() {
        super("FetchAddressIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        // ... (省略其他代码)
    }

    private void deliverResultToReceiver(int resultCode, String addressMessage) {
        // ... (省略其他代码)
    }
}

Constant.java 文件:

class Constants {
    private static final String PACKAGE_NAME = "com.example.registration";
    static final String RESULT_DATA_KEY = PACKAGE_NAME + ".RESULT_DATA_KEY";
    static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
    static final String LOCATION_DATA_EXTRA = PACKAGE_NAME + ".LOCATION_DATA_EXTRA";
    static final int SUCCESS_RESULT = 1;
    static final int FAILURE_RESULT = 0;
}

请注意,我只翻译了您提供的代码部分,去掉了代码中的注释和无关的内容。如果您有任何问题或需要进一步的帮助,请随时告诉我。

英文:

This is my coding below, it is giving me an output but its not my exact location. (Its giving me some location in USA).
I implemented a facility to get the user's current location using the Fused Location Provider API. and also i created intent service to fetch address from latitude and longitude using Geocoder.
Please help me out with this issue for my project.
Here is my coding below:

This is my main Activity

public class ContactDetails extends AppCompatActivity {
private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;
public TextView  LatLong;
ProgressBar pb;
private ResultReceiver resultReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_details);
resultReceiver=new AddressResultReceiver(new Handler());
LatLong = (TextView) findViewById(R.id.latlong);
pb = (ProgressBar) findViewById(R.id.progressBar);
findViewById(R.id.buttonGetCurrentLocation).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(
getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
ContactDetails.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION_PERMISSION
);
} else {
getCurrentLocation();
}
}
});
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
private void getCurrentLocation() {
pb.setVisibility(View.VISIBLE);
final LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//  return;
}
LocationServices.getFusedLocationProviderClient(ContactDetails.this)
.requestLocationUpdates(locationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
LocationServices.getFusedLocationProviderClient(ContactDetails.this)
.removeLocationUpdates(this);
if (locationResult != null && locationResult.getLocations().size() > 0) {
int latestLocationIndex = locationResult.getLocations().size() - 1;
double latitude =
locationResult.getLocations().get(latestLocationIndex).getLatitude();
double longitude =
locationResult.getLocations().get(latestLocationIndex).getLongitude();
LatLong.setText(String.format("Latitude: %s\nLongtitude: %s", latitude, longitude));
Location location= new Location("providerNA");
location.setLatitude(latitude);
location.setLongitude(longitude);
fetchAddressFromLatLong(location);
} else {
pb.setVisibility(View.GONE);
}
}
}, Looper.getMainLooper());
}
private void fetchAddressFromLatLong(Location location){
Intent intent=new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, resultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, location);
startService(intent);
}
private class AddressResultReceiver extends ResultReceiver {
AddressResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if(resultCode== Constants.SUCCESS_RESULT) {
add.setText(resultData.getString(Constants.RESULT_DATA_KEY));
}else {
Toast.makeText(ContactDetails.this, resultData.getString(Constants.RESULT_DATA_KEY), Toast.LENGTH_SHORT).show();
}
pb.setVisibility(View.GONE);
}
} 

FetchAddressIntentService.java

public class FetchAddressIntentService extends IntentService {
private ResultReceiver resultReceiver;
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if(intent != null) {
String errorMessage="";
resultReceiver=intent.getParcelableExtra(Constants.RECEIVER);
Location location= intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
if(location==null){
return;
}
Geocoder geocoder= new Geocoder(this, Locale.getDefault());
List<Address> addresses=null;
try {
addresses=geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (Exception exception) {
errorMessage= exception.getMessage();
}
if (addresses== null || addresses.isEmpty()){
deliverResultToReceiver(Constants.FAILURE_RESULT,errorMessage);
}else {
Address address=addresses.get(0);
ArrayList<String> addressFragments= new ArrayList<>();
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++){
addressFragments.add(address.getAddressLine(i));
}
deliverResultToReceiver(
Constants.SUCCESS_RESULT,
TextUtils.join(
Objects.requireNonNull(System.getProperty("line.separator")),
addressFragments
)
);
}
}
}
private void deliverResultToReceiver(int resultCode, String addressMessage) {
Bundle bundle=new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, addressMessage);
resultReceiver.send(resultCode, bundle);
}
}

Constant.java file


class Constants {
private static final String PACKAGE_NAME="com.example.registration";
static final String RESULT_DATA_KEY= PACKAGE_NAME + ".RESULT_DATA_KEY";
static final String RECEIVER= PACKAGE_NAME+ ".RECEIVER";
static final String LOCATION_DATA_EXTRA = PACKAGE_NAME+ ".LOCATION_DATA_EXTRA";
static final int SUCCESS_RESULT=1;
static final int FAILURE_RESULT= 0;
}

Screenshot of the app

答案1

得分: 1

如果您正在模拟器上运行应用程序,那么您应该发送一个位置来进行模拟。默认位置是GooglePlex的位置,这就是您正在接收的位置。

否则,可能您的精确度不正确。

尝试查看这个问题以模拟位置。

希望能有所帮助。

英文:

If you are running your app on the simulator, then you should send a location to simulate it. The default is the location of GooglePlex, which is the one you are receiving.

Otherwise maybe your precission is not correct.

try to check this question for simulating locations.

Hope it helps.

huangapple
  • 本文由 发表于 2020年6月6日 01:13:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/62220768.html
匿名

发表评论

匿名网友

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

确定