private static void commitPointsRemoval(
     OsmandApplication app, final boolean[] checkedIntermediates) {
   int cnt = 0;
   for (int i = checkedIntermediates.length - 1; i >= 0; i--) {
     if (!checkedIntermediates[i]) {
       cnt++;
     }
   }
   if (cnt > 0) {
     boolean changeDestinationFlag = !checkedIntermediates[checkedIntermediates.length - 1];
     if (cnt
         == checkedIntermediates
             .length) { // there is no alternative destination if all points are to be removed?
       app.getTargetPointsHelper().removeAllWayPoints(true);
     } else {
       for (int i = checkedIntermediates.length - 2;
           i >= 0;
           i--) { // skip the destination until a retained waypoint is found
         if (checkedIntermediates[i]
             && changeDestinationFlag) { // Find a valid replacement for the destination
           app.getTargetPointsHelper().makeWayPointDestination(cnt == 0, i);
           changeDestinationFlag = false;
         } else if (!checkedIntermediates[i]) {
           cnt--;
           app.getTargetPointsHelper().removeWayPoint(cnt == 0, i);
         }
       }
       // FIXME delete location when point is removed
       //				if(mapActivity instanceof MapActivity) {
       //					((MapActivity) mapActivity).getMapLayers().getContextMenuLayer().setLocation(null,
       // "");
       //				}
     }
   }
 }
  public EntityInfo loadNode(Node n) {
    long nodeId = n.getId(); // >> 1;
    try {
      String res =
          sendRequest(
              SITE_API + "api/0.6/node/" + nodeId,
              "GET",
              null,
              ctx.getString(R.string.loading_poi_obj) + nodeId,
              false); //$NON-NLS-1$ //$NON-NLS-2$
      if (res != null) {
        OsmBaseStorage st = new OsmBaseStorage();
        st.parseOSM(
            new ByteArrayInputStream(res.getBytes("UTF-8")), null, null, true); // $NON-NLS-1$
        EntityId id = new Entity.EntityId(EntityType.NODE, nodeId);
        //				Node entity = (Node) st.getRegisteredEntities().get(id);
        entityInfo = st.getRegisteredEntityInfo().get(id);
        return entityInfo;
      }

    } catch (IOException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    } catch (SAXException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    }
    return null;
  }
Esempio n. 3
0
 public void stopRecording() {
   settings.SAVE_GLOBAL_TRACK_TO_GPX.set(false);
   if (app.getNavigationService() != null) {
     app.getNavigationService().stopIfNeeded(app, NavigationService.USED_BY_GPX);
     app.getNotificationHelper().showNotification();
   }
 }
Esempio n. 4
0
  public void select(int mode) {
    try {
      double lat = convert(((TextView) view.findViewById(R.id.LatitudeEdit)).getText().toString());
      double lon = convert(((TextView) view.findViewById(R.id.LongitudeEdit)).getText().toString());
      if (mode == ADD_TO_FAVORITE) {
        Bundle b = new Bundle();
        Dialog dlg = MapActivityActions.createAddFavouriteDialog(getActivity(), b);
        dlg.show();
        MapActivityActions.prepareAddFavouriteDialog(
            getActivity(), dlg, b, lat, lon, getString(R.string.point_on_map, lat, lon));
      } else if (mode == NAVIGATE_TO) {
        MapActivityActions.directionsToDialogAndLaunchMap(
            getActivity(), lat, lon, getString(R.string.point_on_map, lat, lon));
      } else if (mode == ADD_WAYPOINT) {
        MapActivityActions.addWaypointDialogAndLaunchMap(
            getActivity(), lat, lon, getString(R.string.point_on_map, lat, lon));
      } else if (mode == SHOW_ON_MAP) {
        OsmandApplication app = (OsmandApplication) getActivity().getApplication();
        app.getSettings()
            .setMapLocationToShow(
                lat,
                lon,
                Math.max(12, app.getSettings().getLastKnownMapZoom()),
                getString(R.string.point_on_map, lat, lon));
        MapActivity.launchMapActivityMoveToTop(getActivity());
      }

    } catch (RuntimeException e) {
      ((TextView) view.findViewById(R.id.ValidateTextView)).setVisibility(View.VISIBLE);
      ((TextView) view.findViewById(R.id.ValidateTextView)).setText(R.string.invalid_locations);
      Log.w(PlatformUtil.TAG, "Convertion failed", e); // $NON-NLS-1$
    }
  }
 @Override
 protected void onResume() {
   super.onResume();
   Intent intent = getIntent();
   LatLon startPoint = null;
   if (intent != null) {
     double lat = intent.getDoubleExtra(SEARCH_LAT, 0);
     double lon = intent.getDoubleExtra(SEARCH_LON, 0);
     if (lat != 0 || lon != 0) {
       startPoint = new LatLon(lat, lon);
     }
   }
   if (startPoint == null && getParent() instanceof SearchActivity) {
     startPoint = ((SearchActivity) getParent()).getSearchPoint();
   }
   if (startPoint == null) {
     startPoint = settings.getLastKnownMapLocation();
   }
   OsmandApplication app = (OsmandApplication) getApplication();
   LatLon pointToNavigate = app.getTargetPointsHelper().getPointToNavigate();
   if (!Algorithms.objectEquals(pointToNavigate, this.destinationLocation)
       || !Algorithms.objectEquals(startPoint, this.lastKnownMapLocation)) {
     destinationLocation = pointToNavigate;
     selectedDestinationLocation = destinationLocation;
     lastKnownMapLocation = startPoint;
     searchTransport();
   }
 }
