first commit
@@ -0,0 +1,15 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/caches
|
||||
/.idea/libraries
|
||||
/.idea/modules.xml
|
||||
/.idea/workspace.xml
|
||||
/.idea/navEditor.xml
|
||||
/.idea/assetWizardSettings.xml
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
@@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
@@ -0,0 +1 @@
|
||||
SafeRoute
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="17" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="testRunner" value="GRADLE" />
|
||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="gradleJvm" value="jbr-17" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/app" />
|
||||
</set>
|
||||
</option>
|
||||
<option name="resolveExternalAnnotations" value="false" />
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectMigrations">
|
||||
<option name="MigrateToGradleLocalJavaHome">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
</set>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
<component name="ProjectType">
|
||||
<option name="id" value="Android" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1 @@
|
||||
/build
|
||||
@@ -0,0 +1,55 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.saferoute"
|
||||
compileSdk = 34
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.example.saferoute"
|
||||
minSdk = 26
|
||||
targetSdk = 34
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation("androidx.appcompat:appcompat:1.7.1")
|
||||
implementation("com.google.android.material:material:1.13.0")
|
||||
implementation("androidx.constraintlayout:constraintlayout:2.2.1")
|
||||
implementation ("androidx.recyclerview:recyclerview:1.2.1")
|
||||
|
||||
implementation("com.google.android.gms:play-services-location:21.3.0")
|
||||
implementation("com.google.android.gms:play-services-maps:20.0.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
implementation("com.yandex.android:maps.mobile:4.4.0-full")
|
||||
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
|
||||
// Добавление зависимости Gson
|
||||
implementation ("com.google.code.gson:gson:2.10.1")
|
||||
|
||||
implementation ("org.osmdroid:osmdroid-android:6.1.14")
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
|
||||
-keep class com.yandex.mapkit.** { *; }
|
||||
-dontwarn com.yandex.**
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class ExampleInstrumentedTest {
|
||||
@Test
|
||||
public void useAppContext() {
|
||||
// Context of the app under test.
|
||||
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
assertEquals("com.example.saferoute", appContext.getPackageName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.telephony"
|
||||
android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
||||
<uses-permission android:name="android.permission.SEND_SMS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.SafeRoute">
|
||||
<meta-data
|
||||
android:name="com.yandex.android.maps.ApiKey"
|
||||
android:value="4bfaac8a-f87f-4c92-a625-beb599b99079" />
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".SettingActivity" />
|
||||
<activity android:name=".contacts.ContactActivity" />
|
||||
<activity android:name=".places.PlaceActivity" />
|
||||
<activity android:name=".places.LocationPlaceActivity"/>
|
||||
<activity android:name=".places.LocationRouteActivity"/>
|
||||
|
||||
</application>
|
||||
</manifest>
|
||||
|
After Width: | Height: | Size: 106 KiB |
@@ -0,0 +1,668 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.location.Location;
|
||||
import android.location.LocationListener;
|
||||
import android.location.LocationManager;
|
||||
import android.media.Ringtone;
|
||||
import android.media.RingtoneManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Vibrator;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.activity.result.ActivityResultLauncher;
|
||||
import androidx.activity.result.contract.ActivityResultContracts;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
|
||||
import com.example.saferoute.contacts.Contact;
|
||||
import com.example.saferoute.contacts.ContactStorage;
|
||||
import com.example.saferoute.places.Place;
|
||||
import com.example.saferoute.places.PlaceStorage;
|
||||
import com.example.saferoute.places.Point;
|
||||
import com.example.saferoute.places.Route;
|
||||
import com.example.saferoute.places.RouteStorage;
|
||||
import com.google.android.gms.location.FusedLocationProviderClient;
|
||||
import com.google.android.gms.location.LocationCallback;
|
||||
import com.google.android.gms.location.LocationRequest;
|
||||
import com.google.android.gms.location.LocationResult;
|
||||
import com.google.android.gms.location.LocationServices;
|
||||
|
||||
import org.osmdroid.config.Configuration;
|
||||
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
|
||||
import org.osmdroid.util.GeoPoint;
|
||||
import org.osmdroid.views.MapView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class MainActivity extends FragmentActivity {
|
||||
|
||||
private static final String TAG = "MainActivity";
|
||||
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
|
||||
|
||||
private FusedLocationProviderClient fusedLocationClient;
|
||||
private LocationCallback locationCallback;
|
||||
private MapView mapView;
|
||||
|
||||
// Текущие координаты (используем единый источник)
|
||||
private double currentLat = 0.0;
|
||||
private double currentLon = 0.0;
|
||||
|
||||
private LocationManager locationManager;
|
||||
private LocationListener locationListener;
|
||||
|
||||
private List<Place> places = new ArrayList<>();
|
||||
private List<Route> routes = new ArrayList<>();
|
||||
|
||||
private Place selectedPlace;
|
||||
private Route selectedRoute;
|
||||
|
||||
|
||||
private ContactStorage contactStorage;
|
||||
private PlaceStorage placeStorage;
|
||||
private RouteStorage routeStorage;
|
||||
|
||||
|
||||
private Button btnGetRoute, btnSOS;
|
||||
|
||||
// Навигация
|
||||
private static final double MAX_DEVIATION_METERS = 30;
|
||||
private List<GeoPoint> routePoints;
|
||||
private int currentSegmentIndex = 0;
|
||||
private boolean isNavigationActive = false;
|
||||
|
||||
// Request permission launcher (регистрация в onCreate)
|
||||
private ActivityResultLauncher<String> requestPermissionLauncher;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
// Osmdroid конфиг — ставим до setContentView
|
||||
Configuration.getInstance().load(this, getSharedPreferences("osmdroid", MODE_PRIVATE));
|
||||
Configuration.getInstance().setUserAgentValue(getPackageName());
|
||||
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
// ========== Инициализация UI и объектов ==========
|
||||
mapView = findViewById(R.id.map);
|
||||
btnGetRoute = findViewById(R.id.btnStartRoute);
|
||||
btnSOS = findViewById(R.id.btnSOS);
|
||||
|
||||
contactStorage = new ContactStorage(this);
|
||||
placeStorage = new PlaceStorage(this);
|
||||
places = placeStorage.loadPlaces();
|
||||
routeStorage = new RouteStorage(this);
|
||||
routes = routeStorage.loadRoutesSync();
|
||||
|
||||
// Настройка карты
|
||||
mapView.setTileSource(TileSourceFactory.MAPNIK);
|
||||
mapView.setBuiltInZoomControls(true);
|
||||
mapView.setMultiTouchControls(true);
|
||||
|
||||
// Инициализация fusedLocationClient до любых вызовов локации!
|
||||
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
|
||||
|
||||
// Локационный колбэк для активного запроса
|
||||
locationCallback = new LocationCallback() {
|
||||
@Override
|
||||
public void onLocationResult(@NonNull LocationResult locationResult) {
|
||||
if (locationResult == null) return;
|
||||
for (Location loc : locationResult.getLocations()) {
|
||||
if (loc != null) {
|
||||
currentLat = loc.getLatitude();
|
||||
currentLon = loc.getLongitude();
|
||||
Log.d(TAG, "Активное получение: " + currentLat + ", " + currentLon);
|
||||
centerMapOnLocation(currentLat, currentLon);
|
||||
stopActiveLocationRequests(); // получили — останавливаем
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ActivityResult API — регистрируем здесь (гарантировано после onAttach)
|
||||
requestPermissionLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.RequestPermission(),
|
||||
isGranted -> {
|
||||
if (isGranted) {
|
||||
Log.d(TAG, "Разрешение получено через ActivityResultLauncher");
|
||||
getAccurateLocation();
|
||||
} else {
|
||||
Toast.makeText(this, "Разрешение на локацию не предоставлено", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчики кнопок
|
||||
btnGetRoute.setOnClickListener(v -> showDestinationDialog());
|
||||
btnSOS.setOnClickListener(v -> SOS(v));
|
||||
|
||||
// Не запрашиваем права дважды: используем единый поток
|
||||
checkAndRequestLocationPermission();
|
||||
|
||||
// Центрируем карту на текущих координатах (если есть last location — будет установлен в getAccurateLocation)
|
||||
// В любом случае устанавливаем минимальный центр, чтобы карта показалась сразу
|
||||
mapView.getController().setZoom(15);
|
||||
mapView.getController().setCenter(new GeoPoint(0.0, 0.0));
|
||||
}
|
||||
|
||||
private void checkAndRequestLocationPermission() {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
== PackageManager.PERMISSION_GRANTED) {
|
||||
getAccurateLocation();
|
||||
} else {
|
||||
requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION);
|
||||
}
|
||||
}
|
||||
|
||||
// Центрирование карты
|
||||
private void centerMapOnLocation(double latitude, double longitude) {
|
||||
if (mapView == null) return;
|
||||
try {
|
||||
mapView.getController().setZoom(16.5);
|
||||
mapView.getController().setCenter(new GeoPoint(latitude, longitude));
|
||||
mapView.invalidate();
|
||||
Log.d(TAG, "Карта центрирована: " + latitude + ", " + longitude);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Ошибка центрирования карты", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Получаем last location или делаем активный запрос
|
||||
private void getAccurateLocation() {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
!= PackageManager.PERMISSION_GRANTED) {
|
||||
Log.w(TAG, "getAccurateLocation вызван без разрешения");
|
||||
return;
|
||||
}
|
||||
|
||||
fusedLocationClient.getLastLocation()
|
||||
.addOnSuccessListener(this, location -> {
|
||||
if (location != null) {
|
||||
currentLat = location.getLatitude();
|
||||
currentLon = location.getLongitude();
|
||||
Log.d(TAG, "getLastLocation: " + currentLat + ", " + currentLon);
|
||||
centerMapOnLocation(currentLat, currentLon);
|
||||
} else {
|
||||
Log.d(TAG, "getLastLocation вернул null, делаем активный запрос");
|
||||
startActiveLocationRequest();
|
||||
}
|
||||
})
|
||||
.addOnFailureListener(this, e -> {
|
||||
Log.e(TAG, "Ошибка getLastLocation: " + e.getMessage());
|
||||
startActiveLocationRequest();
|
||||
});
|
||||
}
|
||||
|
||||
private void startActiveLocationRequest() {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
!= PackageManager.PERMISSION_GRANTED) return;
|
||||
|
||||
LocationRequest lr = LocationRequest.create()
|
||||
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
|
||||
.setNumUpdates(1)
|
||||
.setInterval(2000);
|
||||
|
||||
fusedLocationClient.requestLocationUpdates(lr, locationCallback, getMainLooper());
|
||||
Log.d(TAG, "Запрошено активное получение локации");
|
||||
}
|
||||
|
||||
private void stopActiveLocationRequests() {
|
||||
if (fusedLocationClient != null && locationCallback != null) {
|
||||
fusedLocationClient.removeLocationUpdates(locationCallback);
|
||||
Log.d(TAG, "Активный запрос локации остановлен");
|
||||
}
|
||||
}
|
||||
|
||||
// ========= Dialog и построение маршрута (ORS) =========
|
||||
private void showDestinationDialog() {
|
||||
if ((places == null || places.isEmpty()) && routes == null || routes.isEmpty()) {
|
||||
Toast.makeText(this, "Список мест пуст", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(this);
|
||||
builder.setTitle("Выберите точку назначения");
|
||||
|
||||
List<String> list = new ArrayList<>();
|
||||
for (Place item : places)
|
||||
list.add(item.getTitle());
|
||||
for (Route item : routes)
|
||||
list.add(item.getTitle());
|
||||
|
||||
String[] result = list.toArray(new String[0]);
|
||||
|
||||
builder.setSingleChoiceItems(result, -1, (dialog, which) -> {
|
||||
if (which < places.size()) {
|
||||
selectedPlace = places.get(which);
|
||||
dialog.dismiss();
|
||||
buildRouteToPlace();
|
||||
} else {
|
||||
selectedRoute = routes.get(which - places.size());
|
||||
dialog.dismiss();
|
||||
buildRoute();
|
||||
|
||||
}
|
||||
Toast.makeText(this, "Выбрано: " + result[which], Toast.LENGTH_SHORT).show();
|
||||
|
||||
|
||||
});
|
||||
builder.setNegativeButton("Отмена", (dialog, which) -> dialog.dismiss());
|
||||
builder.show();
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void buildRouteToPlace() {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
!= PackageManager.PERMISSION_GRANTED) {
|
||||
Toast.makeText(this, "Нет доступа к локации", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
// Убедимся, что у нас есть актуальные координаты
|
||||
final double startLon = currentLon;
|
||||
final double startLat = currentLat;
|
||||
final double endLon = selectedPlace.getLongitude();
|
||||
final double endLat = selectedPlace.getLatitude();
|
||||
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl("https://api.openrouteservice.org/")
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build();
|
||||
|
||||
ORSService service = retrofit.create(ORSService.class);
|
||||
String apiKey = "eyJvcmciOiI1YjNjZTM1OTc4NTExMTAwMDFjZjYyNDgiLCJpZCI6IjVhNDU5MGQxOTNjNzQxYTNhOTA4MDY5Nzg4ZWUxMDM1IiwiaCI6Im11cm11cjY0In0=";
|
||||
|
||||
// Получаем координаты для запроса в формате "lat,lon"
|
||||
String start = startLon + "," + startLat;
|
||||
String end = endLon + "," + endLat;
|
||||
|
||||
service.getFootRoute(apiKey, start, end).enqueue(new Callback<ORSResponse>() {
|
||||
@Override
|
||||
public void onResponse(Call<ORSResponse> call, Response<ORSResponse> response) {
|
||||
if (response.isSuccessful() && response.body() != null && !response.body().features.isEmpty()) {
|
||||
List<List<Double>> coords = response.body().features.get(0).geometry.coordinates;
|
||||
List<GeoPoint> route = new ArrayList<>();
|
||||
for (List<Double> p : coords) route.add(new GeoPoint(p.get(1), p.get(0)));
|
||||
drawRouteOnMap(route);
|
||||
startNavigation(route);
|
||||
} else {
|
||||
Log.e(TAG, "Ошибка маршрута. Код: " + response.code());
|
||||
Toast.makeText(MainActivity.this, "Ошибка получения маршрута", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<ORSResponse> call, Throwable t) {
|
||||
Log.e(TAG, "Network error: " + t.getMessage());
|
||||
Toast.makeText(MainActivity.this, "Ошибка сети: " + t.getMessage(), Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private void buildRoute() {
|
||||
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl("https://api.openrouteservice.org/") // НОВЫЙ URL
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build();
|
||||
|
||||
ORSService service = retrofit.create(ORSService.class);
|
||||
|
||||
// Преобразуем List<GeoPoint> в формат для API [[lon, lat], [lon, lat], ...]
|
||||
List<double[]> coordsForApi = new ArrayList<>();
|
||||
for (Point p : selectedRoute.points) {
|
||||
coordsForApi.add(new double[]{p.lon, p.lat});
|
||||
}
|
||||
|
||||
ORSRequest requestBody = new ORSRequest(coordsForApi);
|
||||
String apiKey = "eyJvcmciOiI1YjNjZTM1OTc4NTExMTAwMDFjZjYyNDgiLCJpZCI6IjVhNDU5MGQxOTNjNzQxYTNhOTA4MDY5Nzg4ZWUxMDM1IiwiaCI6Im11cm11cjY0In0=";
|
||||
|
||||
service.getMultiPointRoute(apiKey, requestBody).enqueue(new Callback<ORSResponse>() {
|
||||
@Override
|
||||
public void onResponse(Call<ORSResponse> call, Response<ORSResponse> response) {
|
||||
if (response.isSuccessful() && response.body() != null) {
|
||||
|
||||
|
||||
// Получаем «сырые» координаты пути от ORS [[lon, lat], [lon, lat], ...]
|
||||
List<List<Double>> rawCoords = response.body().features.get(0).geometry.coordinates;
|
||||
|
||||
// Конвертируем их в List<GeoPoint>
|
||||
List<GeoPoint> routePoints = new ArrayList<>();
|
||||
for (List<Double> coord : rawCoords) {
|
||||
// Важно: ORS возвращает [Lon, Lat], а GeoPoint создается как (Lat, Lon)
|
||||
double lon = coord.get(0);
|
||||
double lat = coord.get(1);
|
||||
routePoints.add(new GeoPoint(lat, lon));
|
||||
}
|
||||
|
||||
// Передаем готовый список в ваш метод отрисовки
|
||||
drawRoute(routePoints);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<ORSResponse> call, Throwable t) {
|
||||
Log.e("API", "Ошибка: " + t.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void drawRoute(List<GeoPoint> points) {
|
||||
if (points == null || points.isEmpty()) return;
|
||||
|
||||
// Сохраняем, что это текущий показанный маршрут
|
||||
List<GeoPoint> lastRoutePoints = new ArrayList<>(points);
|
||||
|
||||
|
||||
// третья версия
|
||||
// Удаляем старые Polyline-ы безопасно (итерация с конца)
|
||||
for (int i = mapView.getOverlays().size() - 1; i >= 0; i--) {
|
||||
org.osmdroid.views.overlay.Overlay ov = mapView.getOverlays().get(i);
|
||||
if (ov instanceof org.osmdroid.views.overlay.Polyline) {
|
||||
mapView.getOverlays().remove(i);
|
||||
}
|
||||
}
|
||||
|
||||
org.osmdroid.views.overlay.Polyline polyline = new org.osmdroid.views.overlay.Polyline();
|
||||
polyline.setPoints(points);
|
||||
polyline.setColor(0x880000FF); // Полупрозрачный синий
|
||||
polyline.setWidth(10f);
|
||||
|
||||
|
||||
mapView.getOverlays().add(polyline);
|
||||
mapView.invalidate(); // Перерисовываем карту
|
||||
|
||||
// Автоматически центрируем и масштабируем карту под маршрут
|
||||
try {
|
||||
mapView.zoomToBoundingBox(polyline.getBounds(), false);
|
||||
} catch (Exception e) {
|
||||
Log.w("DRAW_ROUTE", "Не удалось масштабировать bounding box: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Безопасное удаление старых overlay-ов и отрисовка новой линии
|
||||
private void drawRouteOnMap(List<GeoPoint> points) {
|
||||
if (mapView == null || points == null || points.isEmpty()) return;
|
||||
|
||||
// Удаляем старые Polyline-ы безопасно (итерируем с конца)
|
||||
List<org.osmdroid.views.overlay.Overlay> overlays = mapView.getOverlays();
|
||||
for (int i = overlays.size() - 1; i >= 0; i--) {
|
||||
org.osmdroid.views.overlay.Overlay ov = overlays.get(i);
|
||||
if (ov instanceof org.osmdroid.views.overlay.Polyline) {
|
||||
overlays.remove(i);
|
||||
}
|
||||
}
|
||||
|
||||
org.osmdroid.views.overlay.Polyline polyline = new org.osmdroid.views.overlay.Polyline();
|
||||
polyline.setPoints(points);
|
||||
polyline.setColor(0x880000FF);
|
||||
polyline.setWidth(10f);
|
||||
mapView.getOverlays().add(polyline);
|
||||
mapView.invalidate();
|
||||
|
||||
try {
|
||||
mapView.zoomToBoundingBox(polyline.getBounds(), false);
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Не удалось масштабировать bbox: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ========== Навигация и позиционирование ==========
|
||||
|
||||
public void startNavigation(List<GeoPoint> points) {
|
||||
if (points == null || points.isEmpty()) return;
|
||||
this.routePoints = points;
|
||||
currentSegmentIndex = 0;
|
||||
isNavigationActive = true;
|
||||
startLocationUpdatesForNavigation();
|
||||
}
|
||||
|
||||
private void updateCurrentPosition(Location location) {
|
||||
if (mapView == null || location == null) return;
|
||||
|
||||
// Удаляем старые маркеры безопасно
|
||||
List<org.osmdroid.views.overlay.Overlay> overlays = mapView.getOverlays();
|
||||
for (int i = overlays.size() - 1; i >= 0; i--) {
|
||||
org.osmdroid.views.overlay.Overlay ov = overlays.get(i);
|
||||
if (ov instanceof org.osmdroid.views.overlay.Marker) overlays.remove(i);
|
||||
}
|
||||
|
||||
org.osmdroid.views.overlay.Marker marker = new org.osmdroid.views.overlay.Marker(mapView);
|
||||
marker.setPosition(new GeoPoint(location.getLatitude(), location.getLongitude()));
|
||||
marker.setIcon(getResources().getDrawable(R.drawable.ic_location1));
|
||||
mapView.getOverlays().add(marker);
|
||||
mapView.invalidate();
|
||||
}
|
||||
|
||||
private void startLocationUpdatesForNavigation() {
|
||||
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
|
||||
if (locationManager == null) {
|
||||
Toast.makeText(this, "LocationManager недоступен", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
Toast.makeText(this, "Включите GPS для навигации", Toast.LENGTH_LONG).show();
|
||||
return;
|
||||
}
|
||||
|
||||
locationListener = new LocationListener() {
|
||||
@Override
|
||||
public void onLocationChanged(@NonNull Location location) {
|
||||
updateCurrentPosition(location);
|
||||
checkDeviation(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderEnabled(@NonNull String provider) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderDisabled(@NonNull String provider) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) {
|
||||
}
|
||||
};
|
||||
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
== PackageManager.PERMISSION_GRANTED) {
|
||||
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 3, locationListener);
|
||||
}
|
||||
}
|
||||
|
||||
private void stopNavigationLocationUpdates() {
|
||||
if (locationManager != null && locationListener != null) {
|
||||
try {
|
||||
locationManager.removeUpdates(locationListener);
|
||||
} catch (SecurityException e) {
|
||||
Log.w(TAG, "removeUpdates failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
locationListener = null;
|
||||
locationManager = null;
|
||||
}
|
||||
|
||||
private void checkDeviation(Location currentLocation) {
|
||||
if (!isNavigationActive || routePoints == null || routePoints.isEmpty() || currentLocation == null)
|
||||
return;
|
||||
|
||||
GeoPoint currentPoint = new GeoPoint(currentLocation.getLatitude(), currentLocation.getLongitude());
|
||||
|
||||
double minDistance = Double.MAX_VALUE;
|
||||
int closestIndex = -1;
|
||||
for (int i = 0; i < routePoints.size(); i++) {
|
||||
double d = currentPoint.distanceToAsDouble(routePoints.get(i));
|
||||
if (d < minDistance) {
|
||||
minDistance = d;
|
||||
closestIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
if (closestIndex > currentSegmentIndex + 1) currentSegmentIndex = closestIndex - 1;
|
||||
|
||||
if (currentSegmentIndex < routePoints.size() - 1) {
|
||||
GeoPoint a = routePoints.get(currentSegmentIndex);
|
||||
GeoPoint b = routePoints.get(currentSegmentIndex + 1);
|
||||
double deviation = calculateDistanceToSegment(currentPoint, a, b);
|
||||
if (deviation > MAX_DEVIATION_METERS) handleDeviation(deviation);
|
||||
else {
|
||||
double toEnd = currentPoint.distanceToAsDouble(b);
|
||||
if (toEnd < 10) {
|
||||
currentSegmentIndex++;
|
||||
if (currentSegmentIndex >= routePoints.size() - 1) navigationComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private double calculateDistanceToSegment(GeoPoint point, GeoPoint start, GeoPoint end) {
|
||||
double A = point.getLatitude() - start.getLatitude();
|
||||
double B = point.getLongitude() - start.getLongitude();
|
||||
double C = end.getLatitude() - start.getLatitude();
|
||||
double D = end.getLongitude() - start.getLongitude();
|
||||
|
||||
double dot = A * C + B * D;
|
||||
double lenSq = C * C + D * D;
|
||||
double param = (lenSq != 0) ? (dot / lenSq) : -1;
|
||||
|
||||
double xx, yy;
|
||||
if (param < 0) {
|
||||
xx = start.getLatitude();
|
||||
yy = start.getLongitude();
|
||||
} else if (param > 1) {
|
||||
xx = end.getLatitude();
|
||||
yy = end.getLongitude();
|
||||
} else {
|
||||
xx = start.getLatitude() + param * C;
|
||||
yy = start.getLongitude() + param * D;
|
||||
}
|
||||
|
||||
double dx = point.getLatitude() - xx;
|
||||
double dy = point.getLongitude() - yy;
|
||||
|
||||
return Math.sqrt(dx * dx + dy * dy) * 111319.9;
|
||||
}
|
||||
|
||||
private void handleDeviation(double deviation) {
|
||||
Log.w(TAG, "Отклонение: " + deviation);
|
||||
triggerDeviationAlert(deviation);
|
||||
updateDeviationVisualization(deviation);
|
||||
}
|
||||
|
||||
private void triggerDeviationAlert(double deviation) {
|
||||
try {
|
||||
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
|
||||
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
|
||||
if (r != null) r.play();
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Sound failed: " + e.getMessage());
|
||||
}
|
||||
|
||||
Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
|
||||
if (v != null) v.vibrate(500);
|
||||
|
||||
Toast.makeText(this, "Вы отклонились на " + (int) deviation + " м", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
private void updateDeviationVisualization(double deviation) {
|
||||
if (mapView == null) return;
|
||||
List<org.osmdroid.views.overlay.Overlay> overlays = mapView.getOverlays();
|
||||
for (org.osmdroid.views.overlay.Overlay ov : overlays) {
|
||||
if (ov instanceof org.osmdroid.views.overlay.Polyline) {
|
||||
org.osmdroid.views.overlay.Polyline pl = (org.osmdroid.views.overlay.Polyline) ov;
|
||||
if (deviation > MAX_DEVIATION_METERS * 1.5) pl.setColor(0x88FF0000);
|
||||
else if (deviation > MAX_DEVIATION_METERS) pl.setColor(0x88FFFF00);
|
||||
else pl.setColor(0x8800FF00);
|
||||
}
|
||||
}
|
||||
mapView.invalidate();
|
||||
}
|
||||
|
||||
private void navigationComplete() {
|
||||
isNavigationActive = false;
|
||||
stopNavigationLocationUpdates();
|
||||
Toast.makeText(this, "Маршрут завершён!", Toast.LENGTH_LONG).show();
|
||||
// Сброс цвета маршрута
|
||||
if (mapView != null) {
|
||||
for (org.osmdroid.views.overlay.Overlay ov : mapView.getOverlays()) {
|
||||
if (ov instanceof org.osmdroid.views.overlay.Polyline) {
|
||||
((org.osmdroid.views.overlay.Polyline) ov).setColor(0x880000FF);
|
||||
}
|
||||
}
|
||||
mapView.invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void getSettings(View view) {
|
||||
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
|
||||
// ========== SOS и отправка SMS (без изменения логики) ==========
|
||||
public void SOS(View view) {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
!= PackageManager.PERMISSION_GRANTED) {
|
||||
Toast.makeText(this, "Нет разрешения на локацию", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
fusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
|
||||
String message;
|
||||
if (location == null) message = "SOS! Координаты не найдены.";
|
||||
else
|
||||
message = "SOS! Мои координаты: https://maps.google.com/?q=" + location.getLatitude() + "," + location.getLongitude();
|
||||
|
||||
List<Contact> contacts = contactStorage.loadContacts();
|
||||
for (Contact c : contacts) sendSMS(message, c.getNumber());
|
||||
});
|
||||
}
|
||||
|
||||
private void sendSMS(String message, String phoneNumber) {
|
||||
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
|
||||
intent.putExtra("sms_body", message);
|
||||
if (intent.resolveActivity(getPackageManager()) != null) startActivity(intent);
|
||||
else Toast.makeText(this, "Приложение для SMS не найдено", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
// ========== Lifecycle ==========
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
if (mapView != null) mapView.onResume();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
if (mapView != null) mapView.onPause();
|
||||
// Остановим активные запросы локации, чтобы не держать ресурсы
|
||||
stopActiveLocationRequests();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
stopActiveLocationRequests();
|
||||
stopNavigationLocationUpdates();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ORSRequest {
|
||||
@SerializedName("coordinates")
|
||||
List<double[]> coordinates;
|
||||
|
||||
public ORSRequest(List<double[]> coordinates) {
|
||||
this.coordinates = coordinates;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ORSResponse {
|
||||
@SerializedName("features")
|
||||
public List<Feature> features;
|
||||
|
||||
public static class Feature {
|
||||
@SerializedName("geometry")
|
||||
public Geometry geometry;
|
||||
}
|
||||
|
||||
public static class Geometry {
|
||||
@SerializedName("coordinates")
|
||||
public List<List<Double>> coordinates; // [ [lon, lat], [lon, lat], ... ]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Header;
|
||||
import retrofit2.http.POST;
|
||||
import retrofit2.http.Query;
|
||||
|
||||
public interface ORSService {
|
||||
@GET("v2/directions/foot-hiking")
|
||||
Call<ORSResponse> getFootRoute(
|
||||
@Query("api_key") String apiKey,
|
||||
@Query("start") String start, // Формат: "lon,lat"
|
||||
@Query("end") String end // Формат: "lon,lat"
|
||||
);
|
||||
|
||||
@POST("v2/directions/foot-walking/geojson")
|
||||
Call<ORSResponse> getMultiPointRoute(
|
||||
@Header("Authorization") String apiKey,
|
||||
@Body ORSRequest body
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class OSRMRouteResponse {
|
||||
public List<Route> routes;
|
||||
|
||||
public static class Route {
|
||||
public Geometry geometry;
|
||||
public double distance;
|
||||
public double duration;
|
||||
}
|
||||
|
||||
public static class Geometry {
|
||||
public List<List<Double>> coordinates; // [longitude, latitude]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
import retrofit2.http.Query;
|
||||
|
||||
public interface OSRMService {
|
||||
@GET("route/v1/foot/{coordinates}")
|
||||
Call<OSRMRouteResponse> getRoute(
|
||||
@Path("coordinates") String coordinates,
|
||||
@Query("overview") String overview,
|
||||
@Query("geometries") String geometries
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
// http://router.project-osrm.org/route/v1/foot/64.543982,40.574575;64.529667,40.549826
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.location.Location;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.telephony.SmsManager;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
|
||||
import com.google.android.gms.location.FusedLocationProviderClient;
|
||||
import com.google.android.gms.location.LocationCallback;
|
||||
import com.google.android.gms.location.LocationRequest;
|
||||
import com.google.android.gms.location.LocationResult;
|
||||
|
||||
public class SafeRouteService extends Service implements SensorEventListener {
|
||||
private FusedLocationProviderClient locationClient;
|
||||
private LocationRequest locationRequest;
|
||||
private SensorManager sensorManager;
|
||||
private Sensor accelerometer;
|
||||
private Location lastLocation;
|
||||
private long lastMoveTime;
|
||||
private static final long STILL_THRESHOLD = 5 * 60 * 1000;
|
||||
private static final float FALL_THRESHOLD = 30.0f;
|
||||
private com.google.android.gms.location.LocationServices LocationServices;
|
||||
|
||||
@SuppressLint("ForegroundServiceType")
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
initLocation();
|
||||
initSensors();
|
||||
startForeground(1, createNotification());
|
||||
}
|
||||
|
||||
|
||||
private void initLocation() {
|
||||
locationClient = LocationServices.getFusedLocationProviderClient(this);
|
||||
locationRequest = LocationRequest.create()
|
||||
.setInterval(10000)
|
||||
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
|
||||
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
|
||||
// TODO: Consider calling
|
||||
// ActivityCompat#requestPermissions
|
||||
// here to request the missing permissions, and then overriding
|
||||
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
|
||||
// int[] grantResults)
|
||||
// to handle the case where the user grants the permission. See the documentation
|
||||
// for ActivityCompat#requestPermissions for more details.
|
||||
return;
|
||||
}
|
||||
locationClient.requestLocationUpdates(
|
||||
locationRequest,
|
||||
locationCallback,
|
||||
Looper.getMainLooper());
|
||||
}
|
||||
private LocationCallback locationCallback = new LocationCallback() {
|
||||
@Override
|
||||
public void onLocationResult(LocationResult locationResult) {
|
||||
Location current = locationResult.getLastLocation();
|
||||
if (lastLocation != null) {
|
||||
float distance = current.distanceTo(lastLocation);
|
||||
if (distance > 2.0) {
|
||||
lastMoveTime = System.currentTimeMillis();
|
||||
} else {
|
||||
checkStillness();
|
||||
}
|
||||
}
|
||||
lastLocation = current;
|
||||
}
|
||||
};
|
||||
private void checkStillness() {
|
||||
if (System.currentTimeMillis() - lastMoveTime > STILL_THRESHOLD) {
|
||||
sendAlertSMS("Пользователь долго не двигается!");
|
||||
stopSelf(); // Останавливаем после тревоги
|
||||
}
|
||||
}
|
||||
private void initSensors() {
|
||||
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
|
||||
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
|
||||
sensorManager.registerListener(this, accelerometer,
|
||||
SensorManager.SENSOR_DELAY_NORMAL);
|
||||
}
|
||||
@Override
|
||||
public void onSensorChanged(SensorEvent event) {
|
||||
float x = event.values[0];
|
||||
float y = event.values[1];
|
||||
float z = event.values[2];
|
||||
double acceleration = Math.sqrt(x * x + y * y + z * z);
|
||||
if (acceleration > FALL_THRESHOLD) {
|
||||
sendAlertSMS("Зафиксировано падение!");
|
||||
}
|
||||
}
|
||||
private void sendAlertSMS (String reason) {
|
||||
String phone = "+79815540434";
|
||||
String message = "SOS! " + reason + " Мои координаты: " +
|
||||
lastLocation.getLatitude() + ", " + lastLocation.getLongitude();
|
||||
SmsManager smsManager = SmsManager.getDefault();
|
||||
smsManager.sendTextMessage(phone, null, message, null, null);
|
||||
}
|
||||
private Notification createNotification () {
|
||||
NotificationChannel channel = new NotificationChannel(
|
||||
"safe_route",
|
||||
"SafeRoute Active",
|
||||
NotificationManager.IMPORTANCE_LOW);
|
||||
getSystemService(NotificationManager.class).createNotificationChannel(channel);
|
||||
return new Notification.Builder(this, "safe_route")
|
||||
.setContentTitle("SafeRoute запущен")
|
||||
.setContentText("Мы следим за вашей безопасностью")
|
||||
// .setSmallIcon(R.drawable.ic_shield)
|
||||
.build();
|
||||
}
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public void onAccuracyChanged(Sensor sensor, int i) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import com.example.saferoute.contacts.ContactActivity;
|
||||
import com.example.saferoute.places.PlaceActivity;
|
||||
|
||||
public class SettingActivity extends AppCompatActivity {
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_settings);
|
||||
}
|
||||
|
||||
public void getBack(View view) {
|
||||
Intent intent = new Intent(SettingActivity.this, MainActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
public void contacts(View view){
|
||||
Intent intent = new Intent(SettingActivity.this, ContactActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
public void places(View view){
|
||||
Intent intent = new Intent(SettingActivity.this, PlaceActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.saferoute.contacts;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
public class Contact {
|
||||
// private int id;
|
||||
private String name;
|
||||
private String number;
|
||||
public Contact(String name, String number) {
|
||||
this.name = name;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
public void setNumber(String number) {
|
||||
this.number = number;
|
||||
}
|
||||
// public int getId() {
|
||||
// return id;
|
||||
// }
|
||||
// public void setId(int id) {
|
||||
// this.id = id;
|
||||
// }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + " - " + number;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.example.saferoute.contacts;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.text.TextUtils;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ListView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import com.example.saferoute.R;
|
||||
import com.example.saferoute.SettingActivity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ContactActivity extends AppCompatActivity {
|
||||
|
||||
private ListView listView;
|
||||
private EditText inputName;
|
||||
private EditText inputNumber;
|
||||
private Button btnAdd;
|
||||
|
||||
private ContactAdapter adapter;
|
||||
private List<Contact> contacts = new ArrayList<>();
|
||||
private ContactStorage contactStorage;
|
||||
|
||||
// private SharedPreferences sharedPreferences;
|
||||
// private Set<String> names = new HashSet<>();
|
||||
// private String SAVED_NUMBERS = "SAVED_NUMBERS";
|
||||
|
||||
public void getBack2(View view){
|
||||
Intent intent = new Intent(ContactActivity.this, SettingActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
|
||||
@SuppressLint("MissingInflatedId")
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_contact);
|
||||
|
||||
|
||||
// Инициализация View
|
||||
listView = findViewById(R.id.list_contact);
|
||||
inputName = findViewById(R.id.name1);
|
||||
inputNumber = findViewById(R.id.number1);
|
||||
btnAdd = findViewById(R.id.add_contact);
|
||||
|
||||
contactStorage = new ContactStorage(this);
|
||||
|
||||
// Загружаем контакты из памяти
|
||||
contacts = contactStorage.loadContacts();
|
||||
|
||||
// Если контактов нет, добавим тестовые
|
||||
if (contacts.isEmpty()) {
|
||||
// addTestContacts();
|
||||
}
|
||||
|
||||
// Настраиваем адаптер
|
||||
adapter = new ContactAdapter(this, contacts);
|
||||
listView.setAdapter(adapter);
|
||||
|
||||
|
||||
btnAdd.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
addContact();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Обработка нажатия на элемент списка
|
||||
listView.setOnItemClickListener((parent, view, position, id) -> {
|
||||
showDeleteDialog(position);
|
||||
});
|
||||
}
|
||||
|
||||
private void addContact() {
|
||||
String name = inputName.getText().toString().trim();
|
||||
String phone = inputNumber.getText().toString().trim();
|
||||
|
||||
// Валидация полей
|
||||
if (TextUtils.isEmpty(name)) {
|
||||
inputName.setError("Введите имя");
|
||||
inputName.requestFocus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (TextUtils.isEmpty(phone)) {
|
||||
inputNumber.setError("Введите номер телефона");
|
||||
inputNumber.requestFocus();
|
||||
return;
|
||||
}
|
||||
|
||||
// Создаем новый контакт
|
||||
Contact newContact = new Contact(name, phone);
|
||||
|
||||
// Добавляем в список
|
||||
contacts.add(newContact);
|
||||
|
||||
// Сохраняем в SharedPreferences
|
||||
contactStorage.saveContacts(contacts);
|
||||
|
||||
// Обновляем ListView
|
||||
adapter.notifyDataSetChanged();
|
||||
|
||||
// Очищаем поля ввода
|
||||
inputName.setText("");
|
||||
inputNumber.setText("");
|
||||
|
||||
// Прокручиваем ListView к последнему элементу
|
||||
listView.smoothScrollToPosition(contacts.size() - 1);
|
||||
|
||||
Toast.makeText(this, "Контакт добавлен: " + name, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
private void showDeleteDialog(int position) {
|
||||
Contact contact = contacts.get(position);
|
||||
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle("Удаление контакта")
|
||||
.setMessage("Вы уверены, что хотите удалить контакт \"" + contact.getName() + "\"?")
|
||||
.setPositiveButton("ДА", (dialog, which) -> {
|
||||
deleteContact(position);
|
||||
})
|
||||
.setNegativeButton("НЕТ", (dialog, which) -> {
|
||||
dialog.dismiss();
|
||||
})
|
||||
.show();
|
||||
}
|
||||
|
||||
private void deleteContact(int position) {
|
||||
// Удаляем из списка
|
||||
contacts.remove(position);
|
||||
|
||||
// Сохраняем в памяти (SharedPreferences)
|
||||
contactStorage.saveContacts(contacts);
|
||||
|
||||
// Обновляем ListView
|
||||
adapter.notifyDataSetChanged();
|
||||
|
||||
Toast.makeText(this, "Контакт удален", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
private void addTestContacts() {
|
||||
contacts.add(new Contact("Мама", "+79115716167"));
|
||||
contactStorage.saveContacts(contacts);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.example.saferoute.contacts;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.example.saferoute.R;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ContactAdapter extends ArrayAdapter<Contact> {
|
||||
private final Context context;
|
||||
private final List<Contact> contacts;
|
||||
|
||||
public ContactAdapter(@NonNull Context context, List<Contact> contacts) {
|
||||
super(context, R.layout.list_item_contact, contacts);
|
||||
this.context = context;
|
||||
this.contacts = contacts;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
|
||||
if (convertView == null){
|
||||
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_contact, parent, false);
|
||||
}
|
||||
|
||||
Contact contact = contacts.get(position);
|
||||
|
||||
((TextView) convertView.findViewById(R.id.name)).setText(contact.getName());
|
||||
((TextView) convertView.findViewById(R.id.number)).setText(contact.getNumber());
|
||||
return convertView;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.example.saferoute.contacts;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ContactStorage {
|
||||
private static final String PREF_NAME = "contacts_pref";
|
||||
private static final String KEY_CONTACTS = "contacts_list";
|
||||
private final SharedPreferences sharedPreferences;
|
||||
private final Gson gson;
|
||||
|
||||
public ContactStorage(Context context) {
|
||||
sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
|
||||
gson = new Gson();
|
||||
}
|
||||
|
||||
public void saveContacts(List<Contact> contacts) {
|
||||
String json = gson.toJson(contacts);
|
||||
sharedPreferences.edit().putString(KEY_CONTACTS, json).apply();
|
||||
}
|
||||
|
||||
public List<Contact> loadContacts() {
|
||||
String json = sharedPreferences.getString(KEY_CONTACTS, "");
|
||||
if (json.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
Type type = new TypeToken<List<Contact>>() {}.getType();
|
||||
return gson.fromJson(json, type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.location.Address;
|
||||
import android.location.Geocoder;
|
||||
import android.os.Bundle;
|
||||
import android.text.InputType;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ImageButton;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.example.saferoute.R;
|
||||
import com.google.android.gms.location.FusedLocationProviderClient;
|
||||
import com.google.android.gms.location.LocationServices;
|
||||
|
||||
import org.osmdroid.events.MapEventsReceiver;
|
||||
import org.osmdroid.util.GeoPoint;
|
||||
import org.osmdroid.views.MapView;
|
||||
import org.osmdroid.views.overlay.MapEventsOverlay;
|
||||
import org.osmdroid.views.overlay.Marker;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public class LocationPlaceActivity extends AppCompatActivity {
|
||||
|
||||
private MapView map;
|
||||
private Marker selectedMarker;
|
||||
private GeoPoint selectedPoint;
|
||||
private Button btnConfirm;
|
||||
private EditText etSearch;
|
||||
private ImageButton btnSearch;
|
||||
|
||||
private boolean hasSelectedLocation = false;
|
||||
private String pickedLocationName;
|
||||
|
||||
private double lat, lon;
|
||||
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_location_picker);
|
||||
|
||||
map = findViewById(R.id.map_picker);
|
||||
btnConfirm = findViewById(R.id.btnConfirmLocation);
|
||||
etSearch = findViewById(R.id.etSearchAddress);
|
||||
btnSearch = findViewById(R.id.btnSearch);
|
||||
|
||||
// Слушатель кнопки поиска
|
||||
btnSearch.setOnClickListener(v -> {
|
||||
String addressString = etSearch.getText().toString();
|
||||
if (!addressString.isEmpty()) {
|
||||
searchAddress(addressString);
|
||||
}
|
||||
});
|
||||
|
||||
// Стандартная настройка карты
|
||||
map.setMultiTouchControls(true);
|
||||
map.getController().setZoom(15.0);
|
||||
|
||||
|
||||
/* >> */
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
|
||||
// Эта проверка на случай, если метод вызван без разрешений (например, onRequestPermissionsResult отказал)
|
||||
return;
|
||||
}
|
||||
|
||||
// Попытка получить последнюю известную локацию (из кэша)
|
||||
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);;
|
||||
fusedLocationClient.getLastLocation()
|
||||
.addOnSuccessListener(this, location -> {
|
||||
if (location != null) {
|
||||
lat = location.getLatitude();
|
||||
lon = location.getLongitude();
|
||||
Log.e("LOCATION_TEST", "Найден getLastLocation: " + lat + " : " + lon);
|
||||
// Центрируем где-нибудь (или на текущей позиции)
|
||||
// map.getController().setCenter(new GeoPoint(64.5540, 40.5746));
|
||||
map.getController().setCenter(new GeoPoint(lat, lon));
|
||||
}
|
||||
})
|
||||
.addOnFailureListener(this, e -> {
|
||||
Log.e("LOCATION_TEST", "Ошибка getLastLocation: " + e.getMessage());
|
||||
// Если ошибка, тоже пытаемся запросить текущую
|
||||
});
|
||||
|
||||
/* << */
|
||||
|
||||
|
||||
|
||||
map.getController().setCenter(new GeoPoint(lat, lon));
|
||||
|
||||
// 1. Создаем обработчик нажатий
|
||||
MapEventsReceiver mReceive = new MapEventsReceiver() {
|
||||
@Override
|
||||
public boolean singleTapConfirmedHelper(GeoPoint p) {
|
||||
// Вызывается при обычном тапе по карте
|
||||
updateMarker(p);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean longPressHelper(GeoPoint p) {
|
||||
// Вызывается при долгом нажатии (можно оставить пустым)
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Добавляем слой событий на карту
|
||||
MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(mReceive);
|
||||
map.getOverlays().add(0, mapEventsOverlay); // Добавляем самым первым слоем
|
||||
|
||||
// Кнопка подтверждения
|
||||
btnConfirm.setOnClickListener(v -> {
|
||||
if (selectedPoint != null) {
|
||||
showNameInputDialog();
|
||||
|
||||
// if (hasSelectedLocation) {
|
||||
// // Возвращаем координаты в предыдущее Activity
|
||||
// Intent resultIntent = new Intent();
|
||||
// resultIntent.putExtra("place", pickedLocationName);
|
||||
// resultIntent.putExtra("lat", selectedPoint.getLatitude());
|
||||
// resultIntent.putExtra("lon", selectedPoint.getLongitude());
|
||||
// setResult(RESULT_OK, resultIntent);
|
||||
// finish();
|
||||
// }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void updateMarker(GeoPoint p) {
|
||||
selectedPoint = p;
|
||||
|
||||
// Если маркер уже был, просто двигаем его
|
||||
if (selectedMarker == null) {
|
||||
selectedMarker = new Marker(map);
|
||||
selectedMarker.setTitle("Выбранное место");
|
||||
map.getOverlays().add(selectedMarker);
|
||||
}
|
||||
|
||||
selectedMarker.setPosition(p);
|
||||
map.invalidate(); // Перерисовать карту
|
||||
|
||||
// Показываем кнопку подтверждения
|
||||
btnConfirm.setVisibility(View.VISIBLE);
|
||||
btnConfirm.setText("Выбрать: " + String.format("%.4f", p.getLatitude()) + ", " + String.format("%.4f", p.getLongitude()));
|
||||
}
|
||||
private void searchAddress(String addressString) {
|
||||
// Geocoder работает через интернет, поэтому в идеале его
|
||||
// нужно вызывать в фоновом потоке, но для простоты используем текущий
|
||||
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
|
||||
try {
|
||||
List<Address> addresses = geocoder.getFromLocationName(addressString, 1);
|
||||
|
||||
if (addresses != null && !addresses.isEmpty()) {
|
||||
Address address = addresses.get(0);
|
||||
GeoPoint foundPoint = new GeoPoint(address.getLatitude(), address.getLongitude());
|
||||
|
||||
// 1. Центрируем карту на найденном месте
|
||||
map.getController().animateTo(foundPoint);
|
||||
map.getController().setZoom(17.0);
|
||||
|
||||
// 2. Ставим маркер
|
||||
updateMarker(foundPoint);
|
||||
|
||||
Toast.makeText(this, "Найдено: " + address.getAddressLine(0), Toast.LENGTH_SHORT).show();
|
||||
} else {
|
||||
Toast.makeText(this, "Адрес не найден", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
Toast.makeText(this, "Ошибка сети при поиске", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void showNameInputDialog() {
|
||||
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(this);
|
||||
builder.setTitle("Новая локация");
|
||||
builder.setMessage("Введите название для этого места (например: Дом, Работа, Дача):");
|
||||
|
||||
// Создаем EditText для ввода текста программно
|
||||
final EditText input = new EditText(this);
|
||||
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); // Текст с большой буквы
|
||||
input.setHint("Название места");
|
||||
|
||||
// Добавляем отступы вокруг поля ввода, чтобы оно смотрелось аккуратно
|
||||
FrameLayout container = new FrameLayout(this);
|
||||
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.WRAP_CONTENT
|
||||
);
|
||||
// Конвертируем 16dp в пиксели для отступов
|
||||
int marginInPx = (int) (16 * getResources().getDisplayMetrics().density);
|
||||
params.leftMargin = marginInPx;
|
||||
params.rightMargin = marginInPx;
|
||||
input.setLayoutParams(params);
|
||||
container.addView(input);
|
||||
|
||||
builder.setView(container);
|
||||
|
||||
// Кнопка "Сохранить"
|
||||
builder.setPositiveButton("Сохранить", (dialog, which) -> {
|
||||
String name = input.getText().toString().trim();
|
||||
if (name.isEmpty()) {
|
||||
// Если ввели пустоту, даем дефолтное имя
|
||||
this.pickedLocationName = "Моя локация";
|
||||
} else {
|
||||
this.pickedLocationName = name;
|
||||
}
|
||||
// Возвращаем координаты в предыдущее Activity
|
||||
Intent resultIntent = new Intent();
|
||||
// String.format("%.4f", selectedPoint.getLatitude()) + ", " + String.format("%.4f", p.getLongitude())
|
||||
resultIntent.putExtra("place", pickedLocationName);
|
||||
resultIntent.putExtra("lat", selectedPoint.getLatitude());
|
||||
resultIntent.putExtra("lon", selectedPoint.getLongitude());
|
||||
setResult(RESULT_OK, resultIntent);
|
||||
finish();
|
||||
|
||||
});
|
||||
|
||||
// Кнопка "Отмена"
|
||||
builder.setNegativeButton("Отмена", (dialog, which) -> {
|
||||
dialog.cancel();
|
||||
Toast.makeText(this, "Выбор названия отменен", Toast.LENGTH_SHORT).show();
|
||||
});
|
||||
|
||||
// Показываем окно
|
||||
builder.show();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
import static java.lang.Character.getType;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Bundle;
|
||||
import android.text.InputType;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.example.saferoute.ORSRequest;
|
||||
import com.example.saferoute.ORSResponse;
|
||||
import com.example.saferoute.ORSService;
|
||||
import com.example.saferoute.R;
|
||||
import com.google.android.gms.location.FusedLocationProviderClient;
|
||||
import com.google.android.gms.location.LocationServices;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import org.osmdroid.events.MapEventsReceiver;
|
||||
import org.osmdroid.util.GeoPoint;
|
||||
import org.osmdroid.views.MapView;
|
||||
import org.osmdroid.views.overlay.MapEventsOverlay;
|
||||
import org.osmdroid.views.overlay.Marker;
|
||||
import org.osmdroid.views.overlay.Overlay;
|
||||
import org.osmdroid.views.overlay.Polyline;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class LocationRouteActivity extends AppCompatActivity {
|
||||
|
||||
private MapView map;
|
||||
private Marker selectedMarker;
|
||||
|
||||
private boolean hasSelectedLocation = false;
|
||||
private String pickedLocationName;
|
||||
|
||||
private double lat, lon;
|
||||
|
||||
|
||||
private List<GeoPoint> waypoints = new ArrayList<>(); // Список выбранных точек
|
||||
private boolean isSelectedRoute = false; // Флаг: построен маршрут или нет
|
||||
private boolean isSelectionMode = false; // Флаг: ставим мы точки или нет
|
||||
private Button btnStartSelection, btnBuildRoute;
|
||||
private Button btnConfirm;
|
||||
|
||||
|
||||
private static final String ROUTES_FILE = "routes.json";
|
||||
private Gson gson = new Gson();
|
||||
|
||||
// Список точек окончательного проложенного маршрута (заполняется в drawRoute)
|
||||
private List<GeoPoint> lastRoutePoints = new ArrayList<>();
|
||||
|
||||
// Executor для фоновых записей/чтения
|
||||
private final java.util.concurrent.Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
|
||||
// Вложенные классы для сериализации маршрутов в routes.json
|
||||
private static class SavedPoint {
|
||||
double lat;
|
||||
double lon;
|
||||
SavedPoint() {}
|
||||
SavedPoint(double lat, double lon) { this.lat = lat; this.lon = lon; }
|
||||
}
|
||||
|
||||
private static class SavedRoute {
|
||||
long id;
|
||||
String title;
|
||||
List<SavedPoint> points;
|
||||
long createdAt;
|
||||
SavedRoute() {}
|
||||
SavedRoute(String title, List<SavedPoint> points) {
|
||||
this.id = System.currentTimeMillis();
|
||||
this.title = title;
|
||||
this.points = points;
|
||||
this.createdAt = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_location_pickers);
|
||||
|
||||
map = findViewById(R.id.map_picker);
|
||||
btnConfirm = findViewById(R.id.btnConfirmLocationRoute);
|
||||
btnStartSelection = findViewById(R.id.btnStartSelection);
|
||||
btnBuildRoute = findViewById(R.id.btnBuildRoute);
|
||||
|
||||
|
||||
// Создаем приемник событий
|
||||
MapEventsReceiver mReceive = new MapEventsReceiver() {
|
||||
@Override
|
||||
public boolean singleTapConfirmedHelper(GeoPoint p) {
|
||||
if (isSelectionMode) {
|
||||
Log.d("MAP_TAP", "Нажата точка: " + p.getLatitude() + ", " + p.getLongitude());
|
||||
addWaypoint(p); // Добавляем точку
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean longPressHelper(GeoPoint p) { return false; }
|
||||
};
|
||||
|
||||
// Добавляем его в самый конец списка оверлеев
|
||||
MapEventsOverlay eventsOverlay = new MapEventsOverlay(mReceive);
|
||||
map.getOverlays().add(eventsOverlay);
|
||||
|
||||
|
||||
|
||||
////////===============
|
||||
// Стандартная настройка карты
|
||||
map.setMultiTouchControls(true);
|
||||
map.getController().setZoom(15.0);
|
||||
|
||||
|
||||
/* >> */
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
|
||||
// Эта проверка на случай, если метод вызван без разрешений (например, onRequestPermissionsResult отказал)
|
||||
return;
|
||||
}
|
||||
|
||||
// Попытка получить последнюю известную локацию (из кэша)
|
||||
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
|
||||
fusedLocationClient.getLastLocation()
|
||||
.addOnSuccessListener(this, location -> {
|
||||
if (location != null) {
|
||||
lat = location.getLatitude();
|
||||
lon = location.getLongitude();
|
||||
Log.e("LOCATION_TEST", "Найден getLastLocation: " + lat + " : " + lon);
|
||||
// Центрируем где-нибудь (или на текущей позиции)
|
||||
// map.getController().setCenter(new GeoPoint(64.5540, 40.5746));
|
||||
map.getController().setCenter(new GeoPoint(lat, lon));
|
||||
}
|
||||
})
|
||||
.addOnFailureListener(this, e -> {
|
||||
Log.e("LOCATION_TEST", "Ошибка getLastLocation: " + e.getMessage());
|
||||
// Если ошибка, тоже пытаемся запросить текущую
|
||||
});
|
||||
|
||||
|
||||
btnStartSelection.setOnClickListener(v -> {
|
||||
isSelectedRoute = false;
|
||||
isSelectionMode = true;
|
||||
waypoints.clear();
|
||||
|
||||
// Вместо clear() удаляем только маркеры и старые пути
|
||||
// Проходим циклом с конца, чтобы безопасно удалять
|
||||
Iterator<Overlay> it = map.getOverlays().iterator();
|
||||
while (it.hasNext()) {
|
||||
Overlay overlay = it.next();
|
||||
if (overlay instanceof Marker || overlay instanceof Polyline) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
map.invalidate(); // Обновить карту
|
||||
Toast.makeText(this, "Режим выбора: ставьте точки на карте", Toast.LENGTH_SHORT).show();
|
||||
});
|
||||
|
||||
|
||||
|
||||
// Когда пользователь нажал «Построить маршрут»:
|
||||
btnBuildRoute.setOnClickListener(v -> {
|
||||
if (waypoints.size() < 2) {
|
||||
Toast.makeText(this, "Нужно минимум 2 точки", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
isSelectionMode = false; // Выключаем режим выбора
|
||||
buildRoute();
|
||||
});
|
||||
|
||||
|
||||
// Кнопка подтверждения
|
||||
btnConfirm.setOnClickListener(v -> {
|
||||
if (isSelectedRoute) {
|
||||
Toast.makeText(this, "ПУТЬ ЕСТЬ", Toast.LENGTH_SHORT).show();
|
||||
showNameInputDialog();
|
||||
}else
|
||||
Toast.makeText(this, "ПУТи нет", Toast.LENGTH_SHORT).show();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void buildRoute() {
|
||||
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl("https://api.openrouteservice.org/") // НОВЫЙ URL
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build();
|
||||
|
||||
ORSService service = retrofit.create(ORSService.class);
|
||||
|
||||
// Преобразуем List<GeoPoint> в формат для API [[lon, lat], [lon, lat], ...]
|
||||
List<double[]> coordsForApi = new ArrayList<>();
|
||||
for (GeoPoint p : waypoints) {
|
||||
coordsForApi.add(new double[]{p.getLongitude(), p.getLatitude()});
|
||||
}
|
||||
|
||||
ORSRequest requestBody = new ORSRequest(coordsForApi);
|
||||
String apiKey = "eyJvcmciOiI1YjNjZTM1OTc4NTExMTAwMDFjZjYyNDgiLCJpZCI6IjVhNDU5MGQxOTNjNzQxYTNhOTA4MDY5Nzg4ZWUxMDM1IiwiaCI6Im11cm11cjY0In0=";
|
||||
|
||||
service.getMultiPointRoute(apiKey, requestBody).enqueue(new Callback<ORSResponse>() {
|
||||
@Override
|
||||
public void onResponse(Call<ORSResponse> call, Response<ORSResponse> response) {
|
||||
if (response.isSuccessful() && response.body() != null) {
|
||||
|
||||
|
||||
|
||||
// Получаем «сырые» координаты пути от ORS [[lon, lat], [lon, lat], ...]
|
||||
List<List<Double>> rawCoords = response.body().features.get(0).geometry.coordinates;
|
||||
|
||||
// Конвертируем их в List<GeoPoint>
|
||||
List<GeoPoint> routePoints = new ArrayList<>();
|
||||
for (List<Double> coord : rawCoords) {
|
||||
// Важно: ORS возвращает [Lon, Lat], а GeoPoint создается как (Lat, Lon)
|
||||
double lon = coord.get(0);
|
||||
double lat = coord.get(1);
|
||||
routePoints.add(new GeoPoint(lat, lon));
|
||||
}
|
||||
|
||||
// Передаем готовый список в ваш метод отрисовки
|
||||
drawRoute(routePoints);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<ORSResponse> call, Throwable t) {
|
||||
Log.e("API", "Ошибка: " + t.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void addWaypoint(GeoPoint p) {
|
||||
waypoints.add(p);
|
||||
Log.d("WAYPOINTS", "Количество точек: " + waypoints.size());
|
||||
|
||||
Marker marker = new Marker(map);
|
||||
marker.setPosition(p);
|
||||
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
|
||||
marker.setTitle("Точка " + waypoints.size());
|
||||
|
||||
map.getOverlays().add(marker);
|
||||
map.invalidate(); // Обязательно! Без этого маркер не появится сразу
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void drawRoute(List<GeoPoint> points) {
|
||||
if (points == null || points.isEmpty()) return;
|
||||
|
||||
// Сохраняем, что это текущий показанный маршрут
|
||||
lastRoutePoints = new ArrayList<>(points);
|
||||
|
||||
// третья версия
|
||||
// Удаляем старые Polyline-ы безопасно (итерация с конца)
|
||||
for (int i = map.getOverlays().size() - 1; i >= 0; i--) {
|
||||
org.osmdroid.views.overlay.Overlay ov = map.getOverlays().get(i);
|
||||
if (ov instanceof org.osmdroid.views.overlay.Polyline) {
|
||||
map.getOverlays().remove(i);
|
||||
}
|
||||
}
|
||||
|
||||
org.osmdroid.views.overlay.Polyline polyline = new org.osmdroid.views.overlay.Polyline();
|
||||
polyline.setPoints(points);
|
||||
polyline.setColor(0x880000FF); // Полупрозрачный синий
|
||||
polyline.setWidth(10f);
|
||||
|
||||
|
||||
map.getOverlays().add(polyline);
|
||||
map.invalidate(); // Перерисовываем карту
|
||||
|
||||
// Автоматически центрируем и масштабируем карту под маршрут
|
||||
try {
|
||||
map.zoomToBoundingBox(polyline.getBounds(), false);
|
||||
} catch (Exception e) {
|
||||
Log.w("DRAW_ROUTE", "Не удалось масштабировать bounding box: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Показываем кнопку подтверждения
|
||||
btnConfirm.setVisibility(View.VISIBLE);
|
||||
btnConfirm.setText("Сохранить путь?");
|
||||
isSelectedRoute = true;
|
||||
}
|
||||
|
||||
|
||||
private void showNameInputDialog() {
|
||||
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(this);
|
||||
builder.setTitle("Новый путь");
|
||||
builder.setMessage("Введите название для этого пути (например: Дом - Школа):");
|
||||
|
||||
// Создаем EditText для ввода текста программно
|
||||
final EditText input = new EditText(this);
|
||||
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); // Текст с большой буквы
|
||||
input.setHint("Название пути");
|
||||
|
||||
// Добавляем отступы вокруг поля ввода, чтобы оно смотрелось аккуратно
|
||||
FrameLayout container = new FrameLayout(this);
|
||||
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.WRAP_CONTENT
|
||||
);
|
||||
// Конвертируем 16dp в пиксели для отступов
|
||||
int marginInPx = (int) (16 * getResources().getDisplayMetrics().density);
|
||||
params.leftMargin = marginInPx;
|
||||
params.rightMargin = marginInPx;
|
||||
input.setLayoutParams(params);
|
||||
container.addView(input);
|
||||
|
||||
builder.setView(container);
|
||||
|
||||
// Кнопка "Сохранить"
|
||||
builder.setPositiveButton("Сохранить", (dialog, which) -> {
|
||||
String name = input.getText().toString().trim();
|
||||
if (name.isEmpty()) {
|
||||
name = "Мой путь";
|
||||
}
|
||||
// Проверки: есть ли что сохранять
|
||||
if (lastRoutePoints == null || lastRoutePoints.isEmpty()) {
|
||||
Toast.makeText(this, "Нет маршрута для сохранения", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
// Конвертируем GeoPoint -> SavedPoint
|
||||
List<SavedPoint> pts = new ArrayList<>();
|
||||
for (GeoPoint gp : lastRoutePoints) {
|
||||
pts.add(new SavedPoint(gp.getLatitude(), gp.getLongitude()));
|
||||
}
|
||||
|
||||
// Создаём объект маршрута
|
||||
SavedRoute newRoute = new SavedRoute(name, pts);
|
||||
|
||||
// Загружаем текущие маршруты, добавляем новый в начало и сохраняем в фоне
|
||||
executor.execute(() -> {
|
||||
List<SavedRoute> existing = loadSavedRoutesSync();
|
||||
// добавим в начало (последние сверху)
|
||||
existing.add(0, newRoute);
|
||||
// Сохраняем (сюда можно вызвать saveRoutesAsync, но мы в executor уже)
|
||||
try (java.io.FileOutputStream fos = openFileOutput(ROUTES_FILE, MODE_PRIVATE)) {
|
||||
String json = gson.toJson(existing);
|
||||
fos.write(json.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
Log.e("RouteSave", "Ошибка сохранения маршрута: " + e.getMessage());
|
||||
}
|
||||
|
||||
// После успешной записи вернёмся в UI-потоке
|
||||
runOnUiThread(() -> {
|
||||
// Вернём json нового маршрута (или просто сигнал)
|
||||
Intent resultIntent = new Intent();
|
||||
resultIntent.putExtra("route_json", gson.toJson(newRoute));
|
||||
setResult(RESULT_OK, resultIntent);
|
||||
Toast.makeText(LocationRouteActivity.this, "Маршрут сохранён", Toast.LENGTH_SHORT).show();
|
||||
finish();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// Кнопка "Отмена"
|
||||
builder.setNegativeButton("Отмена", (dialog, which) -> {
|
||||
dialog.cancel();
|
||||
Toast.makeText(this, "Выбор названия отменен", Toast.LENGTH_SHORT).show();
|
||||
});
|
||||
|
||||
// Показываем окно
|
||||
builder.show();
|
||||
}
|
||||
|
||||
// Синхронная загрузка существующих маршрутов из файла
|
||||
private List<SavedRoute> loadSavedRoutesSync() {
|
||||
List<SavedRoute> res = new ArrayList<>();
|
||||
try (java.io.FileInputStream fis = openFileInput(ROUTES_FILE)) {
|
||||
byte[] bytes = new byte[fis.available()];
|
||||
fis.read(bytes);
|
||||
String json = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
|
||||
java.lang.reflect.Type t = new com.google.gson.reflect.TypeToken<List<SavedRoute>>(){}.getType();
|
||||
List<SavedRoute> loaded = gson.fromJson(json, t);
|
||||
if (loaded != null) res = loaded;
|
||||
} catch (Exception e) {
|
||||
// файл может отсутствовать — возвращаем пустой список
|
||||
Log.d("RouteSave", "routes file not found or error: " + e.getMessage());
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// Асинхронная запись списка маршрутов в файл
|
||||
private void saveRoutesAsync(List<SavedRoute> routes, Runnable onDone) {
|
||||
executor.execute(() -> {
|
||||
try (java.io.FileOutputStream fos = openFileOutput(ROUTES_FILE, MODE_PRIVATE)) {
|
||||
String json = gson.toJson(routes);
|
||||
fos.write(json.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
Log.e("RouteSave", "saveRoutesAsync failed: " + e.getMessage());
|
||||
}
|
||||
// вызвать onDone на UI-потоке, если нужно
|
||||
if (onDone != null) {
|
||||
runOnUiThread(onDone);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
public class Place {
|
||||
int id;
|
||||
String title;
|
||||
String address;
|
||||
double latitude;
|
||||
double longitude;
|
||||
|
||||
public Place(String title, double latitude, double longitude) {
|
||||
this.title = title;
|
||||
this.address = address;
|
||||
this.latitude = latitude;
|
||||
this.longitude = longitude;
|
||||
}
|
||||
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public double getLatitude() {
|
||||
return latitude;
|
||||
}
|
||||
|
||||
public double getLongitude() {
|
||||
return longitude;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.text.InputType;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ListView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.activity.result.ActivityResultLauncher;
|
||||
import androidx.activity.result.contract.ActivityResultContracts;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import com.example.saferoute.R;
|
||||
import com.example.saferoute.SettingActivity;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PlaceActivity extends AppCompatActivity {
|
||||
|
||||
private Button btnAddPlace, btnAddRoute;
|
||||
|
||||
private PlaceStorage placesStorage;
|
||||
private PlaceAdapter placesAdapter;
|
||||
private ListView lvPlaces;
|
||||
private List<Place> places= new ArrayList<>();
|
||||
|
||||
private RouteStorage routeStorage;
|
||||
// private RoutesListAdapter routesAdapter;
|
||||
private RouteAdapter routesAdapter;
|
||||
private ListView lvRoutes;
|
||||
private List<Route> routes = new ArrayList<>();
|
||||
|
||||
private Gson gson = new Gson();
|
||||
private static final String ROUTES_FILE = "routes.json";
|
||||
|
||||
String pickedLocationName = ""; // Переменная для хранения имени локации
|
||||
private boolean hasSelectedLocation = false;
|
||||
|
||||
public void getBack3(View view){
|
||||
Intent intent = new Intent(PlaceActivity.this, SettingActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
|
||||
@SuppressLint("MissingInflatedId")
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_place);
|
||||
|
||||
|
||||
lvPlaces = findViewById(R.id.lvPlaces);
|
||||
lvRoutes = findViewById(R.id.lvRoutes);
|
||||
btnAddPlace = findViewById(R.id.btnAddPlace);
|
||||
btnAddRoute = findViewById(R.id.btnAddRoute);
|
||||
|
||||
|
||||
placesStorage = new PlaceStorage(this);
|
||||
routeStorage = new RouteStorage(this);
|
||||
|
||||
places = placesStorage.loadPlaces();
|
||||
if (places.isEmpty()) {
|
||||
// addTestContacts();
|
||||
}
|
||||
|
||||
placesAdapter = new PlaceAdapter(this, places);
|
||||
lvPlaces.setAdapter(placesAdapter);
|
||||
|
||||
// routesAdapter = new RoutesListAdapter(this);
|
||||
routesAdapter = new RouteAdapter(this, routes);
|
||||
lvRoutes.setAdapter(routesAdapter);
|
||||
|
||||
|
||||
// Обработчики действий адаптера
|
||||
// routesAdapter.setOnActionListener(new RoutesListAdapter.OnActionListener() {
|
||||
// @Override
|
||||
// public void onUse(RouteModel route) {
|
||||
// sendRouteToMain(route);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void onShow(RouteModel route) {
|
||||
// // тут можно отправить Intent в Activity-карту показа маршрута,
|
||||
// // или просто центрировать карту в Activity с картой, если она есть
|
||||
// // пример: открыть Activity карты и передать маршрут (json)
|
||||
// openMapWithRoute(route);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void onDelete(RouteModel route) {
|
||||
// confirmAndDeleteRoute(route);
|
||||
// }
|
||||
// });
|
||||
|
||||
// Загрузка маршрутов из файла
|
||||
routeStorage.loadRoutesAsync(list -> {
|
||||
routes = list;
|
||||
routesAdapter.setItems(routes);
|
||||
});
|
||||
|
||||
|
||||
// Получение широты и долготы через карту
|
||||
btnAddPlace.setOnClickListener(v -> {
|
||||
// 2. Запускаем выбор локации
|
||||
Intent intent = new Intent(this, LocationPlaceActivity.class);
|
||||
locationPlaceLauncher.launch(intent);
|
||||
});
|
||||
|
||||
// Получение пути через карту
|
||||
btnAddRoute.setOnClickListener(v -> {
|
||||
// 2. Запускаем выбор локации
|
||||
Intent intent = new Intent(this, LocationRouteActivity.class);
|
||||
locationRouteLauncher.launch(intent);
|
||||
});
|
||||
|
||||
lvPlaces.setOnItemClickListener((parent, view, position, id) -> {
|
||||
showDeletePlaceDialog(position);
|
||||
});
|
||||
|
||||
lvRoutes.setOnItemClickListener((parent, view, position, id) -> {
|
||||
showDeleteRouteDialog(position);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
// если есть готовый маршрут (например, вернулся из Activity создания пути):
|
||||
private void addRoute(Route route) {
|
||||
if (route == null) return;
|
||||
// добавить в список и сохранить
|
||||
routes.add(0, route); // вставляем в начало
|
||||
routesAdapter.setItems(routes);
|
||||
routeStorage.saveRoutesAsync(routes);
|
||||
}
|
||||
|
||||
|
||||
private void deleteRoute(Route route) {
|
||||
routes.remove(route);
|
||||
routesAdapter.setItems(routes);
|
||||
routeStorage.saveRoutesAsync(routes);
|
||||
Toast.makeText(this, "Путь удален!", Toast.LENGTH_SHORT).show();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void showDeletePlaceDialog(int position) {
|
||||
Place place = places.get(position);
|
||||
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle("Удаление места")
|
||||
.setMessage("Вы уверены, что хотите удалить место? \"" + place.getTitle() + "\"?")
|
||||
.setPositiveButton("ДА", (dialog, which) -> {
|
||||
deletePlace(position);
|
||||
})
|
||||
.setNegativeButton("НЕТ", (dialog, which) -> {
|
||||
dialog.dismiss();
|
||||
})
|
||||
.show();
|
||||
}
|
||||
|
||||
private void showDeleteRouteDialog(int position) {
|
||||
Route route = routes.get(position);
|
||||
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle("Удаление пути")
|
||||
.setMessage("Вы уверены, что хотите удалить путь? \"" + route.getTitle() + "\"?")
|
||||
.setPositiveButton("ДА", (dialog, which) -> {
|
||||
// deleteRoute(position);
|
||||
deleteRoute(route);
|
||||
})
|
||||
.setNegativeButton("НЕТ", (dialog, which) -> {
|
||||
dialog.dismiss();
|
||||
})
|
||||
.show();
|
||||
}
|
||||
|
||||
|
||||
private void addPlace(String place, double lat, double lon) {
|
||||
|
||||
Place newPlace = new Place(place, lat, lon);
|
||||
places.add(newPlace);
|
||||
placesStorage.savePlaces(places);
|
||||
|
||||
placesAdapter.notifyDataSetChanged();
|
||||
|
||||
lvPlaces.smoothScrollToPosition(places.size() - 1);
|
||||
|
||||
}
|
||||
|
||||
private void deletePlace(int position) {
|
||||
// Удаляем из списка
|
||||
places.remove(position);
|
||||
|
||||
// Сохраняем в памяти (SharedPreferences)
|
||||
placesStorage.savePlaces(places);
|
||||
|
||||
// Обновляем ListView
|
||||
placesAdapter.notifyDataSetChanged();
|
||||
|
||||
Toast.makeText(this, "Место удалено!", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
private void deleteRoute(int position) {
|
||||
// Удаляем из списка
|
||||
routes.remove(position);
|
||||
|
||||
// Сохраняем в памяти (SharedPreferences)
|
||||
// routeStorage.saveRoutes(places);
|
||||
|
||||
// Обновляем ListView
|
||||
// routeAdapter.notifyDataSetChanged();
|
||||
|
||||
Toast.makeText(this, "Путь удален!", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
private void addTestContacts() {
|
||||
|
||||
places.add(new Place("Дом", 64.543982, 40.574575));
|
||||
places.add(new Place("Школа", 64.529667, 40.549826));
|
||||
places.add(new Place("Больница", 64.532115, 40.552135));
|
||||
placesStorage.savePlaces(places);
|
||||
}
|
||||
|
||||
|
||||
// 1. Регистрируем слушатель результата 1 кнопки
|
||||
ActivityResultLauncher<Intent> locationPlaceLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(),
|
||||
result -> {
|
||||
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
|
||||
String place = result.getData().getStringExtra("place");
|
||||
double lat = result.getData().getDoubleExtra("lat", 0);
|
||||
double lon = result.getData().getDoubleExtra("lon", 0);
|
||||
|
||||
// ЗАПИСЫВАЕМ:
|
||||
// this.hasSelectedLocation = true; // Теперь мы знаем, что точка выбрана
|
||||
// Запускаем показ всплывающего окошка для ввода названия!
|
||||
// showNameInputDialog();
|
||||
addPlace(place, lat, lon);
|
||||
|
||||
Toast.makeText(this, "Выбрано: " + lat + ", " + lon, Toast.LENGTH_SHORT).show();
|
||||
// Сохраните эти координаты или отправьте по СМС
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// 1. Регистрируем слушатель результата 2 кнопки
|
||||
ActivityResultLauncher<Intent> locationRouteLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(),
|
||||
result -> {
|
||||
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
|
||||
// здесь должно быть получение результата и добавление
|
||||
|
||||
String routeJson = result.getData().getStringExtra("route_json");
|
||||
if (routeJson != null) {
|
||||
// можно вставить в адаптер сразу:
|
||||
Route route = new Gson().fromJson(routeJson, Route.class);
|
||||
// добавить в локальный список и обновить ListView
|
||||
addRoute(route);
|
||||
Toast.makeText(this, "Путь добавлен: " + route.title, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.example.saferoute.R;
|
||||
import com.example.saferoute.contacts.Contact;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PlaceAdapter extends ArrayAdapter<Place> {
|
||||
private final Context context;
|
||||
private final List<Place> places;
|
||||
|
||||
public PlaceAdapter(@NonNull Context context, List<Place> places) {
|
||||
super(context, R.layout.list_item_place, places);
|
||||
this.context = context;
|
||||
this.places = places;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
|
||||
if (convertView == null){
|
||||
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_place, parent, false);
|
||||
}
|
||||
|
||||
Place place = places.get(position);
|
||||
|
||||
((TextView) convertView.findViewById(R.id.title)).setText(place.getTitle());
|
||||
((TextView) convertView.findViewById(R.id.lat)).setText(String.format("Lat: %.4f", place.getLatitude()));
|
||||
((TextView) convertView.findViewById(R.id.lon)).setText(String.format("Lon: %.4f", place.getLongitude()));
|
||||
return convertView;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import com.example.saferoute.contacts.Contact;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PlaceStorage {
|
||||
private static final String PREF_NAME = "places_pref";
|
||||
private static final String KEY_PLACES = "places_list";
|
||||
private final SharedPreferences sharedPreferences;
|
||||
private final Gson gson;
|
||||
|
||||
public PlaceStorage(Context context) {
|
||||
sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
|
||||
gson = new Gson();
|
||||
}
|
||||
|
||||
public void savePlaces(List<Place> places) {
|
||||
String json = gson.toJson(places);
|
||||
sharedPreferences.edit().putString(KEY_PLACES, json).apply();
|
||||
}
|
||||
|
||||
public List<Place> loadPlaces() {
|
||||
String json = sharedPreferences.getString(KEY_PLACES, "");
|
||||
if (json.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
Type type = new TypeToken<List<Place>>() {}.getType();
|
||||
return gson.fromJson(json, type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
public class Point {
|
||||
|
||||
public double lat;
|
||||
public double lon;
|
||||
|
||||
public Point() {}
|
||||
|
||||
public Point(double lat, double lon) { this.lat = lat; this.lon = lon; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
String s1 = String.format("%.4f", lat);
|
||||
String s2 = String.format("%.4f", lon);
|
||||
return "Lat=" + s1 + "; Lon=" + s2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Route {
|
||||
|
||||
public long id; // можно генерировать timestamp
|
||||
public String title;
|
||||
public List<Point> points;
|
||||
public long createdAt;
|
||||
|
||||
public Route() {
|
||||
}
|
||||
|
||||
public Route(String title, List<Point> points) {
|
||||
this.id = System.currentTimeMillis();
|
||||
this.title = title;
|
||||
this.points = points;
|
||||
this.createdAt = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public List<Point> getPoints() {
|
||||
return points;
|
||||
}
|
||||
|
||||
public String[] getInfo() {
|
||||
if (points != null && points.size() != 0) {
|
||||
String s1 = points.get(0).toString();
|
||||
String s2 = points.get(points.size() - 1).toString();
|
||||
|
||||
return new String[]{s1, s2};
|
||||
} else return new String[]{"нет информации", "нет информации"};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.example.saferoute.R;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class RouteAdapter extends ArrayAdapter<Route> {
|
||||
private final Context context;
|
||||
private final List<Route> routes;
|
||||
|
||||
public RouteAdapter(@NonNull Context context, List<Route> routes) {
|
||||
super(context, R.layout.list_item_route, routes);
|
||||
this.context = context;
|
||||
this.routes = routes;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
|
||||
if (convertView == null){
|
||||
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_route, parent, false);
|
||||
}
|
||||
|
||||
Route route = routes.get(position);
|
||||
|
||||
((TextView) convertView.findViewById(R.id.title)).setText(route.getTitle());
|
||||
((TextView) convertView.findViewById(R.id.info1)).setText(route.getInfo()[0]);
|
||||
((TextView) convertView.findViewById(R.id.info2)).setText(route.getInfo()[1]);
|
||||
|
||||
return convertView;
|
||||
}
|
||||
|
||||
public void setItems(List<Route> list) {
|
||||
routes.clear();
|
||||
if (list != null) routes.addAll(list);
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() { return routes.size(); }
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class RouteStorage {
|
||||
private static final String FILE_NAME = "routes.json";
|
||||
private final Context ctx;
|
||||
private final Gson gson = new Gson();
|
||||
private final Executor executor = Executors.newSingleThreadExecutor();
|
||||
|
||||
public RouteStorage(Context ctx) {
|
||||
this.ctx = ctx.getApplicationContext();
|
||||
}
|
||||
|
||||
// Асинхронно сохраняет список (без callback)
|
||||
public void saveRoutesAsync(List<Route> routes) {
|
||||
executor.execute(() -> saveRoutesSync(routes));
|
||||
}
|
||||
|
||||
// Синхронная запись (внутри executor вызывается)
|
||||
public void saveRoutesSync(List<Route> routes) {
|
||||
try (FileOutputStream fos = ctx.openFileOutput(FILE_NAME, Context.MODE_PRIVATE)) {
|
||||
String json = gson.toJson(routes);
|
||||
fos.write(json.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
Log.e("RouteStorage", "saveRoutesSync failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Асинхронно загружает и вызывает callback на UI thread
|
||||
public void loadRoutesAsync(LoadCallback callback) {
|
||||
executor.execute(() -> {
|
||||
List<Route> list = loadRoutesSync();
|
||||
// вызываем callback в UI-потоке
|
||||
android.os.Handler mainHandler = new android.os.Handler(ctx.getMainLooper());
|
||||
mainHandler.post(() -> callback.onLoaded(list));
|
||||
});
|
||||
}
|
||||
|
||||
// Синхронная загрузка
|
||||
public List<Route> loadRoutesSync() {
|
||||
List<Route> res = new ArrayList<>();
|
||||
try (FileInputStream fis = ctx.openFileInput(FILE_NAME)) {
|
||||
byte[] bytes = new byte[fis.available()];
|
||||
fis.read(bytes);
|
||||
String json = new String(bytes, StandardCharsets.UTF_8);
|
||||
Type t = new TypeToken<List<Route>>(){}.getType();
|
||||
List<Route> loaded = gson.fromJson(json, t);
|
||||
if (loaded != null) res = loaded;
|
||||
} catch (Exception e) {
|
||||
// файл может не существовать — возвращаем пустой список
|
||||
Log.d("RouteStorage", "loadRoutesSync: file not found or error, returning empty list");
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public interface LoadCallback {
|
||||
void onLoaded(List<Route> routes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.example.saferoute.places;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.ImageButton;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.example.saferoute.R;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class RoutesListAdapter extends BaseAdapter {
|
||||
private final Context ctx;
|
||||
private final List<Route> items = new ArrayList<>();
|
||||
private final LayoutInflater inflater;
|
||||
private OnActionListener listener;
|
||||
|
||||
public interface OnActionListener {
|
||||
// void onUse(Route route); // нажали "Использовать" (отправить в MainActivity)
|
||||
// void onShow(Route route); // нажали "Показать" (центровать/показать на карте)
|
||||
void onDelete(Route route); // удалить маршрут
|
||||
}
|
||||
|
||||
public RoutesListAdapter(Context ctx) {
|
||||
this.ctx = ctx;
|
||||
this.inflater = LayoutInflater.from(ctx);
|
||||
}
|
||||
|
||||
public void setOnActionListener(OnActionListener l) { this.listener = l; }
|
||||
|
||||
public void setItems(List<Route> list) {
|
||||
items.clear();
|
||||
if (list != null) items.addAll(list);
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
public List<Route> getItems() { return items; }
|
||||
|
||||
@Override
|
||||
public int getCount() { return items.size(); }
|
||||
|
||||
@Override
|
||||
public Object getItem(int position) { return items.get(position); }
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) { return items.get(position).id; }
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
VH vh;
|
||||
if (convertView == null) {
|
||||
convertView = inflater.inflate(R.layout.list_item_route, parent, false);
|
||||
vh = new VH(convertView);
|
||||
convertView.setTag(vh);
|
||||
} else vh = (VH) convertView.getTag();
|
||||
|
||||
final Route r = items.get(position);
|
||||
vh.tvName.setText(r.title != null ? r.title : ("Маршрут " + r.id));
|
||||
int pointsCount = r.points != null ? r.points.size() : 0;
|
||||
// vh.tvInfo.setText(pointsCount + " точек");
|
||||
// vh.tvInfo.setText(pointsCount + " точек • " + android.text.format.DateFormat.format("dd.MM.yy HH:mm", r.createdAt));
|
||||
|
||||
// vh.btnUse.setOnClickListener(v -> {
|
||||
// if (listener != null) listener.onUse(r);
|
||||
// });
|
||||
//
|
||||
// vh.btnShow.setOnClickListener(v -> {
|
||||
// if (listener != null) listener.onShow(r);
|
||||
// });
|
||||
|
||||
// Длинный клик — удаление
|
||||
convertView.setOnLongClickListener(v -> {
|
||||
if (listener != null) listener.onDelete(r);
|
||||
return true;
|
||||
});
|
||||
|
||||
return convertView;
|
||||
}
|
||||
|
||||
static class VH {
|
||||
TextView tvName, tvInfo1, tvInfo2;
|
||||
// ImageButton btnUse, btnShow;
|
||||
VH(View v) {
|
||||
tvName = v.findViewById(R.id.title);
|
||||
tvInfo1 = v.findViewById(R.id.info1);
|
||||
tvInfo2 = v.findViewById(R.id.info2);
|
||||
// btnUse = v.findViewById(R.id.btnUse);
|
||||
// btnShow = v.findViewById(R.id.btnShow);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:height="50dp" android:viewportHeight="24" android:viewportWidth="24" android:width="50dp">
|
||||
|
||||
<path android:fillColor="@color/sgray" android:pathData="M16.041,24 L6.534,14.48a3.507,3.507 0,0 1,0 -4.948L16.052,0 18.17,2.121 8.652,11.652a0.5,0.5 0,0 0,0 0.707l9.506,9.52Z"/>
|
||||
|
||||
</vector>
|
||||
@@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector
|
||||
android:height="108dp"
|
||||
android:width="108dp"
|
||||
android:viewportHeight="108"
|
||||
android:viewportWidth="108"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="#3DDC84"
|
||||
android:pathData="M0,0h108v108h-108z"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M9,0L9,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M19,0L19,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M29,0L29,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M39,0L39,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M49,0L49,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M59,0L59,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M69,0L69,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M79,0L79,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M89,0L89,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M99,0L99,108"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,9L108,9"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,19L108,19"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,29L108,29"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,39L108,39"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,49L108,49"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,59L108,59"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,69L108,69"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,79L108,79"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,89L108,89"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M0,99L108,99"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M19,29L89,29"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M19,39L89,39"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M19,49L89,49"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M19,59L89,59"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M19,69L89,69"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M19,79L89,79"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M29,19L29,89"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M39,19L39,89"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M49,19L49,89"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M59,19L59,89"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M69,19L69,89"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
<path android:fillColor="#00000000" android:pathData="M79,19L79,89"
|
||||
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,30 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="85.84757"
|
||||
android:endY="92.4963"
|
||||
android:startX="42.9492"
|
||||
android:startY="49.59793"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||
android:strokeWidth="1"
|
||||
android:strokeColor="#00000000" />
|
||||
</vector>
|
||||
|
After Width: | Height: | Size: 685 B |
|
After Width: | Height: | Size: 627 B |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 39 KiB |
@@ -0,0 +1,5 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:height="50dp" android:viewportHeight="24" android:viewportWidth="24" android:width="50dp">
|
||||
|
||||
<path android:fillColor="@color/sgray" android:pathData="M21,12a9.143,9.143 0,0 0,-0.15 -1.645L23.893,8.6l-3,-5.2L17.849,5.159A9,9 0,0 0,15 3.513L15,0L9,0L9,3.513A9,9 0,0 0,6.151 5.159L3.107,3.4l-3,5.2L3.15,10.355a9.1,9.1 0,0 0,0 3.29L0.107,15.4l3,5.2 3.044,-1.758A9,9 0,0 0,9 20.487L9,24h6L15,20.487a9,9 0,0 0,2.849 -1.646L20.893,20.6l3,-5.2L20.85,13.645A9.143,9.143 0,0 0,21 12ZM15,12a3,3 0,1 1,-3 -3A3,3 0,0 1,15 12Z"/>
|
||||
|
||||
</vector>
|
||||
@@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:background="@color/lblue">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:orientation="horizontal">
|
||||
<ImageButton
|
||||
android:onClick="getBack2"
|
||||
android:id="@+id/go_back2"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:src="@drawable/angle_left"
|
||||
android:backgroundTint="@color/lblue"
|
||||
android:layout_weight="2"
|
||||
android:layout_marginRight="8dp"
|
||||
android:layout_marginLeft="8dp"/>
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_gravity="center"
|
||||
android:layout_marginRight="10dp"
|
||||
android:layout_weight="5"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:text="Контакты"
|
||||
android:textColor="@color/dblue"
|
||||
android:textSize="48dp" />
|
||||
</LinearLayout>
|
||||
<EditText
|
||||
android:id="@+id/name1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="Введите имя..."
|
||||
android:inputType="textPersonName"
|
||||
android:padding="12dp"
|
||||
android:layout_marginBottom="12dp"
|
||||
/>
|
||||
|
||||
<EditText
|
||||
android:id="@+id/number1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="Введите номер телефона..."
|
||||
android:inputType="phone"
|
||||
android:padding="12dp"
|
||||
android:layout_marginBottom="12dp"
|
||||
/>
|
||||
|
||||
<Button
|
||||
android:id="@+id/add_contact"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:layout_marginRight="10dp"
|
||||
android:layout_marginBottom="24dp"
|
||||
android:backgroundTint="@color/last"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:text="Добавить контакт" />
|
||||
<ListView
|
||||
android:id="@+id/list_contact"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,46 @@
|
||||
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<!-- Карта на весь экран -->
|
||||
<org.osmdroid.views.MapView
|
||||
android:id="@+id/map_picker"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
|
||||
<!-- Панель поиска сверху -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:padding="8dp"
|
||||
android:background="#AAFFFFFF"> <!-- Полупрозрачный белый фон -->
|
||||
|
||||
<EditText
|
||||
android:id="@+id/etSearchAddress"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:hint="Введите адрес..."
|
||||
android:background="@android:drawable/editbox_background"/>
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/btnSearch"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:src="@android:drawable/ic_menu_search"
|
||||
android:contentDescription="Поиск" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Кнопка подтверждения снизу (как была) -->
|
||||
<Button
|
||||
android:id="@+id/btnConfirmLocation"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_alignParentBottom="true"
|
||||
android:layout_centerHorizontal="true"
|
||||
android:layout_marginBottom="30dp"
|
||||
android:text="Подтвердить выбор"
|
||||
android:visibility="gone" />
|
||||
|
||||
</RelativeLayout>
|
||||
@@ -0,0 +1,51 @@
|
||||
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<!-- Карта на весь экран -->
|
||||
<org.osmdroid.views.MapView
|
||||
android:id="@+id/map_picker"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
|
||||
<!-- Панель поиска сверху -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:padding="8dp"
|
||||
android:background="#AAFFFFFF"> <!-- Полупрозрачный белый фон -->
|
||||
<Button
|
||||
android:id="@+id/btnStartSelection"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:layout_marginRight="10dp"
|
||||
android:backgroundTint="@color/last"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:layout_weight="1"
|
||||
android:text="Старт" />
|
||||
<Button
|
||||
android:id="@+id/btnBuildRoute"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:layout_marginRight="10dp"
|
||||
android:backgroundTint="@color/last"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:layout_weight="1"
|
||||
android:text="Стоп" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Кнопка подтверждения снизу (как была) -->
|
||||
<Button
|
||||
android:id="@+id/btnConfirmLocationRoute"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_alignParentBottom="true"
|
||||
android:layout_centerHorizontal="true"
|
||||
android:layout_marginBottom="30dp"
|
||||
android:text="Подтвердить выбор"
|
||||
android:visibility="gone" />
|
||||
|
||||
</RelativeLayout>
|
||||
@@ -0,0 +1,92 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:id="@+id/main"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
tools:context=".MainActivity"
|
||||
android:background="@color/lblue">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_weight="0.5"
|
||||
android:layout_marginTop="10dp"
|
||||
android:layout_marginBottom="10dp"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="50dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:layout_weight="5"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:text="SafeRoute"
|
||||
android:textColor="@color/dblue"
|
||||
android:textSize="50dp"></TextView>
|
||||
<ImageButton
|
||||
android:id="@+id/settings"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:src="@drawable/settings"
|
||||
android:backgroundTint="@color/lblue"
|
||||
android:onClick="getSettings"
|
||||
android:layout_weight="2">
|
||||
</ImageButton>
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.cardview.widget.CardView
|
||||
android:layout_weight="5"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="176dp"
|
||||
android:layout_margin="16dp"
|
||||
app:cardCornerRadius="16dp"
|
||||
app:layout_constraintBottom_toTopOf="@+id/controlPanel"
|
||||
app:layout_constraintTop_toBottomOf="@+id/statusCard">
|
||||
|
||||
<org.osmdroid.views.MapView
|
||||
android:id="@+id/map"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
</androidx.cardview.widget.CardView>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_weight="0.5"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:layout_marginBottom="30dp"
|
||||
android:layout_marginTop="20dp">
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/btnStartRoute"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginLeft="20dp"
|
||||
android:layout_marginRight="10dp"
|
||||
android:layout_weight="6"
|
||||
android:backgroundTint="@color/last"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:text="В путь"
|
||||
android:textSize="30dp"
|
||||
app:cornerRadius="10dp" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/btnSOS"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginRight="20dp"
|
||||
android:layout_weight="1"
|
||||
android:backgroundTint="@color/pink"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:onClick="SOS"
|
||||
android:text="SOS"
|
||||
android:textSize="30dp"
|
||||
app:cornerRadius="10dp" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,134 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:background="@color/lblue">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal">
|
||||
<ImageButton
|
||||
android:onClick="getBack3"
|
||||
android:id="@+id/go_back3"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:src="@drawable/angle_left"
|
||||
android:backgroundTint="@color/lblue"
|
||||
android:layout_weight="2"
|
||||
android:layout_marginRight="10dp"
|
||||
android:layout_marginLeft="10dp"/>
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_gravity="center"
|
||||
android:layout_marginRight="10dp"
|
||||
android:layout_weight="5"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:text="Места"
|
||||
android:textColor="@color/dblue"
|
||||
android:textSize="50dp" />
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
|
||||
<!-- Кнопки -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:layout_marginTop="2dp"
|
||||
android:weightSum="2">
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnAddPlace"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:layout_marginStart="2dp"
|
||||
android:text="Добавить место"
|
||||
android:backgroundTint="@color/last" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnAddRoute"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:layout_marginStart="2dp"
|
||||
android:text=" Создать путь"
|
||||
android:backgroundTint="@color/last" />
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
<!-- <ListView-->
|
||||
<!-- android:id="@+id/list_place"-->
|
||||
<!-- android:layout_width="match_parent"-->
|
||||
<!-- android:layout_height="match_parent"/>-->
|
||||
|
||||
<!-- Списки: две колонки -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="horizontal"
|
||||
android:layout_marginTop="8dp">
|
||||
|
||||
<!-- Колонка мест -->
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical"
|
||||
android:paddingEnd="4dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Места"
|
||||
android:layout_gravity="center"
|
||||
android:textColor="@color/dblue"
|
||||
android:textSize="20sp"
|
||||
android:fontFamily="sans-serif-medium" />
|
||||
|
||||
<!-- <androidx.recyclerview.widget.RecyclerView-->
|
||||
<!-- android:id="@+id/listPlace"-->
|
||||
<!-- android:layout_width="match_parent"-->
|
||||
<!-- android:layout_height="0dp"-->
|
||||
<!-- android:layout_weight="1"/>-->
|
||||
|
||||
<ListView
|
||||
android:id="@+id/lvPlaces"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"/>
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Колонка путей -->
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical"
|
||||
android:layout_gravity="center"
|
||||
android:paddingStart="4dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Пути"
|
||||
android:textColor="@color/dblue"
|
||||
android:textSize="20sp"
|
||||
android:layout_gravity="center"
|
||||
android:fontFamily="sans-serif-medium" />
|
||||
|
||||
<ListView
|
||||
android:id="@+id/lvRoutes"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"/>
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:background="@color/lblue">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:layout_marginTop="10dp"
|
||||
android:layout_marginBottom="10dp">
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/go_back"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:backgroundTint="@color/lblue"
|
||||
android:src="@drawable/angle_left"
|
||||
android:layout_weight="2"
|
||||
android:onClick="getBack"/>
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_gravity="center"
|
||||
android:layout_weight="6"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:text="Настройки"
|
||||
android:textColor="@color/dblue"
|
||||
android:textSize="50dp" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
<Button
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Мои контакты"
|
||||
android:textSize="35dp"
|
||||
android:textColor="@color/last"
|
||||
android:backgroundTint="@color/lblue"
|
||||
android:onClick="contacts"/>
|
||||
<Button
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Места"
|
||||
android:textSize="35dp"
|
||||
android:textColor="@color/last"
|
||||
android:backgroundTint="@color/lblue"
|
||||
android:onClick="places"/>
|
||||
|
||||
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginBottom="6dp"
|
||||
android:padding="12dp"
|
||||
>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/name"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="2"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:padding="2dp"
|
||||
android:text="ИМЯ"
|
||||
android:textSize="28sp" />
|
||||
<TextView
|
||||
android:id="@+id/number"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:padding="12dp"
|
||||
android:text="+00000000000"
|
||||
android:textSize="20dp"
|
||||
android:layout_gravity="right"/>
|
||||
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:layout_marginBottom="6dp"
|
||||
android:padding="6dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:text="НАЗВАНИЕ"
|
||||
android:textSize="20sp" />
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical">
|
||||
<TextView
|
||||
android:id="@+id/lat"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="00.000000"
|
||||
android:textSize="12sp"/>
|
||||
<TextView
|
||||
android:id="@+id/lon"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="00.000000"
|
||||
android:textSize="12sp"/>
|
||||
</LinearLayout>
|
||||
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,66 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:padding="8dp"
|
||||
android:gravity="center_vertical"
|
||||
android:background="?android:attr/selectableItemBackground">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical"
|
||||
android:paddingEnd="8dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Имя маршрута"
|
||||
android:textStyle="bold"
|
||||
android:fontFamily="sans-serif-black"
|
||||
android:textColor="@android:color/black"
|
||||
android:textSize="20sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/info1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Начало"
|
||||
android:textSize="12sp"
|
||||
android:textColor="#666666" />
|
||||
<TextView
|
||||
android:id="@+id/info2"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Конец"
|
||||
android:textSize="12sp"
|
||||
android:layout_marginTop="4dp"
|
||||
android:textColor="#666666" />
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<!-- <ImageButton-->
|
||||
<!-- android:id="@+id/btnUse"-->
|
||||
<!-- android:layout_width="44dp"-->
|
||||
<!-- android:layout_height="44dp"-->
|
||||
<!-- android:layout_marginEnd="4dp"-->
|
||||
<!-- android:background="@android:color/transparent"-->
|
||||
<!-- android:src="@drawable/ic_send"-->
|
||||
<!-- android:contentDescription="Использовать"-->
|
||||
<!-- android:scaleType="centerInside"-->
|
||||
<!-- android:tint="@color/dblue" />-->
|
||||
|
||||
<!-- <ImageButton-->
|
||||
<!-- android:id="@+id/btnShow"-->
|
||||
<!-- android:layout_width="44dp"-->
|
||||
<!-- android:layout_height="44dp"-->
|
||||
<!-- android:background="@android:color/transparent"-->
|
||||
<!-- android:src="@drawable/ic_eye"-->
|
||||
<!-- android:contentDescription="Показать"-->
|
||||
<!-- android:scaleType="centerInside"-->
|
||||
<!-- android:tint="@color/dblue" />-->
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 5.8 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 9.7 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,7 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Base.Theme.SafeRoute" parent="Theme.Material3.DayNight.NoActionBar">
|
||||
<!-- Customize your dark theme here. -->
|
||||
<!-- <item name="colorPrimary">@color/my_dark_primary</item> -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<resources>
|
||||
|
||||
<color name="black">#FF000000</color>
|
||||
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
|
||||
<color name="lightpink">#efd0db</color>
|
||||
|
||||
<color name="pink">#8f0030</color>
|
||||
|
||||
<color name="spink">#dca7bb</color>
|
||||
|
||||
<color name="sgray">#7f7679</color>
|
||||
|
||||
<color name="dgray">#696969</color>
|
||||
<color name="lblue">#94c5ff</color>
|
||||
<color name="dblue">#002060</color>
|
||||
<color name="last">#2a52a1</color>
|
||||
|
||||
</resources>
|
||||
@@ -0,0 +1,3 @@
|
||||
<resources>
|
||||
<string name="app_name">SafeRoute</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,9 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Base.Theme.SafeRoute" parent="Theme.Material3.DayNight.NoActionBar">
|
||||
<!-- Customize your light theme here. -->
|
||||
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
|
||||
</style>
|
||||
|
||||
<style name="Theme.SafeRoute" parent="Base.Theme.SafeRoute" />
|
||||
</resources>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
Sample backup rules file; uncomment and customize as necessary.
|
||||
See https://developer.android.com/guide/topics/data/autobackup
|
||||
for details.
|
||||
Note: This file is ignored for devices older that API 31
|
||||
See https://developer.android.com/about/versions/12/backup-restore
|
||||
-->
|
||||
<full-backup-content>
|
||||
<!--
|
||||
<include domain="sharedpref" path="."/>
|
||||
<exclude domain="sharedpref" path="device.xml"/>
|
||||
-->
|
||||
</full-backup-content>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
Sample data extraction rules file; uncomment and customize as necessary.
|
||||
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
|
||||
for details.
|
||||
-->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
||||
<include .../>
|
||||
<exclude .../>
|
||||
-->
|
||||
</cloud-backup>
|
||||
<!--
|
||||
<device-transfer>
|
||||
<include .../>
|
||||
<exclude .../>
|
||||
</device-transfer>
|
||||
-->
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<network-security-config>
|
||||
<domain-config cleartextTrafficPermitted="true">
|
||||
<domain includeSubdomains="true">router.project-osrm.org</domain>
|
||||
</domain-config>
|
||||
</network-security-config>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.saferoute;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
public class ExampleUnitTest {
|
||||
@Test
|
||||
public void addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
plugins {
|
||||
id("com.android.application") version "8.1.4" apply false
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Project-wide Gradle settings.
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app's APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
||||
|
||||
org.gradle.java.home=C\:\\Program Files\\Android\\Android Studio\\jbr
|
||||
@@ -0,0 +1,6 @@
|
||||
#Sat May 23 13:35:46 MSK 2026
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,26 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
// ВАЖНО: Меняем режим, чтобы разрешить добавление репозиториев
|
||||
// Временно меняем с FAIL_ON_PROJECT_REPOS на PREFER_SETTINGS
|
||||
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
|
||||
// Добавляем репозиторий Яндекс.Карт
|
||||
maven {
|
||||
url = uri("https://maven.datastax.com")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "SafeRoute"
|
||||
include(":app")
|
||||
|
||||