我试图通过单击按钮来访问位置并在文本视图中显示纬度和经度。
这是我的代码:
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends Activity {
TextView textView, textView1;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView1 = findViewById(R.id.textView2);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean enableOnly = true;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(enableOnly);
for (String provider : providers) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
textView.setText((int) location.getLatitude());
textView1.setText((int) location.getLatitude());
} else {
Toast.makeText(MainActivity.this, "sorry", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}
});
}
}
我正在测试的AVD在Android 8.1上 我还在AndroidManifest中设置了用户权限,以访问粗略和精细的位置。位置权限也已授予该应用。
但是,每当我单击按钮时,都不会发生任何事情。 请帮帮我。
答案 0 :(得分:0)
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
//do your task
}
此代码也仅适用于您提到的上述棉花糖设备
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
}
答案 1 :(得分:0)
使用此代码:
LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();
private Location getLastKnownLocation() {
mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
答案 2 :(得分:0)
抱歉,我没有看到您的许可。 现在,只要授予权限,就使用setUpGPS:
Application.Current.Dispatcher.BeginInvoke(new System.Action(() => {
/* code you want to run on the GUI thread goes here */
})).Wait();
onLocationChanged方法具有两个方法:getLatitude和getLongitude。这些是用户的位置点。您可以在double变量中传递它们并使用它们。