Esempio n. 6
0
 @Override
 public void disable(OsmandApplication app) {
   super.disable(app);
   if (app.getSettings().RENDERER.get().equals(RendererRegistry.TOURING_VIEW)) {
     app.getSettings().RENDERER.set(previousRenderer);
   }
 }
Esempio n. 7
0
 public Drawable getDrawable(Context uiCtx, OsmandApplication app) {
   if (type == POI) {
     Amenity amenity = ((AmenityLocationPoint) point).a;
     PoiType st = amenity.getType().getPoiTypeByKeyName(amenity.getSubType());
     if (st != null) {
       if (RenderingIcons.containsBigIcon(st.getIconKeyName())) {
         return uiCtx
             .getResources()
             .getDrawable(RenderingIcons.getBigIconResourceId(st.getIconKeyName()));
       } else if (RenderingIcons.containsBigIcon(st.getOsmTag() + "_" + st.getOsmValue())) {
         return uiCtx
             .getResources()
             .getDrawable(
                 RenderingIcons.getBigIconResourceId(st.getOsmTag() + "_" + st.getOsmValue()));
       }
     }
     return null;
   } else if (type == TARGETS) {
     int i =
         !((TargetPoint) point).intermediate
             ? R.drawable.list_destination
             : R.drawable.list_intermediate;
     return uiCtx.getResources().getDrawable(i);
   } else if (type == FAVORITES || type == WAYPOINTS) {
     return FavoriteImageDrawable.getOrCreate(uiCtx, point.getColor(), false);
   } else if (type == ALARMS) {
     // assign alarm list icons manually for now
     if (((AlarmInfo) point).getType().toString() == "SPEED_CAMERA") {
       return uiCtx.getResources().getDrawable(R.drawable.mx_highway_speed_camera);
     } else if (((AlarmInfo) point).getType().toString() == "BORDER_CONTROL") {
       return uiCtx.getResources().getDrawable(R.drawable.mx_barrier_border_control);
     } else if (((AlarmInfo) point).getType().toString() == "RAILWAY") {
       if (app.getSettings().DRIVING_REGION.get().americanSigns) {
         return uiCtx.getResources().getDrawable(R.drawable.list_warnings_railways_us);
       } else {
         return uiCtx.getResources().getDrawable(R.drawable.list_warnings_railways);
       }
     } else if (((AlarmInfo) point).getType().toString() == "TRAFFIC_CALMING") {
       if (app.getSettings().DRIVING_REGION.get().americanSigns) {
         return uiCtx.getResources().getDrawable(R.drawable.list_warnings_traffic_calming_us);
       } else {
         return uiCtx.getResources().getDrawable(R.drawable.list_warnings_traffic_calming);
       }
     } else if (((AlarmInfo) point).getType().toString() == "TOLL_BOOTH") {
       return uiCtx.getResources().getDrawable(R.drawable.mx_toll_booth);
     } else if (((AlarmInfo) point).getType().toString() == "STOP") {
       return uiCtx.getResources().getDrawable(R.drawable.list_stop);
     } else if (((AlarmInfo) point).getType().toString() == "PEDESTRIAN") {
       if (app.getSettings().DRIVING_REGION.get().americanSigns) {
         return uiCtx.getResources().getDrawable(R.drawable.list_warnings_pedestrian_us);
       } else {
         return uiCtx.getResources().getDrawable(R.drawable.list_warnings_pedestrian);
       }
     } else {
       return null;
     }
   } else {
     return null;
   }
 }
