在我的应用程序中,我正在绘制从Web服务到Google地图的一组纬度和经度,但当网络服务中的纬度和经度发生变化时,标记不会移动。当我关闭并打开应用程序时,它会更新更改,但我需要移动标记而不关闭并重新启动应用程序。我的更新代码如下所示。
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/* new DownloadJSON().execute();
setUpMapIfNeeded(rootView); */
/*
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.d("Data in Log", "");
}
}, 10*1000);*/
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 000, 10, this);
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
mMap.addMarker(options);
mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
// pubname = json.getString("PubName");
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
// map.put("PubName", json.getString("PubName"));
//map.put("PubID", json.getString("PubID"));
map.put("Latitude", json.getString("Latitude"));
map.put("Longitude", json.getString("Longitude"));
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:3)
您可以使用处理程序更新location.Inside run()只需调用该webservice.And将标记放在当前位置。
// Call current location API after 3 Min
handler.postDelayed(run, 3000 * 60);
Runnable run = new Runnable() {
@Override
public void run() {
if (isConnected(context)) {
new CurrentPosTask().execute();
} else {
Toast.makeText(context, "No internet connection",
Toast.LENGTH_LONG).show();
}
}
};
不要忘记调用下面的方法到onDestroy()方法
// Stop the handler
handler.removeCallbacks(run);
希望它会对你有所帮助。让我知道一旦完成。
答案 1 :(得分:0)
您必须设置重复警报以检查intervel中的Web服务
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
60 * 1000, alarmIntent);
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
5000, alarmIntent);
并在警报接收器类中调用Web服务并更新地图位置
public class AlarmReceiverextends WakefulBroadcastReceiver {
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
完整教程看看developers.android https://developer.android.com/training/scheduling/alarms.html