//**
表示)。我刚刚学习了1个月的Android开发,所以犯了很多错误。现在,我确实需要获取当前位置的纬度和经度。请帮我)。顺便说一下,真正的设备是Redmi 8 Android 9@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetCityName = findViewById(R.id.get_city_name);
CityName = findViewById(R.id.city_name);
temperature = findViewById(R.id.temperature);
//**if (ContextCompat.checkSelfPermission(this, PERMISSION_STRING) != PackageManager.PERMISSION_GRANTED){
//**ActivityCompat.requestPermissions(this, new String[]{PERMISSION_STRING}, 6699);
//**}
//**final LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//**final String Gps_provider = lm.getBestProvider(new Criteria(), true);
//**final Location location = lm.getLastKnownLocation(Gps_provider);
GetCityName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//*String longgg = String.valueOf(location.getLongitude());
//*String lattt = String.valueOf(location.getLatitude());
api_key(lattt,longgg);
}
});
}//get the weather data with current latitude and longtitude
private void api_key(String Lat,String Longg) {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("https://api.openweathermap.org/data/2.5/weather?lat="+Lat+"&lon="+Longg+"&appid=a6f41d947e0542a26580bcd5c3fb90ef&units=metric")
.get()
.build();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Response response= client.newCall(request).execute();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String responseData= response.body().string();
try {
JSONObject json=new JSONObject(responseData);
String name = json.getString("name");
JSONObject temp1= json.getJSONObject("main");
String Temperature=String.valueOf(temp1.getDouble("temp"));
setText(CityName,name);
setText(temperature, Temperature);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}catch (IOException e){
e.printStackTrace();
}
}//This simply use to set text to TextView
private void setText(final TextView text, final String value){
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(value);
}
});
}
当我在模拟器中运行以下代码时,它完全可以正常工作。但是,当我在真实设备中运行它时,它总是崩溃,几乎无法工作(几乎在它第一次启动时一直都在工作...