Esempio n. 8
0
    public void update(OsmandApplication ctx, boolean night) {
      if (nightMode == night && !f) {
        return;
      }
      f = false;
      nightMode = night;
      if (bgDark != 0 && bgLight != 0) {
        iv.setBackgroundDrawable(ctx.getResources().getDrawable(night ? bgDark : bgLight));
      }
      Drawable d = null;
      if (resDarkId != 0 && nightMode) {
        d = ctx.getIconsCache().getIcon(resDarkId);
      } else if (resLightId != 0 && !nightMode) {
        d = ctx.getIconsCache().getIcon(resLightId);
      } else if (resId != 0) {
        d = ctx.getIconsCache().getIcon(resId, nightMode ? resClrDark : resClrLight);
      }

      if (iv instanceof ImageView) {
        if (compass) {
          ((ImageView) iv).setImageDrawable(new CompassDrawable(d));
        } else {
          ((ImageView) iv).setImageDrawable(d);
        }
      } else if (iv instanceof TextView) {
        ((TextView) iv).setCompoundDrawablesWithIntrinsicBounds(d, null, null, null);
      }
    }
Esempio n. 9
0
  public void updateApplicationModeSettings() {
    // update vector renderer
    RendererRegistry registry = app.getRendererRegistry();
    RenderingRulesStorage newRenderer = registry.getRenderer(settings.RENDERER.get());
    if (newRenderer == null) {
      newRenderer = registry.defaultRender();
    }
    if (registry.getCurrentSelectedRenderer() != newRenderer) {
      registry.setCurrentSelectedRender(newRenderer);
      app.getResourceManager().getRenderer().clearCache();
    }
    mapViewTrackingUtilities.updateSettings();
    app.getRoutingHelper().setAppMode(settings.getApplicationMode());
    if (mapLayers.getMapInfoLayer() != null) {
      mapLayers.getMapInfoLayer().recreateControls();
    }
    mapLayers.updateLayers(mapView);
    app.getDaynightHelper()
        .startSensorIfNeeded(
            new StateChangedListener<Boolean>() {

              @Override
              public void stateChanged(Boolean change) {
                getMapView().refreshMap(true);
              }
            });
    getMapView().refreshMap(true);
  }
Esempio n. 10
0
 @Override
 public boolean init(final OsmandApplication app, final Activity activity) {
   if (activity != null) {
     // called from UI
     previousRenderer = app.getSettings().RENDERER.get();
     app.getSettings().RENDERER.set(RendererRegistry.TOURING_VIEW);
   }
   return true;
 }
