Search in sources :

Example 56 with OsmandApplication

use of net.osmand.plus.OsmandApplication in project Osmand by osmandapp.

the class DiscountHelper method checkAndDisplay.

public static void checkAndDisplay(final MapActivity mapActivity) {
    OsmandApplication app = mapActivity.getMyApplication();
    OsmandSettings settings = app.getSettings();
    if (settings.DO_NOT_SHOW_STARTUP_MESSAGES.get() || !settings.INAPPS_READ.get()) {
        return;
    }
    if (mBannerVisible) {
        showDiscountBanner(mapActivity, mTitle, mDescription, mIcon, mUrl);
    }
    if (System.currentTimeMillis() - mLastCheckTime < 1000 * 60 * 60 * 24 || !settings.isInternetConnectionAvailable() || settings.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);
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
Also used : OsmandApplication(net.osmand.plus.OsmandApplication) OsmandSettings(net.osmand.plus.OsmandSettings) LinkedHashMap(java.util.LinkedHashMap)

Example 57 with OsmandApplication

use of net.osmand.plus.OsmandApplication in project Osmand by osmandapp.

the class ExternalApiHelper method startNavigation.

private void startNavigation(GPXFile gpx, LatLon from, PointDescription fromDesc, LatLon to, PointDescription toDesc, ApplicationMode mode) {
    OsmandApplication app = mapActivity.getMyApplication();
    RoutingHelper routingHelper = app.getRoutingHelper();
    if (gpx == null) {
        app.getSettings().APPLICATION_MODE.set(mode);
        final TargetPointsHelper targets = mapActivity.getMyApplication().getTargetPointsHelper();
        targets.removeAllWayPoints(false, true);
        targets.navigateToPoint(to, true, -1, toDesc);
    }
    mapActivity.getMapActions().enterRoutePlanningModeGivenGpx(gpx, from, fromDesc, true, false);
    if (!app.getTargetPointsHelper().checkPointToNavigateShort()) {
        mapActivity.getMapLayers().getMapControlsLayer().getMapRouteInfoMenu().show();
    } else {
        if (app.getSettings().APPLICATION_MODE.get() != routingHelper.getAppMode()) {
            app.getSettings().APPLICATION_MODE.set(routingHelper.getAppMode());
        }
        mapActivity.getMapViewTrackingUtilities().backToLocationImpl();
        app.getSettings().FOLLOW_THE_ROUTE.set(true);
        routingHelper.setFollowingMode(true);
        routingHelper.setRoutePlanningMode(false);
        mapActivity.getMapViewTrackingUtilities().switchToRoutePlanningMode();
        app.getRoutingHelper().notifyIfRouteIsCalculated();
        routingHelper.setCurrentLocation(app.getLocationProvider().getLastKnownLocation(), false);
    }
}
Also used : OsmandApplication(net.osmand.plus.OsmandApplication) RoutingHelper(net.osmand.plus.routing.RoutingHelper) TargetPointsHelper(net.osmand.plus.TargetPointsHelper)

Example 58 with OsmandApplication

use of net.osmand.plus.OsmandApplication in project Osmand by osmandapp.

the class ExternalApiHelper method processApiRequest.

public Intent processApiRequest(Intent intent) {
    Intent result = new Intent();
    OsmandApplication app = (OsmandApplication) mapActivity.getApplication();
    try {
        Uri uri = intent.getData();
        String cmd = uri.getHost().toLowerCase();
        if (API_CMD_SHOW_GPX.equals(cmd) || API_CMD_NAVIGATE_GPX.equals(cmd)) {
            boolean navigate = API_CMD_NAVIGATE_GPX.equals(cmd);
            String path = uri.getQueryParameter(PARAM_PATH);
            boolean force = uri.getBooleanQueryParameter(PARAM_FORCE, false);
            GPXFile gpx = null;
            if (path != null) {
                File f = new File(path);
                if (f.exists()) {
                    gpx = GPXUtilities.loadGPXFile(mapActivity, f);
                }
            } else if (intent.getStringExtra(PARAM_DATA) != null) {
                String gpxStr = intent.getStringExtra(PARAM_DATA);
                if (!Algorithms.isEmpty(gpxStr)) {
                    gpx = GPXUtilities.loadGPXFile(mapActivity, new ByteArrayInputStream(gpxStr.getBytes()));
                }
            } else if (uri.getBooleanQueryParameter(PARAM_URI, false)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    LOG.debug("uriString=" + intent.getClipData().getItemAt(0).getUri());
                    Uri gpxUri = intent.getClipData().getItemAt(0).getUri();
                    ParcelFileDescriptor gpxParcelDescriptor = mapActivity.getContentResolver().openFileDescriptor(gpxUri, "r");
                    if (gpxParcelDescriptor != null) {
                        FileDescriptor fileDescriptor = gpxParcelDescriptor.getFileDescriptor();
                        gpx = GPXUtilities.loadGPXFile(mapActivity, new FileInputStream(fileDescriptor));
                    } else {
                        finish = true;
                        resultCode = RESULT_CODE_ERROR_GPX_NOT_FOUND;
                    }
                } else {
                    finish = true;
                    resultCode = RESULT_CODE_ERROR_GPX_NOT_FOUND;
                }
            } else {
                finish = true;
                resultCode = RESULT_CODE_ERROR_GPX_NOT_FOUND;
            }
            if (gpx != null) {
                if (navigate) {
                    final RoutingHelper routingHelper = app.getRoutingHelper();
                    if (routingHelper.isFollowingMode() && !force) {
                        final GPXFile gpxFile = gpx;
                        AlertDialog dlg = mapActivity.getMapActions().stopNavigationActionConfirm();
                        dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {

                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                if (!routingHelper.isFollowingMode()) {
                                    startNavigation(gpxFile, null, null, null, null, null);
                                }
                            }
                        });
                    } else {
                        startNavigation(gpx, null, null, null, null, null);
                    }
                } else {
                    app.getSelectedGpxHelper().setGpxFileToDisplay(gpx);
                }
                resultCode = Activity.RESULT_OK;
            } else {
                finish = true;
                resultCode = RESULT_CODE_ERROR_GPX_NOT_FOUND;
            }
        } else if (API_CMD_NAVIGATE.equals(cmd)) {
            String profileStr = uri.getQueryParameter(PARAM_PROFILE);
            final ApplicationMode profile = ApplicationMode.valueOfStringKey(profileStr, DEFAULT_PROFILE);
            boolean validProfile = false;
            for (ApplicationMode mode : VALID_PROFILES) {
                if (mode == profile) {
                    validProfile = true;
                    break;
                }
            }
            if (!validProfile) {
                resultCode = RESULT_CODE_ERROR_INVALID_PROFILE;
            } else {
                String startName = uri.getQueryParameter(PARAM_START_NAME);
                if (Algorithms.isEmpty(startName)) {
                    startName = "";
                }
                String destName = uri.getQueryParameter(PARAM_DEST_NAME);
                if (Algorithms.isEmpty(destName)) {
                    destName = "";
                }
                final LatLon start;
                final PointDescription startDesc;
                String startLatStr = uri.getQueryParameter(PARAM_START_LAT);
                String startLonStr = uri.getQueryParameter(PARAM_START_LON);
                if (!Algorithms.isEmpty(startLatStr) && !Algorithms.isEmpty(startLonStr)) {
                    double lat = Double.parseDouble(uri.getQueryParameter(PARAM_START_LAT));
                    double lon = Double.parseDouble(uri.getQueryParameter(PARAM_START_LON));
                    start = new LatLon(lat, lon);
                    startDesc = new PointDescription(PointDescription.POINT_TYPE_LOCATION, startName);
                } else {
                    start = null;
                    startDesc = null;
                }
                double destLat = Double.parseDouble(uri.getQueryParameter(PARAM_DEST_LAT));
                double destLon = Double.parseDouble(uri.getQueryParameter(PARAM_DEST_LON));
                final LatLon dest = new LatLon(destLat, destLon);
                final PointDescription destDesc = new PointDescription(PointDescription.POINT_TYPE_LOCATION, destName);
                boolean force = uri.getBooleanQueryParameter(PARAM_FORCE, false);
                final RoutingHelper routingHelper = app.getRoutingHelper();
                if (routingHelper.isFollowingMode() && !force) {
                    AlertDialog dlg = mapActivity.getMapActions().stopNavigationActionConfirm();
                    dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (!routingHelper.isFollowingMode()) {
                                startNavigation(null, start, startDesc, dest, destDesc, profile);
                            }
                        }
                    });
                } else {
                    startNavigation(null, start, startDesc, dest, destDesc, profile);
                }
            }
        } else if (API_CMD_RECORD_AUDIO.equals(cmd) || API_CMD_RECORD_VIDEO.equals(cmd) || API_CMD_RECORD_PHOTO.equals(cmd) || API_CMD_STOP_AV_REC.equals(cmd)) {
            AudioVideoNotesPlugin plugin = OsmandPlugin.getEnabledPlugin(AudioVideoNotesPlugin.class);
            if (plugin == null) {
                resultCode = RESULT_CODE_ERROR_PLUGIN_INACTIVE;
                finish = true;
            } else {
                if (API_CMD_STOP_AV_REC.equals(cmd)) {
                    plugin.stopRecording(mapActivity, false);
                } else {
                    double lat = Double.parseDouble(uri.getQueryParameter(PARAM_LAT));
                    double lon = Double.parseDouble(uri.getQueryParameter(PARAM_LON));
                    if (API_CMD_RECORD_AUDIO.equals(cmd)) {
                        plugin.recordAudio(lat, lon, mapActivity);
                    } else if (API_CMD_RECORD_VIDEO.equals(cmd)) {
                        plugin.recordVideo(lat, lon, mapActivity, false);
                    } else if (API_CMD_RECORD_PHOTO.equals(cmd)) {
                        plugin.takePhoto(lat, lon, mapActivity, true, false);
                    }
                }
                resultCode = Activity.RESULT_OK;
            }
        } else if (API_CMD_GET_INFO.equals(cmd)) {
            Location location = mapActivity.getMyApplication().getLocationProvider().getLastKnownLocation();
            if (location != null) {
                result.putExtra(PARAM_LAT, location.getLatitude());
                result.putExtra(PARAM_LON, location.getLongitude());
            }
            final RoutingHelper routingHelper = app.getRoutingHelper();
            if (routingHelper.isRouteCalculated()) {
                int time = routingHelper.getLeftTime();
                result.putExtra(PARAM_TIME_LEFT, time);
                long eta = time + System.currentTimeMillis() / 1000;
                result.putExtra(PARAM_ETA, eta);
                result.putExtra(PARAM_DISTANCE_LEFT, routingHelper.getLeftDistance());
                NextDirectionInfo ni = routingHelper.getNextRouteDirectionInfo(new NextDirectionInfo(), true);
                if (ni.distanceTo > 0) {
                    updateTurnInfo("next_", result, ni);
                    ni = routingHelper.getNextRouteDirectionInfoAfter(ni, new NextDirectionInfo(), true);
                    if (ni.distanceTo > 0) {
                        updateTurnInfo("after_next", result, ni);
                    }
                }
                routingHelper.getNextRouteDirectionInfo(new NextDirectionInfo(), false);
                if (ni.distanceTo > 0) {
                    updateTurnInfo("no_speak_next_", result, ni);
                }
            }
            result.putExtra(PARAM_VERSION, VERSION_CODE);
            finish = true;
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_ADD_FAVORITE.equals(cmd)) {
            String name = uri.getQueryParameter(PARAM_NAME);
            String desc = uri.getQueryParameter(PARAM_DESC);
            String category = uri.getQueryParameter(PARAM_CATEGORY);
            double lat = Double.parseDouble(uri.getQueryParameter(PARAM_LAT));
            double lon = Double.parseDouble(uri.getQueryParameter(PARAM_LON));
            String colorTag = uri.getQueryParameter(PARAM_COLOR);
            boolean visible = uri.getBooleanQueryParameter(PARAM_VISIBLE, true);
            if (name == null) {
                name = "";
            }
            if (desc == null) {
                desc = "";
            }
            if (category == null) {
                category = "";
            }
            int color = 0;
            if (!Algorithms.isEmpty(colorTag)) {
                color = ColorDialogs.getColorByTag(colorTag);
                if (color == 0) {
                    LOG.error("Wrong color tag: " + colorTag);
                }
            }
            FavouritePoint fav = new FavouritePoint(lat, lon, name, category);
            fav.setDescription(desc);
            fav.setColor(color);
            fav.setVisible(visible);
            FavouritesDbHelper helper = app.getFavorites();
            helper.addFavourite(fav);
            showOnMap(lat, lon, fav, mapActivity.getMapLayers().getFavouritesLayer().getObjectName(fav));
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_ADD_MAP_MARKER.equals(cmd)) {
            double lat = Double.parseDouble(uri.getQueryParameter(PARAM_LAT));
            double lon = Double.parseDouble(uri.getQueryParameter(PARAM_LON));
            String name = uri.getQueryParameter(PARAM_NAME);
            PointDescription pd = new PointDescription(PointDescription.POINT_TYPE_MAP_MARKER, name != null ? name : "");
            MapMarkersHelper markersHelper = app.getMapMarkersHelper();
            markersHelper.addMapMarker(new LatLon(lat, lon), pd);
            MapMarker marker = markersHelper.getFirstMapMarker();
            if (marker != null) {
                showOnMap(lat, lon, marker, mapActivity.getMapLayers().getMapMarkersLayer().getObjectName(marker));
            }
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_START_GPX_REC.equals(cmd)) {
            OsmandMonitoringPlugin plugin = OsmandPlugin.getEnabledPlugin(OsmandMonitoringPlugin.class);
            if (plugin == null) {
                resultCode = RESULT_CODE_ERROR_PLUGIN_INACTIVE;
                finish = true;
            } else {
                plugin.startGPXMonitoring(null);
            }
            if (uri.getBooleanQueryParameter(PARAM_CLOSE_AFTER_COMMAND, true)) {
                finish = true;
            }
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_STOP_GPX_REC.equals(cmd)) {
            OsmandMonitoringPlugin plugin = OsmandPlugin.getEnabledPlugin(OsmandMonitoringPlugin.class);
            if (plugin == null) {
                resultCode = RESULT_CODE_ERROR_PLUGIN_INACTIVE;
                finish = true;
            } else {
                plugin.stopRecording();
            }
            if (uri.getBooleanQueryParameter(PARAM_CLOSE_AFTER_COMMAND, true)) {
                finish = true;
            }
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_SUBSCRIBE_VOICE_NOTIFICATIONS.equals(cmd)) {
            // not implemented yet
            resultCode = RESULT_CODE_ERROR_NOT_IMPLEMENTED;
        }
    } catch (Exception e) {
        LOG.error("Error processApiRequest:", e);
        resultCode = RESULT_CODE_ERROR_UNKNOWN;
    }
    return result;
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) OsmandApplication(net.osmand.plus.OsmandApplication) AudioVideoNotesPlugin(net.osmand.plus.audionotes.AudioVideoNotesPlugin) FavouritePoint(net.osmand.data.FavouritePoint) MapMarker(net.osmand.plus.MapMarkersHelper.MapMarker) DialogInterface(android.content.DialogInterface) ApplicationMode(net.osmand.plus.ApplicationMode) Uri(android.net.Uri) OsmandMonitoringPlugin(net.osmand.plus.monitoring.OsmandMonitoringPlugin) NextDirectionInfo(net.osmand.plus.routing.RouteCalculationResult.NextDirectionInfo) Intent(android.content.Intent) RoutingHelper(net.osmand.plus.routing.RoutingHelper) FavouritesDbHelper(net.osmand.plus.FavouritesDbHelper) ParcelFileDescriptor(android.os.ParcelFileDescriptor) FileDescriptor(java.io.FileDescriptor) FileInputStream(java.io.FileInputStream) FavouritePoint(net.osmand.data.FavouritePoint) LatLon(net.osmand.data.LatLon) MapMarkersHelper(net.osmand.plus.MapMarkersHelper) ByteArrayInputStream(java.io.ByteArrayInputStream) PointDescription(net.osmand.data.PointDescription) ParcelFileDescriptor(android.os.ParcelFileDescriptor) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) File(java.io.File) Location(net.osmand.Location)

