当我使用LocationManager.getLastKnowLocation()时,在实际设备中第二次启动时应用程序崩溃。

问题描述 投票:0回答:1
当我在模拟器中运行以下代码时,它完全可以正常工作。但是当我在真实的设备上运行它时,它总是崩溃并且几乎无法工作(几乎在我重新安装后首次启动时几乎一直都能工作)但是当我忽略与位置有关的代码行时,它就可以正常工作(我在每行中都用//**表示)。我刚刚学习了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); } }); }

当我在模拟器中运行以下代码时,它完全可以正常工作。但是,当我在真实设备中运行它时,它总是崩溃,几乎无法工作(几乎在它第一次启动时一直都在工作...
java android-studio android-permissions okhttp
1个回答
0
投票
您是否在代码中要求获得位置许可?我认为您缺少这些,这将是在实际设备上崩溃的唯一原因。查看此链接如果您遵循此步骤,我相信您会解决您的问题
© www.soinside.com 2019 - 2024. All rights reserved.