首页 > 解决方案 > 根据我当前的位置每秒更新文本视图

问题描述

我使用 google play-services-location 获取当前位置并使用函数显示纬度和经度getLocation()

纬度和经度是两个不同的TextView

但现在我想每秒更新纬度和经度,但它有一些问题。

我一直在尝试使用线程类,但没有得到结果。

public class MainActivity extends AppCompatActivity {

 public String latitude, longitude;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    requestPermission();

    Thread thread = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            getLocation();
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    thread.start();


}

private void requestPermission(){
    ActivityCompat.requestPermissions(this,new String[]{ACCESS_FINE_LOCATION},1);
}

public void getLocation(){

    FusedLocationProviderClient
        client = LocationServices.getFusedLocationProviderClient(this);

        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        client.getLastLocation().addOnSuccessListener(MainActivity.this,new OnSuccessListener<Location>(){

                    @Override
                    public void onSuccess(Location location) {

                        if(location!=null){

                            latitude = Double.toString(location.getLatitude());
                            TextView textView = findViewById(R.id.latitude_text);
                            textView.setText( "Latitude :- " + latitude );

                            longitude = Double.toString(location.getLongitude());
                            textView = findViewById(R.id.longitude_text);
                            textView.setText("Longitude :- " + longitude );

                        }
                    }
                }
        );

 }
}

标签: javaandroidandroid-studio

解决方案


您可以像这样在方法结束时使用postDelayed方法HandlergetLocation()

  handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getLocation();
            }
        }, 1000);

推荐阅读