Esempio n. 11
0
 public void checkPreviousRunsForExceptions(boolean firstTime) {
   long size = getPreferences(MODE_WORLD_READABLE).getLong(EXCEPTION_FILE_SIZE, 0);
   final OsmandApplication app = ((OsmandApplication) getApplication());
   final File file = app.getAppPath(OsmandApplication.EXCEPTION_PATH);
   if (file.exists() && file.length() > 0) {
     if (size != file.length() && !firstTime) {
       String msg =
           MessageFormat.format(
               getString(R.string.previous_run_crashed), OsmandApplication.EXCEPTION_PATH);
       Builder builder = new AccessibleAlertBuilder(MainMenuActivity.this);
       builder.setMessage(msg).setNeutralButton(getString(R.string.close), null);
       builder.setPositiveButton(
           R.string.send_report,
           new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
               Intent intent = new Intent(Intent.ACTION_SEND);
               intent.putExtra(
                   Intent.EXTRA_EMAIL, new String[] {"*****@*****.**"}); // $NON-NLS-1$
               intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
               intent.setType("vnd.android.cursor.dir/email"); // $NON-NLS-1$
               intent.putExtra(Intent.EXTRA_SUBJECT, "OsmAnd bug"); // $NON-NLS-1$
               StringBuilder text = new StringBuilder();
               text.append("\nDevice : ").append(Build.DEVICE); // $NON-NLS-1$
               text.append("\nBrand : ").append(Build.BRAND); // $NON-NLS-1$
               text.append("\nModel : ").append(Build.MODEL); // $NON-NLS-1$
               text.append("\nProduct : ").append(Build.PRODUCT); // $NON-NLS-1$
               text.append("\nBuild : ").append(Build.DISPLAY); // $NON-NLS-1$
               text.append("\nVersion : ").append(Build.VERSION.RELEASE); // $NON-NLS-1$
               text.append("\nApp Version : ").append(Version.getAppName(app)); // $NON-NLS-1$
               try {
                 PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
                 if (info != null) {
                   text.append("\nApk Version : ")
                       .append(info.versionName)
                       .append(" ")
                       .append(info.versionCode); // $NON-NLS-1$ //$NON-NLS-2$
                 }
               } catch (NameNotFoundException e) {
               }
               intent.putExtra(Intent.EXTRA_TEXT, text.toString());
               startActivity(Intent.createChooser(intent, getString(R.string.send_report)));
             }
           });
       builder.show();
     }
     getPreferences(MODE_WORLD_WRITEABLE)
         .edit()
         .putLong(EXCEPTION_FILE_SIZE, file.length())
         .commit();
   } else {
     if (size > 0) {
       getPreferences(MODE_WORLD_WRITEABLE).edit().putLong(EXCEPTION_FILE_SIZE, 0).commit();
     }
   }
 }
 public AlarmWidget(final OsmandApplication app, MapActivity ma) {
   layout = ma.findViewById(R.id.map_alarm_warning);
   icon = (ImageView) ma.findViewById(R.id.map_alarm_warning_icon);
   text = (TextView) ma.findViewById(R.id.map_alarm_warning_text);
   settings = app.getSettings();
   rh = ma.getRoutingHelper();
   trackingUtilities = ma.getMapViewTrackingUtilities();
   locationProvider = app.getLocationProvider();
   wh = app.getWaypointHelper();
 }
Esempio n. 13
0
 public void resetStoreDirectory() {
   dirWithTiles = context.getAppPath(IndexConstants.TILES_INDEX_DIR);
   dirWithTiles.mkdirs();
   // ".nomedia" indicates there are no pictures and no music to list in this dir for the Gallery
   // app
   try {
     context.getAppPath(".nomedia").createNewFile(); // $NON-NLS-1$
   } catch (Exception e) {
   }
 }
Esempio n. 14
0
 public void setFollowingMode(boolean follow) {
   isFollowingMode = follow;
   if (!follow) {
     if (app.getNavigationService() != null) {
       app.getNavigationService().stopIfNeeded(app, NavigationService.USED_BY_NAVIGATION);
     }
   } else {
     app.startNavigationService(NavigationService.USED_BY_NAVIGATION);
   }
 }
 public void showOnMap(boolean navigateTo) {
   if (searchPoint == null) {
     return;
   }
   String historyName = null;
   String objectName = "";
   int zoom = 12;
   if (!Algoritms.isEmpty(street2) && !Algoritms.isEmpty(street)) {
     String cityName = !Algoritms.isEmpty(postcode) ? postcode : city;
     objectName = street;
     historyName =
         MessageFormat.format(
             getString(R.string.search_history_int_streets), street, street2, cityName);
     zoom = 16;
   } else if (!Algoritms.isEmpty(building)) {
     String cityName = !Algoritms.isEmpty(postcode) ? postcode : city;
     objectName = street + " " + building;
     historyName =
         MessageFormat.format(
             getString(R.string.search_history_building), building, street, cityName);
     zoom = 16;
   } else if (!Algoritms.isEmpty(street)) {
     String cityName = postcode != null ? postcode : city;
     objectName = street;
     historyName =
         MessageFormat.format(getString(R.string.search_history_street), street, cityName);
     zoom = 15;
   } else if (!Algoritms.isEmpty(city)) {
     historyName = MessageFormat.format(getString(R.string.search_history_city), city);
     objectName = city;
     zoom = 13;
   }
   if (selectAddressMode) {
     Intent intent = getIntent();
     intent.putExtra(SELECT_ADDRESS_POINT_INTENT_KEY, objectName);
     intent.putExtra(SELECT_ADDRESS_POINT_LAT, searchPoint.getLatitude());
     intent.putExtra(SELECT_ADDRESS_POINT_LON, searchPoint.getLongitude());
     setResult(SELECT_ADDRESS_POINT_RESULT_OK, intent);
     finish();
   } else {
     if (navigateTo) {
       OsmandApplication app = (OsmandApplication) getApplication();
       app.getTargetPointsHelper()
           .navigatePointDialogAndLaunchMap(
               SearchAddressActivity.this,
               searchPoint.getLatitude(),
               searchPoint.getLongitude(),
               historyName);
     } else {
       osmandSettings.setMapLocationToShow(
           searchPoint.getLatitude(), searchPoint.getLongitude(), zoom, historyName);
       MapActivity.launchMapActivityMoveToTop(SearchAddressActivity.this);
     }
   }
 }
