Search in sources :

Example 1 with OsmandMonitoringPlugin

use of net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin 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> gpxInfoList, final ContextMenuAdapter contextMenuAdapter, final int themeRes, final boolean nightMode) {
    final OsmandApplication app = (OsmandApplication) activity.getApplication();
    final File dir = app.getAppPath(IndexConstants.GPX_INDEX_DIR);
    AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, themeRes));
    final int layout = R.layout.gpx_track_item;
    final Map<String, String> gpxAppearanceParams = new HashMap<>();
    final DialogGpxDataItemCallback gpxDataItemCallback = new DialogGpxDataItemCallback(app);
    ArrayList<String> modifiableGpxFileNames = new ArrayList<>(Arrays.asList(contextMenuAdapter.getItemNames()));
    final ArrayAdapter<String> alertDialogAdapter = new ArrayAdapter<String>(activity, layout, R.id.title, modifiableGpxFileNames) {

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

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

        private GpxDataItem getDataItem(GPXInfo info) {
            return app.getGpxDbHelper().getItem(new File(app.getAppPath(IndexConstants.GPX_INDEX_DIR), info.getFileName()), gpxDataItemCallback);
        }

        @Override
        @NonNull
        public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
            // User super class to create the View
            View v = convertView;
            boolean checkLayout = getItemViewType(position) == 0;
            if (v == null) {
                v = View.inflate(new ContextThemeWrapper(activity, themeRes), layout, null);
            }
            final ContextMenuItem item = contextMenuAdapter.getItem(position);
            GPXInfo info = gpxInfoList.get(position);
            boolean currentlyRecordingTrack = showCurrentGpx && position == 0;
            GPXTrackAnalysis analysis = null;
            if (currentlyRecordingTrack) {
                analysis = app.getSavingTrackHelper().getCurrentTrack().getTrackAnalysis(app);
            } else {
                GpxDataItem dataItem = getDataItem(info);
                if (dataItem != null) {
                    analysis = dataItem.getAnalysis();
                }
            }
            updateGpxInfoView(v, item.getTitle(), info, analysis, 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 = 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);
                        }
                    });
                    UiUtilities.setupCompoundButton(ch, nightMode, PROFILE_DEPENDENT);
                } else {
                    final SwitchCompat ch = 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);
                        }
                    });
                    UiUtilities.setupCompoundButton(ch, nightMode, PROFILE_DEPENDENT);
                }
                v.findViewById(R.id.check_item).setVisibility(View.VISIBLE);
            }
            return v;
        }
    };
    OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int position) {
        }
    };
    gpxDataItemCallback.setListAdapter(alertDialogAdapter);
    builder.setAdapter(alertDialogAdapter, 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 = View.inflate(new ContextThemeWrapper(activity, themeRes), R.layout.select_gpx_appearance_title, null);
                final CommonPreference<String> prefWidth = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_WIDTH_ATTR);
                final 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(new ContextThemeWrapper(activity, themeRes));
                        popup.setAnchorView(apprTitleView);
                        popup.setContentWidth(AndroidUtils.dpToPx(activity, 200f));
                        popup.setModal(true);
                        popup.setDropDownGravity(Gravity.END | Gravity.TOP);
                        popup.setVerticalOffset(AndroidUtils.dpToPx(activity, -48f));
                        popup.setHorizontalOffset(AndroidUtils.dpToPx(activity, -6f));
                        final GpxAppearanceAdapter gpxApprAdapter = new GpxAppearanceAdapter(new ContextThemeWrapper(activity, themeRes), gpxAppearanceParams.containsKey(CURRENT_TRACK_COLOR_ATTR) ? gpxAppearanceParams.get(CURRENT_TRACK_COLOR_ATTR) : prefColor.get(), GpxAppearanceAdapter.GpxAppearanceAdapterType.TRACK_WIDTH_COLOR, gpxAppearanceParams.containsKey(SHOW_START_FINISH_ATTR) ? "true".equals(gpxAppearanceParams.get(SHOW_START_FINISH_ATTR)) : app.getSettings().SHOW_START_FINISH_ICONS.get(), nightMode);
                        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 (CURRENT_TRACK_WIDTH_ATTR.equals(item.getAttrName())) {
                                        gpxAppearanceParams.put(CURRENT_TRACK_WIDTH_ATTR, item.getValue());
                                    } else if (CURRENT_TRACK_COLOR_ATTR.equals(item.getAttrName())) {
                                        gpxAppearanceParams.put(CURRENT_TRACK_COLOR_ATTR, item.getValue());
                                    } else if (SHOW_START_FINISH_ATTR.equals(item.getAttrName())) {
                                        gpxAppearanceParams.put(SHOW_START_FINISH_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()) {
                        if (SHOW_START_FINISH_ATTR.equals(entry.getKey())) {
                            app.getSettings().SHOW_START_FINISH_ICONS.set("true".equals(entry.getValue()));
                        } else {
                            final CommonPreference<String> pref = app.getSettings().getCustomRenderProperty(entry.getKey());
                            pref.set(entry.getValue());
                        }
                    }
                    if (activity instanceof MapActivity) {
                        ((MapActivity) activity).refreshMapComplete();
                    }
                }
                GPXFile currentGPX = null;
                // clear all previously selected files before adding new one
                OsmandApplication app = (OsmandApplication) activity.getApplication();
                if (app.getSelectedGpxHelper() != null) {
                    app.getSelectedGpxHelper().clearAllGpxFilesToShow(false);
                }
                if (showCurrentGpx && contextMenuAdapter.getItem(0).getSelected()) {
                    currentGPX = app.getSavingTrackHelper().getCurrentGpx();
                }
                List<String> selectedGpxNames = new ArrayList<>();
                for (int i = (showCurrentGpx ? 1 : 0); i < contextMenuAdapter.length(); i++) {
                    if (contextMenuAdapter.getItem(i).getSelected()) {
                        selectedGpxNames.add(gpxInfoList.get(i).getFileName());
                    }
                }
                dialog.dismiss();
                updateSelectedTracksAppearance(app, selectedGpxNames, gpxAppearanceParams);
                loadGPXFileInDifferentThread(activity, callbackWithObject, dir, currentGPX, selectedGpxNames.toArray(new String[0]));
            }
        });
        builder.setNegativeButton(R.string.shared_string_cancel, null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && gpxInfoList.size() > 1 || !showCurrentGpx && gpxInfoList.size() > 0) {
            builder.setNeutralButton(R.string.gpx_add_track, null);
        }
    }
    final AlertDialog dlg = builder.create();
    dlg.setCanceledOnTouchOutside(true);
    if (gpxInfoList.size() == 0 || showCurrentGpx && gpxInfoList.size() == 1) {
        final View footerView = activity.getLayoutInflater().inflate(R.layout.no_gpx_files_list_footer, null);
        TextView descTextView = 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, alertDialogAdapter, contextMenuAdapter, gpxInfoList);
                }
            });
        }
        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 = contextMenuAdapter.getItem(position);
                item.setSelected(!item.getSelected());
                alertDialogAdapter.notifyDataSetInvalidated();
                if (position == 0 && showCurrentGpx && item.getSelected()) {
                    OsmandMonitoringPlugin monitoringPlugin = OsmandPlugin.getActivePlugin(OsmandMonitoringPlugin.class);
                    if (monitoringPlugin == null) {
                        AlertDialog.Builder confirm = new AlertDialog.Builder(new ContextThemeWrapper(activity, themeRes));
                        confirm.setPositiveButton(R.string.shared_string_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Bundle params = new Bundle();
                                params.putBoolean(PluginsFragment.OPEN_PLUGINS, true);
                                MapActivity.launchMapActivityMoveToTop(activity, null, null, params);
                            }
                        });
                        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);
                    }
                }
            } else {
                dlg.dismiss();
                if (showCurrentGpx && position == 0) {
                    callbackWithObject.processResult(null);
                } else {
                    String fileName = gpxInfoList.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, alertDialogAdapter, contextMenuAdapter, gpxInfoList);
                    }
                });
            }
        }
    });
    dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            gpxDataItemCallback.setUpdateEnable(false);
        }
    });
    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(androidx.appcompat.app.AlertDialog) OsmandApplication(net.osmand.plus.OsmandApplication) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) OsmandMonitoringPlugin(net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin) Button(android.widget.Button) CompoundButton(android.widget.CompoundButton) NonNull(androidx.annotation.NonNull) GpxDataItem(net.osmand.plus.track.helpers.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) GPXTrackAnalysis(net.osmand.GPXUtilities.GPXTrackAnalysis) SpannableString(android.text.SpannableString) CheckBox(android.widget.CheckBox) OnClickListener(android.content.DialogInterface.OnClickListener) AdapterView(android.widget.AdapterView) GPXFile(net.osmand.GPXUtilities.GPXFile) SelectedGpxFile(net.osmand.plus.track.helpers.GpxSelectionHelper.SelectedGpxFile) File(java.io.File) SwitchCompat(androidx.appcompat.widget.SwitchCompat) DialogInterface(android.content.DialogInterface) AppearanceListItem(net.osmand.plus.track.GpxAppearanceAdapter.AppearanceListItem) Entry(com.github.mikephil.charting.data.Entry) BarEntry(com.github.mikephil.charting.data.BarEntry) ListPopupWindow(androidx.appcompat.widget.ListPopupWindow) GpxAppearanceAdapter(net.osmand.plus.track.GpxAppearanceAdapter) MapActivity(net.osmand.plus.activities.MapActivity) CommonPreference(net.osmand.plus.settings.backend.preferences.CommonPreference) ViewGroup(android.view.ViewGroup) Bundle(android.os.Bundle) RenderingRuleProperty(net.osmand.render.RenderingRuleProperty) ImageView(android.widget.ImageView) GpxMarkerView(net.osmand.plus.track.GpxMarkerView) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) RenderingRulesStorage(net.osmand.render.RenderingRulesStorage) ActivityNotFoundException(android.content.ActivityNotFoundException) ContextThemeWrapper(android.view.ContextThemeWrapper) SelectedGpxFile(net.osmand.plus.track.helpers.GpxSelectionHelper.SelectedGpxFile) StyleSpan(android.text.style.StyleSpan) GPXFile(net.osmand.GPXUtilities.GPXFile) ArrayAdapter(android.widget.ArrayAdapter) CompoundButton(android.widget.CompoundButton)

