我正在使用智能位置库。我正在尝试使用经度和纬度获取位置。但是我的代码在api 16中完美运行。但是我在api 21上检查了它。相同的代码没有显示任何东西..也没有崩溃。我已添加权限但仍然无法正常工作。 请检查一下。帮助将不胜感激。 谢谢
我使用过此库:https://github.com/mrmans0n/smart-location-lib
public class MainActivity extends AppCompatActivity {
private Double lat;
private Double lon;
private Context context;
private Button address_button;
private static final int PERMISSION_REQUEST_CODE =11 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
address_button= (Button) findViewById(R.id.button_address);
address_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)){
new AlertDialog.Builder(MainActivity.this)
.setTitle("Call Permission")
.setMessage("Hi there! We can't access locationanyone without the Location permission, could you please grant it?")
.setPositiveButton("Yep", new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick(DialogInterface dialogInterface, int i) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_CODE);
}
})
.setNegativeButton("No thanks", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, ":(", Toast.LENGTH_SHORT).show(); }
}).show();
}else {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_CODE);
}
} else{
SmartLocationCityName();
}
}else{
SmartLocationCityName();
}
}
});
}
@Override
protected void onStop() {
super.onStop();
SmartLocation.with(context).location().stop();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode== PERMISSION_REQUEST_CODE){
if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
SmartLocationCityName();
}
}
}
public void SmartLocationCityName(){
SmartLocation.with(context).location()
.start(new OnLocationUpdatedListener() {
@Override
public void onLocationUpdated(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
Toast.makeText(context,lat+" "+lon+" ",Toast.LENGTH_LONG).show();
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
Toast.makeText(context,lat+" "+lon+" "+cityName+"-"+"-"+stateName+"-"+countryName,Toast.LENGTH_LONG).show();
}catch (IOException ex){
}
}
});
}
}