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

标签 java android android-permissions okhttp

当我在模拟器中运行下面的代码时,它工作得很好。但是当我在真实设备中运行它时,它不断崩溃并且很少工作(几乎在我重新安装时第一次启动时它一直工作)。但是当我省略与位置相关的代码行时,它工作得很好(我每行都用 //** 来指示它们)。我刚刚学习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);
        }
    });
}

最佳答案

您是否在代码中请求了位置权限?我认为您错过了这些,这将是在实际设备上崩溃的唯一原因。查看此链接 如果您按照此操作,我相信您的问题将会得到解决

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

关于java - 当我使用 LocationManager.getLastKnowLocation() 时,应用程序在真实设备中的第二次启动时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60185262/

相关文章:

java - 内存中字节的大小 - Java

java - 以编程方式为 Android 按钮添加边距

android - Android 中的动态权限

android - 如何获取位置?

java - 解析Json阿拉伯语文本

android - 在 Android Fragment 中允许权限导致应用程序崩溃?

java - 如何将平均值放入 arrayList 中,以及如何将输入文件中的分数放入自己的 arrayList 中?

java - 如何将 Android 应用构建为系统服务

java - 在 wildfly-9.0.2.Final 中未找到类型为 'javax.sql.DataSource' 的接口(interface)的 EJB

java.lang.StringIndexOutOfBoundsException : length=10684; index=10684