Esempio n. 16
0
 private List<String> checkAssets(IProgress progress) {
   String fv = Version.getFullVersion(context);
   if (!fv.equalsIgnoreCase(context.getSettings().PREVIOUS_INSTALLED_VERSION.get())) {
     File applicationDataDir = context.getAppPath(null);
     applicationDataDir.mkdirs();
     if (applicationDataDir.canWrite()) {
       try {
         progress.startTask(context.getString(R.string.installing_new_resources), -1);
         AssetManager assetManager = context.getAssets();
         boolean isFirstInstall =
             context.getSettings().PREVIOUS_INSTALLED_VERSION.get().equals("");
         unpackBundledAssets(assetManager, applicationDataDir, progress, isFirstInstall);
         context.getSettings().PREVIOUS_INSTALLED_VERSION.set(fv);
         copyRegionsBoundaries();
         copyPoiTypes();
         for (String internalStyle :
             context.getRendererRegistry().getInternalRenderers().keySet()) {
           File fl = context.getRendererRegistry().getFileForInternalStyle(internalStyle);
           if (fl.exists()) {
             context.getRendererRegistry().copyFileForInternalStyle(internalStyle);
           }
         }
       } catch (SQLiteException e) {
         log.error(e.getMessage(), e);
       } catch (IOException e) {
         log.error(e.getMessage(), e);
       } catch (XmlPullParserException e) {
         log.error(e.getMessage(), e);
       }
     }
   }
   return Collections.emptyList();
 }
 @Override
 protected void onPreExecute() {
   if (context instanceof AbstractDownloadActivity) {
     AbstractDownloadActivity activity = (AbstractDownloadActivity) context;
     activity.setSupportProgressBarIndeterminateVisibility(true);
     OsmandSettings settings = activity.getMyApplication().getSettings();
   }
   final OsmandApplication myApplication = getMyApplication();
   OsmandSettings.CommonPreference<Long> lastCheckPreference =
       LiveUpdatesHelper.preferenceLastCheck(localIndexInfo, myApplication.getSettings());
   lastCheckPreference.set(System.currentTimeMillis());
 }
Esempio n. 18
0
  @SuppressLint("SimpleDateFormat")
  private static void processDiscountResponse(String response, MapActivity mapActivity) {
    try {
      OsmandApplication app = mapActivity.getMyApplication();

      JSONObject obj = new JSONObject(response);
      String message = obj.getString("message");
      String description = obj.getString("description");
      String icon = obj.getString("icon");
      String url = parseUrl(app, obj.getString("url"));
      SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
      Date start = df.parse(obj.getString("start"));
      Date end = df.parse(obj.getString("end"));
      int showStartFrequency = obj.getInt("show_start_frequency");
      double showDayFrequency = obj.getDouble("show_day_frequency");
      int maxTotalShow = obj.getInt("max_total_show");
      JSONObject application = obj.getJSONObject("application");

      String appName = app.getPackageName();
      Date date = new Date();
      if (application.has(appName)
          && application.getBoolean(appName)
          && date.after(start)
          && date.before(end)) {

        OsmandSettings settings = app.getSettings();
        int discountId = getDiscountId(message, description, start, end);
        boolean discountChanged = settings.DISCOUNT_ID.get() != discountId;
        if (discountChanged) {
          settings.DISCOUNT_TOTAL_SHOW.set(0);
        }
        if (discountChanged
            || app.getAppInitializer().getNumberOfStarts()
                    - settings.DISCOUNT_SHOW_NUMBER_OF_STARTS.get()
                >= showStartFrequency
            || System.currentTimeMillis() - settings.DISCOUNT_SHOW_DATETIME_MS.get()
                > 1000L * 60 * 60 * 24 * showDayFrequency) {
          if (settings.DISCOUNT_TOTAL_SHOW.get() < maxTotalShow) {
            settings.DISCOUNT_ID.set(discountId);
            settings.DISCOUNT_TOTAL_SHOW.set(settings.DISCOUNT_TOTAL_SHOW.get() + 1);
            settings.DISCOUNT_SHOW_NUMBER_OF_STARTS.set(
                app.getAppInitializer().getNumberOfStarts());
            settings.DISCOUNT_SHOW_DATETIME_MS.set(System.currentTimeMillis());
            showDiscountBanner(mapActivity, message, description, icon, url);
          }
        }
      }

    } catch (Exception e) {
      logError("JSON parsing error: ", e);
    }
  }
