[英]Android Google maps, Moving Marker crash application
這是代碼“ MapsActiity.java”:
package com.example.myapplicationgooglemaps;
import ...
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback {
private static GoogleMap mMap;
private static Marker marker;
private static int x = -34;
private static int y = 151;
private static LatLng NextPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void myTimer() {
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
if (mMap != null) {
x = x + 1;
y = y + 1;
NextPosition = new LatLng(x, y);
marker.setPosition(NextPosition);
mMap.moveCamera(CameraUpdateFactory.newLatLng(NextPosition));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16f));
}
}
}, 2000, 1000);
}
/ *操縱地圖(一旦可用)。 准備使用地圖時會觸發此回調。 在這里我們可以添加標記或線條,添加偵聽器或移動攝像機。 在這種情況下,我們只需在澳大利亞悉尼附近添加一個標記。 如果設備上未安裝Google Play服務,則會提示用戶將其安裝在SupportMapFragment中。 僅當用戶安裝了Google Play服務並返回到應用程序后,才會觸發此方法。 * /
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng position = new LatLng(x, y);
marker = mMap.addMarker(new MarkerOptions().position(position).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
myTimer();
}
}
嘗試執行此行后,應用崩潰。
marker.setPosition(NextPosition);
誰能解釋我的問題在哪里? 謝謝!
發生崩潰是因為您沒有在UIThread中運行此代碼。
您可以使用runOnUiThread
並為Runnable()
實現第二個強制性run()
方法,以與TimerTask一起使用。
嘗試用以下代碼替換myTimer()
代碼:
public void myTimer() {
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run () {
if (mMap != null) {
x = x + 1;
y = y + 1;
NextPosition = new LatLng(x, y);
marker.setPosition(NextPosition);
mMap.moveCamera(CameraUpdateFactory.newLatLng(NextPosition));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16f));
}
}
});
}
}, 2000, 1000);
}
另請參閱相關線程:
java.lang.IllegalStateException:不在主線程Google Maps上
Android添加地圖標記錯誤:java.lang.IllegalStateException:不在主線程上
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.