Example 2 with OsmandMonitoringPlugin

use of net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin 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);
            GPXFile gpx = null;
            if (path != null) {
                File f = new File(path);
                if (f.exists()) {
                    gpx = GPXUtilities.loadGPXFile(f);
                }
            } else if (intent.getStringExtra(PARAM_DATA) != null) {
                String gpxStr = intent.getStringExtra(PARAM_DATA);
                if (!Algorithms.isEmpty(gpxStr)) {
                    gpx = GPXUtilities.loadGPXFile(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(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) {
                    boolean force = uri.getBooleanQueryParameter(PARAM_FORCE, false);
                    boolean locationPermission = uri.getBooleanQueryParameter(PARAM_LOCATION_PERMISSION, false);
                    saveAndNavigateGpx(mapActivity, gpx, force, locationPermission);
                } 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 = findNavigationProfile(app, profileStr);
            if (profile == null) {
                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(startLatStr);
                    double lon = Double.parseDouble(startLonStr);
                    start = new LatLon(lat, lon);
                    startDesc = new PointDescription(PointDescription.POINT_TYPE_LOCATION, startName);
                } else {
                    start = null;
                    startDesc = null;
                }
                String destLatStr = uri.getQueryParameter(PARAM_DEST_LAT);
                String destLonStr = uri.getQueryParameter(PARAM_DEST_LON);
                final LatLon dest;
                if (!Algorithms.isEmpty(destLatStr) && !Algorithms.isEmpty(destLonStr)) {
                    double destLat = Double.parseDouble(destLatStr);
                    double destLon = Double.parseDouble(destLonStr);
                    dest = new LatLon(destLat, destLon);
                } else {
                    dest = null;
                }
                final PointDescription destDesc = new PointDescription(PointDescription.POINT_TYPE_LOCATION, destName);
                boolean force = uri.getBooleanQueryParameter(PARAM_FORCE, false);
                final boolean locationPermission = uri.getBooleanQueryParameter(PARAM_LOCATION_PERMISSION, false);
                final RoutingHelper routingHelper = app.getRoutingHelper();
                if (routingHelper.isFollowingMode() && !force) {
                    mapActivity.getMapActions().stopNavigationActionConfirm(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (!routingHelper.isFollowingMode()) {
                                startNavigation(mapActivity, start, startDesc, dest, destDesc, profile, locationPermission);
                            }
                        }
                    });
                } else {
                    startNavigation(mapActivity, start, startDesc, dest, destDesc, profile, locationPermission);
                }
            }
        } else if (API_CMD_NAVIGATE_SEARCH.equals(cmd)) {
            String profileStr = uri.getQueryParameter(PARAM_PROFILE);
            final ApplicationMode profile = findNavigationProfile(app, profileStr);
            final boolean showSearchResults = uri.getBooleanQueryParameter(PARAM_SHOW_SEARCH_RESULTS, false);
            final String searchQuery = uri.getQueryParameter(PARAM_DEST_SEARCH_QUERY);
            if (Algorithms.isEmpty(searchQuery)) {
                resultCode = RESULT_CODE_ERROR_EMPTY_SEARCH_QUERY;
            } else if (profile == null) {
                resultCode = RESULT_CODE_ERROR_INVALID_PROFILE;
            } else {
                String startName = uri.getQueryParameter(PARAM_START_NAME);
                if (Algorithms.isEmpty(startName)) {
                    startName = "";
                }
                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(startLatStr);
                    double lon = Double.parseDouble(startLonStr);
                    start = new LatLon(lat, lon);
                    startDesc = new PointDescription(PointDescription.POINT_TYPE_LOCATION, startName);
                } else {
                    start = null;
                    startDesc = null;
                }
                final LatLon searchLocation;
                String searchLatStr = uri.getQueryParameter(PARAM_SEARCH_LAT);
                String searchLonStr = uri.getQueryParameter(PARAM_SEARCH_LON);
                if (!Algorithms.isEmpty(searchLatStr) && !Algorithms.isEmpty(searchLonStr)) {
                    double lat = Double.parseDouble(searchLatStr);
                    double lon = Double.parseDouble(searchLonStr);
                    searchLocation = new LatLon(lat, lon);
                } else {
                    searchLocation = null;
                }
                if (searchLocation == null) {
                    resultCode = RESULT_CODE_ERROR_SEARCH_LOCATION_UNDEFINED;
                } else {
                    boolean force = uri.getBooleanQueryParameter(PARAM_FORCE, false);
                    final boolean locationPermission = uri.getBooleanQueryParameter(PARAM_LOCATION_PERMISSION, false);
                    final RoutingHelper routingHelper = app.getRoutingHelper();
                    if (routingHelper.isFollowingMode() && !force) {
                        mapActivity.getMapActions().stopNavigationActionConfirm(new DialogInterface.OnDismissListener() {

                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                if (!routingHelper.isFollowingMode()) {
                                    searchAndNavigate(mapActivity, searchLocation, start, startDesc, profile, searchQuery, showSearchResults, locationPermission);
                                }
                            }
                        });
                    } else {
                        searchAndNavigate(mapActivity, searchLocation, start, startDesc, profile, searchQuery, showSearchResults, locationPermission);
                    }
                    resultCode = Activity.RESULT_OK;
                }
            }
        } else if (API_CMD_PAUSE_NAVIGATION.equals(cmd)) {
            RoutingHelper routingHelper = mapActivity.getRoutingHelper();
            if (routingHelper.isRouteCalculated() && !routingHelper.isRoutePlanningMode()) {
                routingHelper.setRoutePlanningMode(true);
                routingHelper.setFollowingMode(false);
                routingHelper.setPauseNavigation(true);
                resultCode = Activity.RESULT_OK;
            }
        } else if (API_CMD_RESUME_NAVIGATION.equals(cmd)) {
            RoutingHelper routingHelper = mapActivity.getRoutingHelper();
            if (routingHelper.isRouteCalculated() && routingHelper.isRoutePlanningMode()) {
                routingHelper.setRoutePlanningMode(false);
                routingHelper.setFollowingMode(true);
                resultCode = Activity.RESULT_OK;
            }
        } else if (API_CMD_STOP_NAVIGATION.equals(cmd)) {
            RoutingHelper routingHelper = mapActivity.getRoutingHelper();
            if (routingHelper.isPauseNavigation() || routingHelper.isFollowingMode()) {
                mapActivity.getMapLayers().getMapControlsLayer().stopNavigationWithoutConfirm();
                resultCode = Activity.RESULT_OK;
            }
        } else if (API_CMD_MUTE_NAVIGATION.equals(cmd)) {
            mapActivity.getRoutingHelper().getVoiceRouter().setMute(true);
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_UNMUTE_NAVIGATION.equals(cmd)) {
            mapActivity.getRoutingHelper().getVoiceRouter().setMute(false);
            resultCode = Activity.RESULT_OK;
        } 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.getActivePlugin(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());
            }
            LatLon mapLocation = mapActivity.getMapLocation();
            if (location != null) {
                result.putExtra(PARAM_MAP_LAT, mapLocation.getLatitude());
                result.putExtra(PARAM_MAP_LON, mapLocation.getLongitude());
            }
            RoutingHelper routingHelper = app.getRoutingHelper();
            if (routingHelper.isRouteCalculated()) {
                LatLon finalLocation = routingHelper.getFinalLocation();
                result.putExtra(PARAM_DESTINATION_LAT, finalLocation.getLatitude());
                result.putExtra(PARAM_DESTINATION_LON, finalLocation.getLongitude());
                int time = routingHelper.getLeftTime();
                long eta = time + System.currentTimeMillis() / 1000;
                result.putExtra(PARAM_ETA, eta);
                result.putExtra(PARAM_TIME_LEFT, time);
                result.putExtra(PARAM_DISTANCE_LEFT, routingHelper.getLeftDistance());
                result.putExtras(getRouteDirectionsInfo(app));
            }
            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);
            FavouritesHelper helper = app.getFavoritesHelper();
            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, null);
            MapMarker marker = markersHelper.getFirstMapMarker();
            if (marker != null) {
                showOnMap(lat, lon, marker, mapActivity.getMapLayers().getMapMarkersLayer().getObjectName(marker));
            }
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_SHOW_LOCATION.equals(cmd)) {
            double lat = Double.parseDouble(uri.getQueryParameter(PARAM_LAT));
            double lon = Double.parseDouble(uri.getQueryParameter(PARAM_LON));
            showOnMap(lat, lon, null, null);
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_START_GPX_REC.equals(cmd)) {
            OsmandMonitoringPlugin plugin = OsmandPlugin.getActivePlugin(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.getActivePlugin(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_SAVE_GPX.equals(cmd)) {
            OsmandMonitoringPlugin plugin = OsmandPlugin.getActivePlugin(OsmandMonitoringPlugin.class);
            if (plugin == null) {
                resultCode = RESULT_CODE_ERROR_PLUGIN_INACTIVE;
                finish = true;
            } else {
                plugin.saveCurrentTrack();
            }
            if (uri.getBooleanQueryParameter(PARAM_CLOSE_AFTER_COMMAND, true)) {
                finish = true;
            }
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_CLEAR_GPX.equals(cmd)) {
            OsmandMonitoringPlugin plugin = OsmandPlugin.getActivePlugin(OsmandMonitoringPlugin.class);
            if (plugin == null) {
                resultCode = RESULT_CODE_ERROR_PLUGIN_INACTIVE;
                finish = true;
            } else {
                app.getSavingTrackHelper().clearRecordedData(true);
            }
            if (uri.getBooleanQueryParameter(PARAM_CLOSE_AFTER_COMMAND, true)) {
                finish = true;
            }
            resultCode = Activity.RESULT_OK;
        } else if (API_CMD_EXECUTE_QUICK_ACTION.equals(cmd)) {
            int actionNumber = Integer.parseInt(uri.getQueryParameter(PARAM_QUICK_ACTION_NUMBER));
            List<QuickAction> actionsList = app.getQuickActionRegistry().getFilteredQuickActions();
            if (actionNumber >= 0 && actionNumber < actionsList.size()) {
                QuickActionRegistry.produceAction(actionsList.get(actionNumber)).execute(mapActivity);
                resultCode = Activity.RESULT_OK;
            } else {
                resultCode = RESULT_CODE_ERROR_QUICK_ACTION_NOT_FOUND;
            }
            if (uri.getBooleanQueryParameter(PARAM_CLOSE_AFTER_COMMAND, true)) {
                finish = true;
            }
        } else if (API_CMD_GET_QUICK_ACTION_INFO.equals(cmd)) {
            int actionNumber = Integer.parseInt(uri.getQueryParameter(PARAM_QUICK_ACTION_NUMBER));
            List<QuickAction> actionsList = app.getQuickActionRegistry().getFilteredQuickActions();
            if (actionNumber >= 0 && actionNumber < actionsList.size()) {
                QuickAction action = actionsList.get(actionNumber);
                Gson gson = new Gson();
                Type type = new TypeToken<HashMap<String, String>>() {
                }.getType();
                result.putExtra(PARAM_QUICK_ACTION_NAME, action.getName(app));
                result.putExtra(PARAM_QUICK_ACTION_TYPE, action.getActionType().getStringId());
                result.putExtra(PARAM_QUICK_ACTION_PARAMS, gson.toJson(action.getParams(), type));
                result.putExtra(PARAM_VERSION, VERSION_CODE);
                resultCode = Activity.RESULT_OK;
            } else {
                resultCode = RESULT_CODE_ERROR_QUICK_ACTION_NOT_FOUND;
            }
            if (uri.getBooleanQueryParameter(PARAM_CLOSE_AFTER_COMMAND, true)) {
                finish = true;
            }
        } 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 : QuickAction(net.osmand.plus.quickaction.QuickAction) OsmandApplication(net.osmand.plus.OsmandApplication) AudioVideoNotesPlugin(net.osmand.plus.plugins.audionotes.AudioVideoNotesPlugin) FavouritePoint(net.osmand.data.FavouritePoint) FavouritesHelper(net.osmand.plus.myplaces.FavouritesHelper) MapMarker(net.osmand.plus.mapmarkers.MapMarker) DialogInterface(android.content.DialogInterface) HashMap(java.util.HashMap) Gson(com.google.gson.Gson) ApplicationMode(net.osmand.plus.settings.backend.ApplicationMode) Uri(android.net.Uri) OsmandMonitoringPlugin(net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin) List(java.util.List) ArrayList(java.util.ArrayList) Intent(android.content.Intent) RoutingHelper(net.osmand.plus.routing.RoutingHelper) ParcelFileDescriptor(android.os.ParcelFileDescriptor) FileDescriptor(java.io.FileDescriptor) FileInputStream(java.io.FileInputStream) FavouritePoint(net.osmand.data.FavouritePoint) LatLon(net.osmand.data.LatLon) Type(java.lang.reflect.Type) ObjectType(net.osmand.search.core.ObjectType) TurnType(net.osmand.router.TurnType) MapMarkersHelper(net.osmand.plus.mapmarkers.MapMarkersHelper) ByteArrayInputStream(java.io.ByteArrayInputStream) PointDescription(net.osmand.data.PointDescription) ParcelFileDescriptor(android.os.ParcelFileDescriptor) GPXFile(net.osmand.GPXUtilities.GPXFile) GPXFile(net.osmand.GPXUtilities.GPXFile) SelectedGpxFile(net.osmand.plus.track.helpers.GpxSelectionHelper.SelectedGpxFile) File(java.io.File) Location(net.osmand.Location)

Example 3 with OsmandMonitoringPlugin

use of net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin in project Osmand by osmandapp.

the class AvailableGPXFragment method updateCurrentTrack.

public void updateCurrentTrack() {
    final OsmandMonitoringPlugin plugin = OsmandPlugin.getActivePlugin(OsmandMonitoringPlugin.class);
    if (currentGpxView == null || plugin == null) {
        return;
    }
    final boolean isRecording = app.getSettings().SAVE_GLOBAL_TRACK_TO_GPX.get();
    ImageView icon = currentGpxView.findViewById(R.id.icon);
    icon.setImageDrawable(app.getUIUtilities().getIcon(R.drawable.monitoring_rec_big));
    icon.setVisibility(selectionMode && showOnMapMode ? View.GONE : View.VISIBLE);
    SavingTrackHelper sth = app.getSavingTrackHelper();
    int activeColorId = ColorUtilities.getActiveColorId(nightMode);
    Button stop = currentGpxView.findViewById(R.id.action_button);
    if (isRecording) {
        currentGpxView.findViewById(R.id.segment_time_div).setVisibility(View.VISIBLE);
        TextView segmentTime = currentGpxView.findViewById(R.id.segment_time);
        segmentTime.setText(OsmAndFormatter.getFormattedDurationShort((int) (sth.getDuration() / 1000)));
        segmentTime.setVisibility(View.VISIBLE);
        Drawable stopIcon = app.getUIUtilities().getIcon(R.drawable.ic_action_rec_stop, activeColorId);
        stop.setCompoundDrawablesWithIntrinsicBounds(stopIcon, null, null, null);
        stop.setText(app.getString(R.string.shared_string_control_stop));
        stop.setContentDescription(app.getString(R.string.gpx_monitoring_stop));
    } else {
        currentGpxView.findViewById(R.id.segment_time_div).setVisibility(View.GONE);
        currentGpxView.findViewById(R.id.segment_time).setVisibility(View.GONE);
        Drawable stopIcon = app.getUIUtilities().getIcon(R.drawable.ic_action_rec_start, activeColorId);
        stop.setCompoundDrawablesWithIntrinsicBounds(stopIcon, null, null, null);
        stop.setText(app.getString(R.string.shared_string_record));
        stop.setContentDescription(app.getString(R.string.gpx_monitoring_start));
    }
    stop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (isRecording) {
                plugin.stopRecording();
                updateCurrentTrack();
            } else if (app.getLocationProvider().checkGPSEnabled(getActivity())) {
                plugin.startGPXMonitoring(getActivity());
                updateCurrentTrack();
            }
        }
    });
    Button save = currentGpxView.findViewById(R.id.save_button);
    Drawable saveIcon = app.getUIUtilities().getIcon(R.drawable.ic_action_gsave_dark, activeColorId);
    save.setCompoundDrawablesWithIntrinsicBounds(saveIcon, null, null, null);
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            plugin.saveCurrentTrack(new Runnable() {

                @Override
                public void run() {
                    if (isResumed()) {
                        reloadTracks();
                    }
                }
            });
            updateCurrentTrack();
        }
    });
    if (sth.getPoints() > 0 || sth.getDistance() > 0) {
        save.setVisibility(View.VISIBLE);
    } else {
        save.setVisibility(View.GONE);
    }
    save.setContentDescription(app.getString(R.string.save_current_track));
    ((TextView) currentGpxView.findViewById(R.id.points_count)).setText(String.valueOf(sth.getPoints()));
    ((TextView) currentGpxView.findViewById(R.id.distance)).setText(OsmAndFormatter.getFormattedDistance(sth.getDistance(), app));
    final CheckBox checkbox = currentGpxView.findViewById(R.id.check_local_index);
    checkbox.setVisibility(selectionMode && showOnMapMode ? View.VISIBLE : View.GONE);
    if (selectionMode && showOnMapMode) {
        checkbox.setChecked(selectedItems.contains(currentRecording));
        checkbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (checkbox.isChecked()) {
                    selectedItems.add(currentRecording);
                } else {
                    selectedItems.remove(currentRecording);
                }
                updateSelectionMode(actionMode);
            }
        });
    }
}
Also used : Drawable(android.graphics.drawable.Drawable) SavingTrackHelper(net.osmand.plus.track.helpers.SavingTrackHelper) ImageView(android.widget.ImageView) SearchView(androidx.appcompat.widget.SearchView) View(android.view.View) TextView(android.widget.TextView) AbsListView(android.widget.AbsListView) ExpandableListView(android.widget.ExpandableListView) OsmandMonitoringPlugin(net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin) ImageButton(android.widget.ImageButton) Button(android.widget.Button) CompoundButton(android.widget.CompoundButton) CheckBox(android.widget.CheckBox) TextView(android.widget.TextView) ImageView(android.widget.ImageView)