Example 59 with OsmandApplication

use of net.osmand.plus.OsmandApplication in project Osmand by osmandapp.

the class GpxUiHelper method createDialog.

private static AlertDialog createDialog(final Activity activity, final boolean showCurrentGpx, final boolean multipleChoice, final boolean showAppearanceSetting, final CallbackWithObject<GPXFile[]> callbackWithObject, final List<GPXInfo> list, final ContextMenuAdapter adapter) {
    final OsmandApplication app = (OsmandApplication) activity.getApplication();
    final DateFormat dateFormat = android.text.format.DateFormat.getMediumDateFormat(activity);
    final File dir = app.getAppPath(IndexConstants.GPX_INDEX_DIR);
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final int layout = R.layout.gpx_track_item;
    final Map<String, String> gpxAppearanceParams = new HashMap<>();
    final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(activity, layout, R.id.title, adapter.getItemNames()) {

        List<GpxDataItem> dataItems = null;

        @Override
        public int getItemViewType(int position) {
            return showCurrentGpx && position == 0 ? 1 : 0;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        private GpxDataItem getDataItem(GPXInfo info) {
            if (dataItems != null) {
                for (GpxDataItem item : dataItems) {
                    if (item.getFile().getAbsolutePath().endsWith(info.fileName)) {
                        return item;
                    }
                }
            }
            return null;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // User super class to create the View
            View v = convertView;
            boolean checkLayout = getItemViewType(position) == 0;
            if (v == null) {
                v = activity.getLayoutInflater().inflate(layout, null);
            }
            if (dataItems == null) {
                dataItems = app.getGpxDatabase().getItems();
            }
            final ContextMenuItem item = adapter.getItem(position);
            GPXInfo info = list.get(position);
            updateGpxInfoView(v, item, info, getDataItem(info), showCurrentGpx && position == 0, app);
            if (item.getSelected() == null) {
                v.findViewById(R.id.check_item).setVisibility(View.GONE);
                v.findViewById(R.id.check_local_index).setVisibility(View.GONE);
            } else {
                if (checkLayout) {
                    final CheckBox ch = ((CheckBox) v.findViewById(R.id.check_local_index));
                    ch.setVisibility(View.VISIBLE);
                    v.findViewById(R.id.toggle_item).setVisibility(View.GONE);
                    ch.setOnCheckedChangeListener(null);
                    ch.setChecked(item.getSelected());
                    ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            item.setSelected(isChecked);
                        }
                    });
                } else {
                    final SwitchCompat ch = ((SwitchCompat) v.findViewById(R.id.toggle_item));
                    ch.setVisibility(View.VISIBLE);
                    v.findViewById(R.id.toggle_checkbox_item).setVisibility(View.GONE);
                    ch.setOnCheckedChangeListener(null);
                    ch.setChecked(item.getSelected());
                    ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            item.setSelected(isChecked);
                        }
                    });
                }
                v.findViewById(R.id.check_item).setVisibility(View.VISIBLE);
            }
            return v;
        }
    };
    OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int position) {
        }
    };
    builder.setAdapter(listAdapter, onClickListener);
    if (multipleChoice) {
        if (showAppearanceSetting) {
            final RenderingRuleProperty trackWidthProp;
            final RenderingRuleProperty trackColorProp;
            final RenderingRulesStorage renderer = app.getRendererRegistry().getCurrentSelectedRenderer();
            if (renderer != null) {
                trackWidthProp = renderer.PROPS.getCustomRule(CURRENT_TRACK_WIDTH_ATTR);
                trackColorProp = renderer.PROPS.getCustomRule(CURRENT_TRACK_COLOR_ATTR);
            } else {
                trackWidthProp = null;
                trackColorProp = null;
            }
            if (trackWidthProp == null || trackColorProp == null) {
                builder.setTitle(R.string.show_gpx);
            } else {
                final View apprTitleView = activity.getLayoutInflater().inflate(R.layout.select_gpx_appearance_title, null);
                final OsmandSettings.CommonPreference<String> prefWidth = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_WIDTH_ATTR);
                final OsmandSettings.CommonPreference<String> prefColor = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_COLOR_ATTR);
                updateAppearanceTitle(activity, app, trackWidthProp, renderer, apprTitleView, prefWidth.get(), prefColor.get());
                apprTitleView.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        final ListPopupWindow popup = new ListPopupWindow(activity);
                        popup.setAnchorView(apprTitleView);
                        popup.setContentWidth(AndroidUtils.dpToPx(activity, 200f));
                        popup.setModal(true);
                        popup.setDropDownGravity(Gravity.RIGHT | Gravity.TOP);
                        popup.setVerticalOffset(AndroidUtils.dpToPx(activity, -48f));
                        popup.setHorizontalOffset(AndroidUtils.dpToPx(activity, -6f));
                        final GpxAppearanceAdapter gpxApprAdapter = new GpxAppearanceAdapter(activity, gpxAppearanceParams.containsKey(CURRENT_TRACK_COLOR_ATTR) ? gpxAppearanceParams.get(CURRENT_TRACK_COLOR_ATTR) : prefColor.get(), GpxAppearanceAdapter.GpxAppearanceAdapterType.TRACK_WIDTH_COLOR);
                        popup.setAdapter(gpxApprAdapter);
                        popup.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                AppearanceListItem item = gpxApprAdapter.getItem(position);
                                if (item != null) {
                                    if (item.getAttrName() == CURRENT_TRACK_WIDTH_ATTR) {
                                        gpxAppearanceParams.put(CURRENT_TRACK_WIDTH_ATTR, item.getValue());
                                    } else if (item.getAttrName() == CURRENT_TRACK_COLOR_ATTR) {
                                        gpxAppearanceParams.put(CURRENT_TRACK_COLOR_ATTR, item.getValue());
                                    }
                                }
                                popup.dismiss();
                                updateAppearanceTitle(activity, app, trackWidthProp, renderer, apprTitleView, gpxAppearanceParams.containsKey(CURRENT_TRACK_WIDTH_ATTR) ? gpxAppearanceParams.get(CURRENT_TRACK_WIDTH_ATTR) : prefWidth.get(), gpxAppearanceParams.containsKey(CURRENT_TRACK_COLOR_ATTR) ? gpxAppearanceParams.get(CURRENT_TRACK_COLOR_ATTR) : prefColor.get());
                            }
                        });
                        popup.show();
                    }
                });
                builder.setCustomTitle(apprTitleView);
            }
        } else {
            builder.setTitle(R.string.show_gpx);
        }
        builder.setPositiveButton(R.string.shared_string_ok, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (gpxAppearanceParams.size() > 0) {
                    for (Map.Entry<String, String> entry : gpxAppearanceParams.entrySet()) {
                        final OsmandSettings.CommonPreference<String> pref = app.getSettings().getCustomRenderProperty(entry.getKey());
                        pref.set(entry.getValue());
                    }
                    if (activity instanceof MapActivity) {
                        ConfigureMapMenu.refreshMapComplete((MapActivity) activity);
                    }
                }
                GPXFile currentGPX = null;
                // clear all previously selected files before adding new one
                OsmandApplication app = (OsmandApplication) activity.getApplication();
                if (app != null && app.getSelectedGpxHelper() != null) {
                    app.getSelectedGpxHelper().clearAllGpxFileToShow();
                }
                if (app != null && showCurrentGpx && adapter.getItem(0).getSelected()) {
                    currentGPX = app.getSavingTrackHelper().getCurrentGpx();
                }
                List<String> s = new ArrayList<>();
                for (int i = (showCurrentGpx ? 1 : 0); i < adapter.length(); i++) {
                    if (adapter.getItem(i).getSelected()) {
                        s.add(list.get(i).getFileName());
                    }
                }
                dialog.dismiss();
                loadGPXFileInDifferentThread(activity, callbackWithObject, dir, currentGPX, s.toArray(new String[s.size()]));
            }
        });
        builder.setNegativeButton(R.string.shared_string_cancel, null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && list.size() > 1 || !showCurrentGpx && list.size() > 0) {
            builder.setNeutralButton(R.string.gpx_add_track, null);
        }
    }
    final AlertDialog dlg = builder.create();
    dlg.setCanceledOnTouchOutside(true);
    if (list.size() == 0 || showCurrentGpx && list.size() == 1) {
        final View footerView = activity.getLayoutInflater().inflate(R.layout.no_gpx_files_list_footer, null);
        TextView descTextView = (TextView) footerView.findViewById(R.id.descFolder);
        String descPrefix = app.getString(R.string.gpx_no_tracks_title_folder);
        SpannableString spannableDesc = new SpannableString(descPrefix + ": " + dir.getAbsolutePath());
        spannableDesc.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), descPrefix.length() + 1, spannableDesc.length(), 0);
        descTextView.setText(spannableDesc);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            footerView.findViewById(R.id.button).setVisibility(View.GONE);
        } else {
            footerView.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    addTrack(activity, dlg);
                }
            });
        }
        dlg.getListView().addFooterView(footerView, null, false);
    }
    dlg.getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (multipleChoice) {
                ContextMenuItem item = adapter.getItem(position);
                item.setSelected(!item.getSelected());
                listAdapter.notifyDataSetInvalidated();
                if (position == 0 && showCurrentGpx && item.getSelected()) {
                    OsmandMonitoringPlugin monitoringPlugin = OsmandPlugin.getEnabledPlugin(OsmandMonitoringPlugin.class);
                    if (monitoringPlugin == null) {
                        AlertDialog.Builder confirm = new AlertDialog.Builder(activity);
                        confirm.setPositiveButton(R.string.shared_string_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(activity, PluginActivity.class);
                                intent.putExtra(PluginActivity.EXTRA_PLUGIN_ID, OsmandMonitoringPlugin.ID);
                                activity.startActivity(intent);
                            }
                        });
                        confirm.setNegativeButton(R.string.shared_string_cancel, null);
                        confirm.setMessage(activity.getString(R.string.enable_plugin_monitoring_services));
                        confirm.show();
                    } else if (!app.getSettings().SAVE_GLOBAL_TRACK_TO_GPX.get()) {
                        monitoringPlugin.controlDialog(activity, false);
                    }
                }
            } else {
                dlg.dismiss();
                if (showCurrentGpx && position == 0) {
                    callbackWithObject.processResult(null);
                } else {
                    String fileName = list.get(position).getFileName();
                    SelectedGpxFile selectedGpxFile = app.getSelectedGpxHelper().getSelectedFileByName(fileName);
                    if (selectedGpxFile != null) {
                        callbackWithObject.processResult(new GPXFile[] { selectedGpxFile.getGpxFile() });
                    } else {
                        loadGPXFileInDifferentThread(activity, callbackWithObject, dir, null, fileName);
                    }
                }
            }
        }
    });
    dlg.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {
            Button addTrackButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEUTRAL);
            if (addTrackButton != null) {
                addTrackButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        addTrack(activity, dlg);
                    }
                });
            }
        }
    });
    dlg.show();
    try {
        dlg.getListView().setFastScrollEnabled(true);
    } catch (Exception e) {
    // java.lang.ClassCastException: com.android.internal.widget.RoundCornerListAdapter
    // Unknown reason but on some devices fail
    }
    return dlg;
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) OsmandApplication(net.osmand.plus.OsmandApplication) HashMap(java.util.HashMap) SpannableString(android.text.SpannableString) OsmandMonitoringPlugin(net.osmand.plus.monitoring.OsmandMonitoringPlugin) Button(android.widget.Button) CompoundButton(android.widget.CompoundButton) GpxDataItem(net.osmand.plus.GPXDatabase.GpxDataItem) ArrayList(java.util.ArrayList) List(java.util.List) TextView(android.widget.TextView) OnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener) ContextMenuItem(net.osmand.plus.ContextMenuItem) OnItemClickListener(android.widget.AdapterView.OnItemClickListener) OsmandSettings(net.osmand.plus.OsmandSettings) SpannableString(android.text.SpannableString) CheckBox(android.widget.CheckBox) AppCompatCheckBox(android.support.v7.widget.AppCompatCheckBox) OnClickListener(android.content.DialogInterface.OnClickListener) AdapterView(android.widget.AdapterView) SelectedGpxFile(net.osmand.plus.GpxSelectionHelper.SelectedGpxFile) File(java.io.File) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) SwitchCompat(android.support.v7.widget.SwitchCompat) DialogInterface(android.content.DialogInterface) AppearanceListItem(net.osmand.plus.dialogs.ConfigureMapMenu.AppearanceListItem) Entry(com.github.mikephil.charting.data.Entry) ListPopupWindow(android.support.v7.widget.ListPopupWindow) GpxAppearanceAdapter(net.osmand.plus.dialogs.ConfigureMapMenu.GpxAppearanceAdapter) MapActivity(net.osmand.plus.activities.MapActivity) ViewGroup(android.view.ViewGroup) RenderingRuleProperty(net.osmand.render.RenderingRuleProperty) Intent(android.content.Intent) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) MarkerView(com.github.mikephil.charting.components.MarkerView) TextView(android.widget.TextView) SuppressLint(android.annotation.SuppressLint) RenderingRulesStorage(net.osmand.render.RenderingRulesStorage) SelectedGpxFile(net.osmand.plus.GpxSelectionHelper.SelectedGpxFile) DateFormat(java.text.DateFormat) StyleSpan(android.text.style.StyleSpan) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) ArrayAdapter(android.widget.ArrayAdapter) CompoundButton(android.widget.CompoundButton)

