java - 根据我当前的位置每秒更新文本视图
问题描述
我使用 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 );
}
}
}
);
}
}
解决方案
您可以像这样在方法结束时使用postDelayed
方法Handler
getLocation()
handler.postDelayed(new Runnable() {
@Override
public void run() {
getLocation();
}
}, 1000);
推荐阅读
- javascript - 如何仅将选中的复选框放入数据库
- pandas - Pandas - 将多行数据合并到单行
- javascript - 加载 URL 时如何将值传递给反应应用程序。?
- git - 永久删除 git 分支 bitbucket
- node.js - 在 reactjs 中安装 jsonwebtoken 包后,npm run build 命令失败
- google-places-api - 在 Google 地方信息中限制每位用户的请求
- linux - 完全抢占式内核和进程卡在 D 状态
- kubernetes - Tick_charts deployment.yaml 不能与 kubectl 一起应用
- php - Laravel 模型 - 未转换的特定列
- c++ - 在 C++ 中使用 this 指针初始化一个类对象