gpt4 book ai didi

java - 根据我当前的位置每秒更新 TextView

转载 作者:行者123 更新时间:2023-12-02 01:04:22 28 4
gpt4 key购买 nike

我使用 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 );

}
}
}
);

}
}

最佳答案

您可以在 getLocation() 方法末尾使用 HandlerpostDelayed 方法,如下所示

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

关于java - 根据我当前的位置每秒更新 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745940/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com