Example 60 with OsmandApplication

use of net.osmand.plus.OsmandApplication in project Osmand by osmandapp.

the class GpxUiHelper method setDescripionInDialog.

private static void setDescripionInDialog(final ArrayAdapter<?> adapter, final ContextMenuAdapter cmAdapter, Activity activity, final File dir, String filename, final int position) {
    final Application app = activity.getApplication();
    final File f = new File(dir, filename);
    loadGPXFileInDifferentThread(activity, new CallbackWithObject<GPXUtilities.GPXFile[]>() {

        @Override
        public boolean processResult(GPXFile[] result) {
            ContextMenuItem item = cmAdapter.getItem(position);
            item.setTitle(item.getTitle() + "\n" + getDescription((OsmandApplication) app, result[0], f, false));
            adapter.notifyDataSetInvalidated();
            return true;
        }
    }, dir, null, filename);
}
Also used : ContextMenuItem(net.osmand.plus.ContextMenuItem) OsmandApplication(net.osmand.plus.OsmandApplication) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) OsmandApplication(net.osmand.plus.OsmandApplication) Application(android.app.Application) SelectedGpxFile(net.osmand.plus.GpxSelectionHelper.SelectedGpxFile) File(java.io.File) GPXFile(net.osmand.plus.GPXUtilities.GPXFile) GPXUtilities(net.osmand.plus.GPXUtilities)

Aggregations

OsmandApplication (net.osmand.plus.OsmandApplication)181 View (android.view.View)46 TextView (android.widget.TextView)39 ArrayList (java.util.ArrayList)33 AlertDialog (android.support.v7.app.AlertDialog)32 ImageView (android.widget.ImageView)31 DialogInterface (android.content.DialogInterface)27 OsmandSettings (net.osmand.plus.OsmandSettings)27 LatLon (net.osmand.data.LatLon)25 Intent (android.content.Intent)21 AdapterView (android.widget.AdapterView)19 File (java.io.File)17 OsmandMapTileView (net.osmand.plus.views.OsmandMapTileView)15 Location (net.osmand.Location)13 EditText (android.widget.EditText)12 ContextMenuAdapter (net.osmand.plus.ContextMenuAdapter)12 ArrayAdapter (android.widget.ArrayAdapter)11 ListView (android.widget.ListView)11 ContextMenuItem (net.osmand.plus.ContextMenuItem)11 SelectedGpxFile (net.osmand.plus.GpxSelectionHelper.SelectedGpxFile)11