gpt4 book ai didi

java - Android 位置和线程

转载 作者:行者123 更新时间:2023-12-01 05:51:58 24 4
gpt4 key购买 nike

我正在尝试大量使用位置 API。我做一个简单的 Activity 来使用 LocationListener 刷新 TextView 没有任何问题,这很好。

问题是,我必须将所有位置内容放入类似 Manager 类之类的东西中,该类由主 Activity 调用。所以我必须将所有内容放在该类中并将位置传递给 Activity 。这是 Activity :

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
g = new GPSManager(getApplicationContext());
t = new Thread(g);
t.start();
updateWithNewLocation(g.getLocation());
}
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.loca);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}

这是“Manager”类:

public GPSManager(Context context) {
locationManager = (LocationManager)context.getSystemService(service);
String service = Context.LOCATION_SERVICE;
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
}
public Location getLocation() {
return this.location;
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Manager.this.location=location;
}
public void onProviderDisabled(String provider){
locationManager.removeUpdates(this);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};

@Override
public void run() {
Looper.prepare();
locationManager.requestLocationUpdates(provider, 0, 0,
locationListener);
location = locationManager.getLastKnownLocation(provider);
Looper.loop();
Looper.myLooper().quit();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
locationManager.removeUpdates(locationListener);
}

我遇到的问题是,它根本不起作用!如果我将此代码放入 Activity 中,不涉及任何线程,效果会很好。但这样,它只是说“找不到位置”。我需要让 Manager 类始终监听更改,因此当我请求当前位置时会更新。

最佳答案

选项#1:删除“manager”类。

选项#2:使“manager”类成为一个Service

选项#3:使“manager”类成为自定义Application

选项 #4:用 HandlerThread 替换 Thread

关于java - Android 位置和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4376918/

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