Esempio n. 19
0
 public TopTextView(OsmandApplication app, MapActivity map) {
   topBar = map.findViewById(R.id.map_top_bar);
   addressText = (TextView) map.findViewById(R.id.map_address_text);
   addressTextShadow = (TextView) map.findViewById(R.id.map_address_text_shadow);
   waypointInfoBar = map.findViewById(R.id.waypoint_info_bar);
   this.routingHelper = app.getRoutingHelper();
   locationProvider = app.getLocationProvider();
   this.map = map;
   settings = app.getSettings();
   waypointHelper = app.getWaypointHelper();
   updateVisibility(false);
   turnDrawable = new NextTurnInfoWidget.TurnDrawable(map);
 }
Esempio n. 20
0
  public static void checkAndDisplay(final MapActivity mapActivity) {
    if (mBannerVisible) {
      showDiscountBanner(mapActivity, mTitle, mDescription, mIcon, mUrl);
    }
    OsmandApplication app = mapActivity.getMyApplication();
    if (System.currentTimeMillis() - mLastCheckTime < 1000 * 60 * 60 * 24
        || !app.getSettings().isInternetConnectionAvailable()
        || app.getSettings().NO_DISCOUNT_INFO.get()) {
      return;
    }
    mLastCheckTime = System.currentTimeMillis();
    final Map<String, String> pms = new LinkedHashMap<>();
    pms.put("version", Version.getFullVersion(app));
    pms.put("nd", app.getAppInitializer().getFirstInstalledDays() + "");
    pms.put("ns", app.getAppInitializer().getNumberOfStarts() + "");
    try {
      pms.put("aid", Secure.getString(app.getContentResolver(), Secure.ANDROID_ID));
    } catch (Exception e) {
      e.printStackTrace();
    }
    new AsyncTask<Void, Void, String>() {

      @Override
      protected String doInBackground(Void... params) {
        try {
          String res =
              AndroidNetworkUtils.sendRequest(
                  mapActivity.getMyApplication(),
                  URL,
                  pms,
                  "Requesting discount info...",
                  false,
                  false);
          return res;
        } catch (Exception e) {
          logError("Requesting discount info error: ", e);
          return null;
        }
      }

      @Override
      protected void onPostExecute(String response) {
        if (response != null) {
          processDiscountResponse(response, mapActivity);
        }
      }
    }.execute();
  }
Esempio n. 21
0
  private void createLayersItems(ContextMenuAdapter adapter, MapActivity activity) {
    OsmandApplication app = activity.getMyApplication();
    OsmandSettings settings = app.getSettings();
    LayerMenuListener l = new LayerMenuListener(activity, adapter);
    adapter
        .item(R.string.shared_string_show)
        .setCategory(true)
        .layout(R.layout.drawer_list_sub_header)
        .reg();
    // String appMode = " [" + settings.getApplicationMode().toHumanString(view.getApplication())
    // +"] ";
    adapter
        .item(R.string.layer_poi)
        .selected(settings.SELECTED_POI_FILTER_FOR_MAP.get() != null ? 1 : 0)
        .iconColor(R.drawable.ic_action_info_dark)
        .listen(l)
        .reg();
    adapter
        .item(R.string.layer_amenity_label)
        .selected(settings.SHOW_POI_LABEL.get() ? 1 : 0)
        .iconColor(R.drawable.ic_action_text_dark)
        .listen(l)
        .reg();
    adapter
        .item(R.string.shared_string_favorites)
        .selected(settings.SHOW_FAVORITES.get() ? 1 : 0)
        .iconColor(R.drawable.ic_action_fav_dark)
        .listen(l)
        .reg();
    adapter
        .item(R.string.layer_gpx_layer)
        .selected(app.getSelectedGpxHelper().isShowingAnyGpxFiles() ? 1 : 0)
        .iconColor(R.drawable.ic_action_polygom_dark)
        .listen(l)
        .reg();
    adapter.item(R.string.layer_map).iconColor(R.drawable.ic_world_globe_dark).listen(l).reg();
    if (TransportRouteHelper.getInstance().routeIsCalculated()) {
      adapter
          .item(R.string.layer_transport_route)
          .selected(1)
          .iconColor(R.drawable.ic_action_bus_dark)
          .listen(l)
          .reg();
    }

    OsmandPlugin.registerLayerContextMenu(activity.getMapView(), adapter, activity);
    app.getAppCustomization().prepareLayerContextMenu(activity, adapter);
  }
