首页 > 解决方案 > 当我使用 LocationManager.getLastKnowLocation() 时,应用程序在真实设备中的第二次启动时崩溃

问题描述

当我在模拟器中运行下面的代码时,它工作得很好。但是当我在真实设备上运行它时,它一直在崩溃并且它很少能工作(几乎所有时间它在我重新安装时第一次启动时都能工作)。但是当我省略与位置相关的代码行时,它工作正常.(我用//**每一行表示它们)。我刚刚学习 Android 开发 1 个月,所以我犯了很多错误。现在我真的需要获取当前位置的经纬度。请帮助我)。顺便说一下,真正的设备是 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);
        }
    });
}

标签: javaandroidandroid-permissionsokhttp

解决方案


您是否在代码中要求位置许可?我认为您错过了这些,这将是在实际设备上崩溃的唯一原因。如果您遵循此链接,请查看此链接,我相信您会解决问题

https://developer.android.com/training/location/retrieve-current


推荐阅读