Example 4 with OsmandMonitoringPlugin

use of net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin in project Osmand by osmandapp.

the class OsmandAidlApi method stopGpxRecording.

boolean stopGpxRecording() {
    OsmandMonitoringPlugin plugin = OsmandPlugin.getActivePlugin(OsmandMonitoringPlugin.class);
    if (plugin != null) {
        plugin.stopRecording();
        plugin.updateControl();
        return true;
    }
    return false;
}
Also used : OsmandMonitoringPlugin(net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin)

Example 5 with OsmandMonitoringPlugin

use of net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin in project Osmand by osmandapp.

the class OsmandAidlApi method startGpxRecording.

boolean startGpxRecording() {
    OsmandMonitoringPlugin plugin = OsmandPlugin.getActivePlugin(OsmandMonitoringPlugin.class);
    if (plugin != null) {
        plugin.startGPXMonitoring(null);
        plugin.updateControl();
        return true;
    }
    return false;
}
Also used : OsmandMonitoringPlugin(net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin)

Aggregations

OsmandMonitoringPlugin (net.osmand.plus.plugins.monitoring.OsmandMonitoringPlugin)11 Intent (android.content.Intent)3 DialogInterface (android.content.DialogInterface)2 View (android.view.View)2 Button (android.widget.Button)2 CheckBox (android.widget.CheckBox)2 CompoundButton (android.widget.CompoundButton)2 ImageView (android.widget.ImageView)2 TextView (android.widget.TextView)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 GPXFile (net.osmand.GPXUtilities.GPXFile)2 OsmandApplication (net.osmand.plus.OsmandApplication)2 SelectedGpxFile (net.osmand.plus.track.helpers.GpxSelectionHelper.SelectedGpxFile)2 PendingIntent (android.app.PendingIntent)1 ActivityNotFoundException (android.content.ActivityNotFoundException)1 BroadcastReceiver (android.content.BroadcastReceiver)1 Context (android.content.Context)1