Esempio n. 22
0
  public static void initPlugins(OsmandApplication app) {
    OsmandSettings settings = app.getSettings();
    Set<String> enabledPlugins = settings.getEnabledPlugins();
    allPlugins.add(new OsmandRasterMapsPlugin(app));
    allPlugins.add(new OsmandMonitoringPlugin(app));
    allPlugins.add(new OsMoPlugin(app));
    checkMarketPlugin(
        app, new SRTMPlugin(app), true, SRTM_PLUGIN_COMPONENT_PAID, SRTM_PLUGIN_COMPONENT);

    // ? questionable - definitely not market plugin
    //		checkMarketPlugin(app, new TouringViewPlugin(app), false, TouringViewPlugin.COMPONENT,
    // null);
    checkMarketPlugin(app, new NauticalMapsPlugin(app), false, NauticalMapsPlugin.COMPONENT, null);
    checkMarketPlugin(app, new SkiMapsPlugin(app), false, SkiMapsPlugin.COMPONENT, null);

    //		checkMarketPlugin(app, new RoutePointsPlugin(app), false /*FIXME*/,
    // RoutePointsPlugin.ROUTE_POINTS_PLUGIN_COMPONENT, null);
    allPlugins.add(new AudioVideoNotesPlugin(app));
    checkMarketPlugin(
        app,
        new ParkingPositionPlugin(app),
        false,
        ParkingPositionPlugin.PARKING_PLUGIN_COMPONENT,
        null);
    allPlugins.add(new DistanceCalculatorPlugin(app));
    allPlugins.add(new AccessibilityPlugin(app));
    allPlugins.add(new OsmEditingPlugin(app));
    allPlugins.add(new OsmandDevelopmentPlugin(app));
    if (android.os.Build.VERSION.SDK_INT >= 19) {
      allPlugins.add(new net.osmand.plus.smartnaviwatch.SmartNaviWatchPlugin(app));
    }

    activatePlugins(app, enabledPlugins);
  }
Esempio n. 23
0
  // test
  @Override
  public boolean init(final OsmandApplication app) {
    mConnection =
        new ServiceConnection() {
          @Override
          public void onServiceConnected(ComponentName name, IBinder service) {
            mIRemoteService = IRemoteOsMoDroidService.Stub.asInterface(service);
            try {
              System.out.println(mIRemoteService.getVersion());
              if (mIRemoteService.getVersion() < OSMODROID_SUPPORTED_VERSION_MIN) {
                app.showToastMessage(R.string.osmodroid_plugin_old_ver_not_supported);
                shutdown(app);
              } else {
                mIRemoteService.registerListener(inter);
                connected = true;
              }

            } catch (RemoteException e) {
              log.error(e.getMessage(), e);
            }
          }

          @Override
          public void onServiceDisconnected(ComponentName name) {
            connected = false;
            mIRemoteService = null;
          }
        };
    Intent serviceIntent = (new Intent("OsMoDroid.remote"));
    app.bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
    return true;
  }
Esempio n. 24
0
  public void saveCurrentTrack() {
    app.getTaskManager()
        .runInBackground(
            new OsmAndTaskRunnable<Void, Void, Void>() {

              @Override
              protected void onPreExecute() {
                isSaving = true;
                if (monitoringControl != null) {
                  monitoringControl.updateInfo(null);
                }
              }

              @Override
              protected Void doInBackground(Void... params) {
                try {
                  SavingTrackHelper helper = app.getSavingTrackHelper();
                  helper.saveDataToGpx(app.getAppCustomization().getTracksDir());
                  helper.close();
                } finally {
                  app.getNotificationHelper().showNotification();
                }
                return null;
              }

              @Override
              protected void onPostExecute(Void aVoid) {
                isSaving = false;
                if (monitoringControl != null) {
                  monitoringControl.updateInfo(null);
                }
              }
            },
            (Void) null);
  }
