0
我試圖使用一個在我的MainActivity的onCreate函數中初始化的locationlistener。 在該函數中,還必須詢問位置,但在調試時發現,偵聽器在函數運行後開始給出座標。等待也沒有奏效。活動加載時獲取位置(在onCreate中)
我該如何實現,在創建活動時獲取位置,或者如何設法通過線程對活動視圖進行更改?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
if(data.gB_GPS_searched == false) {
data.gB_GPS_searched = true;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
data.locationListener = new GPS();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, data.locationListener);
}
data.set_pier("Bodenwerder");
data.set_pier(data.get_closest_pier());
String cityname = data.get_pier_name();
if(cityname != null)
((TextView)findViewById(R.id.current_city)).setText(cityname);
}
聽者基本上是這樣的。
public class GPS implements android.location.LocationListener {
@Override
public void onLocationChanged(Location location) {
if(data.get_gps) {
try {
data.Latitute = ((Double)(location.getLatitude()*100)).intValue();
data.Longitute = ((Double)(location.getLongitude()*100)).intValue();
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
...
}
我使用的數據類是用於保存和傳送接收的數據...
public class data {
public static GPS locationListener;
public static int Latitute = 0;
public static int Longitute = 0;
public static boolean gB_GPS_searched = false;
private static Map<String,int[]> coordinates = new HashMap<String,int[]>();
private static int gI_current_city = -1;
private static List<String> g_piernames = new ArrayList<>();
public static void set_pier(String pS_piername)
{
for(int i = 0; i < g_piernames.size(); i++)
if(g_piernames.get(i).equals(pS_piername))
{
gI_current_city = i;
i = g_piernames.size();
}
}
public static String get_pier_name()
{
return g_piernames.get(gI_current_city);
}
public static String get_closest_pier()
{
String cityname = "";
int x = -1;
int y = -1;
for (Object key : coordinates.keySet().toArray()) {
if(x == -1)
{
x = coordinates.get(key.toString())[0];
y = coordinates.get(key.toString())[1];
cityname = key.toString();
}else{
if(pyth(Math.abs(Latitute-x),Math.abs(Longitute-y)) > pyth(Math.abs(Latitute-coordinates.get(key.toString())[0]),Math.abs(Longitute-coordinates.get(key.toString())[1])))
{
x = coordinates.get(key.toString())[0];
y = coordinates.get(key.toString())[1];
cityname = key.toString();
}
}
}
return cityname;
}
private static int pyth(int a, int b)
{
return ((Double)Math.sqrt(a*a+b*b)).intValue();
}
}
tbh這是我的第一個android項目。我需要在哪裏放置文件和編譯代碼? –
@TimoTreichel我已經更新了答案,請看看。 –
我更新了你的答案,它對我來說是如何工作的 –