implement saving settings to storage

git-svn-id: https://osmand.googlecode.com/svn/trunk@37 e29c36b1-1cfa-d876-8d93-3434fc2bb7b8
This commit is contained in:
Victor Shcherb 2010-05-06 14:55:49 +00:00
parent f150ba9823
commit 2fa9036f12
10 changed files with 254 additions and 140 deletions

View file

@ -21,6 +21,7 @@ import com.osmand.data.DataTileManager;
import com.osmand.data.Region;
import com.osmand.osm.Entity;
import com.osmand.osm.LatLon;
import com.osmand.osm.MapUtils;
import com.osmand.osm.Node;
import com.osmand.osm.OSMSettings;
import com.osmand.osm.Relation;
@ -74,16 +75,63 @@ public class DataExtraction {
private static boolean parseSmallFile = true;
private static boolean parseOSM = true;
private ArrayList<Way> mapWays;
private ArrayList<Amenity> amenities;
private ArrayList<Entity> buildings;
private ArrayList<Node> places;
private DataTileManager<Way> waysManager;
///////////////////////////////////////////
// 1. Reading data - preparing data for UI
public void testReadingOsmFile() throws ParserConfigurationException, SAXException, IOException, XMLStreamException {
InputStream stream ;
String f;
if(parseSmallFile){
stream = new FileInputStream(DefaultLauncherConstants.pathToOsmFile);
f = DefaultLauncherConstants.pathToOsmFile;
} else {
stream = new FileInputStream(DefaultLauncherConstants.pathToOsmBz2File);
f = DefaultLauncherConstants.pathToOsmBz2File;
}
long st = System.currentTimeMillis();
Region country;
if(parseOSM){
country = readCountry(f);
} else {
country = new Region(null);
country.setStorage(new OsmBaseStorage());
}
OsmExtractionUI ui = new OsmExtractionUI(country);
ui.runUI();
List<Long> interestedObjects = new ArrayList<Long>();
// MapUtils.addIdsToList(places, interestedObjects);
// MapUtils.addIdsToList(amenities, interestedObjects);
MapUtils.addIdsToList(waysManager.getAllObjects(), interestedObjects);
// MapUtils.addIdsToList(buildings, interestedObjects);
if (DefaultLauncherConstants.writeTestOsmFile != null) {
OSMStorageWriter writer = new OSMStorageWriter(country.getStorage().getRegisteredEntities());
OutputStream output = new FileOutputStream(DefaultLauncherConstants.writeTestOsmFile);
if (DefaultLauncherConstants.writeTestOsmFile.endsWith(".bz2")) {
output.write('B');
output.write('Z');
output = new CBZip2OutputStream(output);
}
writer.saveStorage(output, interestedObjects, false);
output.close();
}
System.out.println();
System.out.println("USED Memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1e6);
System.out.println("TIME : " + (System.currentTimeMillis() - st));
}
public Region readCountry(String path) throws IOException, SAXException{
InputStream stream = new FileInputStream(path);
long st = System.currentTimeMillis();
if(path.endsWith(".bz2")){
if (stream.read() != 'B' || stream.read() != 'Z')
throw new RuntimeException(
"The source stream must start with the characters BZ if it is to be read as a BZip2 stream.");
@ -92,16 +140,12 @@ public class DataExtraction {
}
System.out.println("USED Memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1e6);
long st = System.currentTimeMillis();
// preloaded data
final List<Node> places = new ArrayList<Node>();
final List<Entity> buildings = new ArrayList<Entity>();
final List<Amenity> amenities = new ArrayList<Amenity>();
places = new ArrayList<Node>();
buildings = new ArrayList<Entity>();
amenities = new ArrayList<Amenity>();
// highways count
final List<Way> mapWays = new ArrayList<Way>();
mapWays = new ArrayList<Way>();
OsmBaseStorage storage = new OsmBaseStorage(){
@Override
@ -117,6 +161,7 @@ public class DataExtraction {
@Override
public boolean acceptNodeToLoad(Node n) {
// TODO accept amenity for way! hospital, university, parking, fast_food...
if(Amenity.isAmenity(n)){
amenities.add(new Amenity(n));
}
@ -144,15 +189,12 @@ public class DataExtraction {
};
if (parseOSM) {
storage.parseOSM(stream);
}
System.out.println(System.currentTimeMillis() - st);
System.out.println("File parsed : " +(System.currentTimeMillis() - st));
// 1. found towns !
Region country = new Region(null);
country.setStorage(storage);
for (Node s : places) {
String place = s.getTag(OSMTagKey.PLACE);
if(place == null){
@ -188,45 +230,16 @@ public class DataExtraction {
}
DataTileManager<LatLon> waysManager = new DataTileManager<LatLon>();
waysManager = new DataTileManager<Way>();
for (Way w : mapWays) {
for (Node n : w.getNodes()) {
if(n != null){
LatLon latLon = n.getLatLon();
waysManager.registerObject(latLon.getLatitude(), latLon.getLongitude(), latLon);
if (w.getTag(OSMTagKey.NAME) != null) {
LatLon latLon = MapUtils.getWeightCenterForNodes(w.getNodes());
waysManager.registerObject(latLon.getLatitude(), latLon.getLongitude(), w);
}
}
/// way with name : МЗОР, ул. ...,
return country;
}
OsmExtractionUI ui = new OsmExtractionUI(country);
ui.runUI();
List<Long> interestedObjects = new ArrayList<Long>();
// MapUtils.addIdsToList(places, interestedObjects);
for(Amenity a : amenities){
interestedObjects.add(a.getNode().getId());
}
// MapUtils.addIdsToList(mapWays, interestedObjects);
// MapUtils.addIdsToList(buildings, interestedObjects);
if (DefaultLauncherConstants.writeTestOsmFile != null) {
OSMStorageWriter writer = new OSMStorageWriter(storage.getRegisteredEntities());
OutputStream output = new FileOutputStream(DefaultLauncherConstants.writeTestOsmFile);
output.write('B');
output.write('Z');
output = new CBZip2OutputStream(output);
writer.saveStorage(output, interestedObjects, true);
output.close();
}
System.out.println();
System.out.println("USED Memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1e6);
System.out.println("TIME : " + (System.currentTimeMillis() - st));
}
///////////////////////////////////////////
// 2. Showing UI
}

View file

@ -1,13 +0,0 @@
package com.osmand;
import com.osmand.map.ITileSource;
public class OsmandSettings {
public static boolean useInternetToDownloadTiles = DefaultLauncherConstants.loadMissingImages;
public static ITileSource tileSource = DefaultLauncherConstants.MAP_defaultTileSource;
public static boolean showPoiOverMap = true;
}

View file

@ -9,10 +9,6 @@ package com.osmand;
*/
public class ToDoConstants {
public int SAVE_SETTINGS_IN_ANDROID_BETWEEN_SESSION = 2;
// First of all switch off gps listener should be implemented
public int IMPLEMENT_ON_STOP_RESUME_ACTIVITY = 3;
// OsmandMapTileView.java have problem with class loading (LogFactory, MapTileDownloader) -
// it is not editable in editor ?
@ -21,7 +17,6 @@ public class ToDoConstants {
// common parts : work with cache on file system & in memory
public int EXTRACT_COMMON_PARTS_FROM_MAPPANEL_AND_OSMMAPVIEW = 5;
/**
* Write activity to show something about authors / donation ....
*/

View file

@ -13,12 +13,15 @@ import com.osmand.osm.LatLon;
import com.osmand.osm.MapUtils;
import com.osmand.osm.Node;
import com.osmand.osm.OSMSettings.OSMTagKey;
import com.osmand.osm.io.OsmBaseStorage;
public class Region {
private Entity entity;
private DataTileManager<Amenity> amenities = new DataTileManager<Amenity>();
private OsmBaseStorage storage;
private Map<CityType, Collection<City>> cities = new HashMap<CityType, Collection<City>>();
{
for(CityType type : CityType.values()){
@ -32,6 +35,14 @@ public class Region {
}
public OsmBaseStorage getStorage() {
return storage;
}
public void setStorage(OsmBaseStorage storage) {
this.storage = storage;
}
public void setEntity(Entity e){
this.entity = e;
}

View file

@ -55,12 +55,16 @@ public class OSMStorageWriter {
nodes.add((Node) entities.get(l));
} else if(entities.get(l) instanceof Way){
ways.add((Way) entities.get(l));
if(includeLinks){
toResolve.addAll(((Way)entities.get(l)).getNodeIds());
}
} else if(entities.get(l) instanceof Relation){
relations.add((Relation) entities.get(l));
if(includeLinks){
toResolve.addAll(((Relation)entities.get(l)).getMemberIds());
}
}
}
streamWriter.writeStartDocument();

View file

@ -0,0 +1,59 @@
package com.osmand;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import com.osmand.map.ITileSource;
import com.osmand.map.TileSourceManager;
import com.osmand.map.TileSourceManager.TileSourceTemplate;
public class OsmandSettings {
// These settings are stored in SharedPreferences
public static final String SHARED_PREFERENCES_NAME = "com.osmand.settings";
// this value string is synchronized with android.xml preference name
public static final String USE_INTERNET_TO_DOWNLOAD_TILES = "use_internet_to_download_tiles";
public static boolean isUsingInternetToDownloadTiles(Context ctx){
SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
return prefs.getBoolean(USE_INTERNET_TO_DOWNLOAD_TILES, true);
}
// this value string is synchronized with android.xml preference name
public static final String SHOW_POI_OVER_MAP = "show_poi_over_map";
public static boolean isShowingPoiOverMap(Context ctx){
SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
return prefs.getBoolean(SHOW_POI_OVER_MAP, false);
}
// this value string is synchronized with android.xml preference name
public static final String MAP_TILE_SOURCES = "map_tile_sources";
public static ITileSource getMapTileSource(Context ctx){
SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
String tileName = prefs.getString(MAP_TILE_SOURCES, null);
if(tileName != null){
List<TileSourceTemplate> list = TileSourceManager.getKnownSourceTemplates();
for(TileSourceTemplate l : list){
if(l.getName().equals(tileName)){
return l;
}
}
}
return DefaultLauncherConstants.MAP_defaultTileSource;
}
public static String getMapTileSourceName(Context ctx){
SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
String tileName = prefs.getString(MAP_TILE_SOURCES, null);
if(tileName != null){
return tileName;
}
return DefaultLauncherConstants.MAP_defaultTileSource.getName();
}
}

View file

@ -51,4 +51,9 @@ public class MainMenuActivity extends Activity {
ResourceManager.getResourceManager().indexingPoi();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}

View file

@ -4,9 +4,12 @@ import java.text.MessageFormat;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
@ -27,13 +30,16 @@ import com.osmand.views.POIMapLayer;
import com.osmand.views.PointLocationLayer;
public class MapActivity extends Activity implements LocationListener, IMapLocationListener {
private static final String KEY_LAST_LAT = "KEY_LAST_LAT";
private static final String KEY_LAST_LON = "KEY_LAST_LON";
private static final String KEY_LAST_ZOOM = "KEY_LAST_ZOOM";
/** Called when the activity is first created. */
private OsmandMapTileView mapView;
private boolean linkLocationWithMap = true;
private Location lastKnownLocation = null;
private ImageButton backToLocation;
private ImageButton backToMenu;
@ -42,6 +48,11 @@ public class MapActivity extends Activity implements LocationListener, IMapLocat
private POIMapLayer poiMapLayer;
protected void onRestoreInstanceState(Bundle savedInstanceState) {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -60,6 +71,20 @@ public class MapActivity extends Activity implements LocationListener, IMapLocat
locationLayer = new PointLocationLayer();
mapView.addLayer(locationLayer);
SharedPreferences prefs = getPreferences(MODE_WORLD_READABLE);
if(prefs != null && prefs.contains(KEY_LAST_LAT)){
mapView.setLatLon(prefs.getFloat(KEY_LAST_LAT, 0f), prefs.getFloat(KEY_LAST_LON, 0f));
mapView.setZoom(prefs.getInt(KEY_LAST_ZOOM, 3));
} else {
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = service.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
mapView.setLatLon(location.getLatitude(), location.getLongitude());
mapView.setZoom(14);
}
}
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.ZoomControls01);
zoomControls.setOnZoomInClickListener(new OnClickListener() {
@ -83,7 +108,8 @@ public class MapActivity extends Activity implements LocationListener, IMapLocat
if(!linkLocationWithMap){
linkLocationWithMap = true;
backToLocation.setVisibility(View.INVISIBLE);
if(lastKnownLocation != null){
if(locationLayer.getLastKnownLocation() != null){
Location lastKnownLocation = locationLayer.getLastKnownLocation();
mapView.setLatLon(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
}
}
@ -93,35 +119,40 @@ public class MapActivity extends Activity implements LocationListener, IMapLocat
backToMenu = (ImageButton)findViewById(R.id.BackToMenu);
backToMenu.setOnClickListener(new OnClickListener(){
backToMenu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
public void setLocation(Location location){
locationLayer.setLastKnownLocation(location);
if (location != null) {
if (linkLocationWithMap) {
mapView.setLatLon(location.getLatitude(), location.getLongitude());
}
} else {
if(!linkLocationWithMap){
backToLocation.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onLocationChanged(Location location) {
lastKnownLocation = location;
if(linkLocationWithMap){
mapView.setLatLon(location.getLatitude(), location.getLongitude());
locationLayer.setLastKnownLocation(lastKnownLocation);
}
setLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
// TODO when provider disabled reset lastKnownLocation!
setLocation(null);
}
@Override
@ -130,33 +161,34 @@ public class MapActivity extends Activity implements LocationListener, IMapLocat
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO when provider disabled reset lastKnownLocation!
if(LocationProvider.OUT_OF_SERVICE == status){
setLocation(null);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
@Override
protected void onPause() {
super.onPause();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
service.removeUpdates(this);
// TODO switch off gps
super.onPause();
SharedPreferences prefs = getPreferences(MODE_WORLD_READABLE);
Editor edit = prefs.edit();
edit.putFloat(KEY_LAST_LAT, (float) mapView.getLatitude());
edit.putFloat(KEY_LAST_LON, (float) mapView.getLongitude());
edit.putInt(KEY_LAST_ZOOM, mapView.getZoom());
edit.commit();
}
@Override
protected void onResume() {
// TODO switch on gps
super.onResume();
if(mapView.getMap() != OsmandSettings.tileSource){
mapView.setMap(OsmandSettings.tileSource);
if(mapView.getMap() != OsmandSettings.getMapTileSource(this)){
mapView.setMap(OsmandSettings.getMapTileSource(this));
}
if(mapView.getLayers().contains(poiMapLayer) != OsmandSettings.showPoiOverMap){
if(OsmandSettings.showPoiOverMap){
if(mapView.getLayers().contains(poiMapLayer) != OsmandSettings.isShowingPoiOverMap(this)){
if(OsmandSettings.isShowingPoiOverMap(this)){
mapView.addLayer(poiMapLayer);
} else {
mapView.removeLayer(poiMapLayer);
@ -178,10 +210,18 @@ public class MapActivity extends Activity implements LocationListener, IMapLocat
@Override
public void locationChanged(double newLatitude, double newLongitude, Object source) {
// when user start dragging
if(lastKnownLocation != null){
if(locationLayer.getLastKnownLocation() != null){
linkLocationWithMap = false;
if (backToLocation.getVisibility() != View.VISIBLE) {
runOnUiThread(new Runnable() {
@Override
public void run() {
backToLocation.setVisibility(View.VISIBLE);
}
});
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
@ -192,10 +232,10 @@ public class MapActivity extends Activity implements LocationListener, IMapLocat
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.map_show_location){
float f= (Runtime.getRuntime().totalMemory())/ 1e6f;
String text = MessageFormat.format("Latitude : {0}, longitude : {1}, zoom : {2}, memory : {3}", mapView.getLatitude(),
mapView.getLongitude(), mapView.getZoom(), f);
if (item.getItemId() == R.id.map_show_location) {
float f = (Runtime.getRuntime().totalMemory()) / 1e6f;
String text = MessageFormat.format("Latitude : {0}, longitude : {1}, zoom : {2}, memory : {3}", mapView.getLatitude(), mapView
.getLongitude(), mapView.getZoom(), f);
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
return true;
} else if (item.getItemId() == R.id.map_show_settings) {

View file

@ -2,6 +2,9 @@ package com.osmand.activities;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
@ -16,9 +19,6 @@ import com.osmand.map.TileSourceManager;
import com.osmand.map.TileSourceManager.TileSourceTemplate;
public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener {
private static final String use_internet_to_download_tiles = "use_internet_to_download_tiles";
private static final String map_tile_sources = "map_tile_sources";
private static final String show_poi_over_map = "show_poi_over_map";
private CheckBoxPreference showPoiOnMap;
private CheckBoxPreference useInternetToDownloadTiles;
@ -29,12 +29,12 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_pref);
PreferenceScreen screen = getPreferenceScreen();
useInternetToDownloadTiles =(CheckBoxPreference) screen.findPreference(use_internet_to_download_tiles);
useInternetToDownloadTiles = (CheckBoxPreference) screen.findPreference(OsmandSettings.USE_INTERNET_TO_DOWNLOAD_TILES);
useInternetToDownloadTiles.setOnPreferenceChangeListener(this);
showPoiOnMap =(CheckBoxPreference) screen.findPreference(show_poi_over_map);
showPoiOnMap =(CheckBoxPreference) screen.findPreference(OsmandSettings.SHOW_POI_OVER_MAP);
showPoiOnMap.setOnPreferenceChangeListener(this);
tileSourcePreference =(ListPreference) screen.findPreference(map_tile_sources);
tileSourcePreference =(ListPreference) screen.findPreference(OsmandSettings.MAP_TILE_SOURCES);
tileSourcePreference.setOnPreferenceChangeListener(this);
@ -43,36 +43,36 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference
@Override
protected void onResume() {
super.onResume();
useInternetToDownloadTiles.setChecked(OsmandSettings.useInternetToDownloadTiles);
showPoiOnMap.setChecked(OsmandSettings.showPoiOverMap);
useInternetToDownloadTiles.setChecked(OsmandSettings.isUsingInternetToDownloadTiles(this));
showPoiOnMap.setChecked(OsmandSettings.isShowingPoiOverMap(this));
List<TileSourceTemplate> list = TileSourceManager.getKnownSourceTemplates();
String[] entries = new String[list.size()];
for(int i=0; i<list.size(); i++){
entries[i] = list.get(i).getName();
}
tileSourcePreference.setEntries(entries);
tileSourcePreference.setEntryValues(entries);
tileSourcePreference.setValue(OsmandSettings.tileSource.getName());
tileSourcePreference.setSummary(tileSourcePreference.getSummary() + "\t\t[" + OsmandSettings.tileSource.getName()+"]");
tileSourcePreference.setValue(OsmandSettings.getMapTileSourceName(this));
tileSourcePreference.setSummary(tileSourcePreference.getSummary() + "\t\t[" + OsmandSettings.getMapTileSourceName(this)+"]");
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
SharedPreferences prefs = getSharedPreferences(OsmandSettings.SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
Editor edit = prefs.edit();
if(preference == showPoiOnMap){
OsmandSettings.showPoiOverMap = (Boolean) newValue;
edit.putBoolean(OsmandSettings.SHOW_POI_OVER_MAP, (Boolean) newValue);
edit.commit();
} else if(preference == useInternetToDownloadTiles){
OsmandSettings.useInternetToDownloadTiles = (Boolean) newValue;
edit.putBoolean(OsmandSettings.USE_INTERNET_TO_DOWNLOAD_TILES, (Boolean) newValue);
edit.commit();
} else if (preference == tileSourcePreference) {
String newTile = newValue.toString();
for (TileSourceTemplate t : TileSourceManager.getKnownSourceTemplates()) {
if (t.getName().equals(newTile)) {
OsmandSettings.tileSource = t;
break;
}
}
edit.putString(OsmandSettings.MAP_TILE_SOURCES, (String) newValue);
edit.commit();
}
return true;
}

View file

@ -43,11 +43,11 @@ public class OsmandMapTileView extends SurfaceView implements IMapDownloaderCall
/**
* zoom level
*/
private int zoom = DefaultLauncherConstants.MAP_startMapZoom;
private int zoom = 3;
private double longitude = DefaultLauncherConstants.MAP_startMapLongitude;
private double longitude = 0d;
private double latitude = DefaultLauncherConstants.MAP_startMapLatitude;
private double latitude = 0d;
// name of source map
private ITileSource map = null;
@ -231,7 +231,7 @@ public class OsmandMapTileView extends SurfaceView implements IMapDownloaderCall
}
public void prepareImage() {
if (OsmandSettings.useInternetToDownloadTiles) {
if (OsmandSettings.isUsingInternetToDownloadTiles(getContext())) {
downloader.refuseAllPreviousRequests();
}
int width = getWidth();
@ -251,7 +251,7 @@ public class OsmandMapTileView extends SurfaceView implements IMapDownloaderCall
for (int i = 0; i * tileSize + startingX < width; i++) {
for (int j = 0; j * tileSize + startingY < height; j++) {
ResourceManager mgr = ResourceManager.getResourceManager();
Bitmap bmp = mgr.getTileImageForMapAsync(map, xTileLeft + i, yTileUp + j, zoom, OsmandSettings.useInternetToDownloadTiles);
Bitmap bmp = mgr.getTileImageForMapAsync(map, xTileLeft + i, yTileUp + j, zoom, OsmandSettings.isUsingInternetToDownloadTiles(getContext()));
if (bmp == null) {
drawEmptyTile(canvas, i * tileSize + startingX, j * tileSize + startingY);
} else {