Esempio n. 25
0
 public static boolean enablePlugin(
     Activity activity, OsmandApplication app, OsmandPlugin plugin, boolean enable) {
   if (enable) {
     if (!plugin.init(app, activity)) {
       plugin.setActive(false);
       return false;
     } else {
       plugin.setActive(true);
     }
   } else {
     plugin.disable(app);
     plugin.setActive(false);
   }
   app.getSettings().enablePlugin(plugin.getId(), enable);
   if (activity instanceof MapActivity) {
     final MapActivity mapActivity = (MapActivity) activity;
     plugin.updateLayers(mapActivity.getMapView(), mapActivity);
     mapActivity.getDashboard().refreshDashboardFragments();
     if (!enable && plugin.getCardFragment() != null) {
       Fragment fragment =
           mapActivity.getSupportFragmentManager().findFragmentByTag(plugin.getCardFragment().tag);
       LOG.debug("fragment=" + fragment);
       mapActivity.getSupportFragmentManager().beginTransaction().remove(fragment).commit();
     }
   }
   return true;
 }
Esempio n. 26
0
 public OsmandMonitoringPlugin(OsmandApplication app) {
   this.app = app;
   liveMonitoringHelper = new LiveMonitoringHelper(app);
   final List<ApplicationMode> am = ApplicationMode.allPossibleValues();
   ApplicationMode.regWidget("monitoring", am.toArray(new ApplicationMode[am.size()]));
   settings = app.getSettings();
 }
Esempio n. 27
0
 private void onApplicationModePress(View v) {
   final QuickAction mQuickAction = new QuickAction(v);
   mQuickAction.setOnAnchorOnTop(true);
   List<ApplicationMode> vls =
       ApplicationMode.values(mapActivity.getMyApplication().getSettings());
   final ApplicationMode[] modes = vls.toArray(new ApplicationMode[vls.size()]);
   Drawable[] icons = new Drawable[vls.size()];
   int[] values = new int[vls.size()];
   for (int k = 0; k < modes.length; k++) {
     icons[k] = app.getIconsCache().getIcon(modes[k].getSmallIconDark(), R.color.icon_color);
     values[k] = modes[k].getStringResource();
   }
   for (int i = 0; i < modes.length; i++) {
     final ActionItem action = new ActionItem();
     action.setTitle(mapActivity.getResources().getString(values[i]));
     action.setIcon(icons[i]);
     final int j = i;
     action.setOnClickListener(
         new OnClickListener() {
           @Override
           public void onClick(View v) {
             mapActivity.getMyApplication().getSettings().APPLICATION_MODE.set(modes[j]);
             mQuickAction.dismiss();
           }
         });
     mQuickAction.addActionItem(action);
   }
   mQuickAction.setAnimStyle(QuickAction.ANIM_AUTO);
   mQuickAction.show();
 }
Esempio n. 28
0
 public void updateLocation(Location currentLocation) {
   if (isFollowingMode()
       || (settings.getPointToStart() == null && isRoutePlanningMode)
       || app.getLocationProvider().getLocationSimulation().isRouteAnimating()) {
     setCurrentLocation(currentLocation, false);
   }
 }
Esempio n. 29
0
  private void createProgressBarForRouting() {
    FrameLayout parent = (FrameLayout) mapView.getParent();
    FrameLayout.LayoutParams params =
        new FrameLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT,
            Gravity.CENTER_HORIZONTAL | Gravity.TOP);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    params.topMargin = (int) (60 * dm.density);
    final ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
    pb.setIndeterminate(false);
    pb.setMax(100);
    pb.setLayoutParams(params);
    pb.setVisibility(View.GONE);

    parent.addView(pb);
    app.getRoutingHelper()
        .setProgressBar(
            new RouteCalculationProgressCallback() {

              @Override
              public void updateProgress(int progress) {
                pb.setVisibility(View.VISIBLE);
                pb.setProgress(progress);
              }

              @Override
              public void finish() {
                pb.setVisibility(View.GONE);
              }
            });
  }
Esempio n. 30
0
 public boolean isTypeVisible(int waypointType) {
   boolean vis = app.getAppCustomization().isWaypointGroupVisible(waypointType, route);
   if (!vis) {
     return false;
   }
   return vis;
 }