Я пытаюсь создать приложение для Android, которое работает в качестве услуги на заднем плане, он обнаруживает, если я еду на велосипеде, а затем начинает расчет общего пройденного расстояния и останавливается, когда он обнаруживает AM пешком. У меня есть сервис, вещательный приемник и основное действие для запроса разрешений у пользователя. Я объявил все соответствующие перемещения в манифесте, но он просто опубликовал одно уведомление под названием Monitoring Activity , которое является результатом некоторого кода в службе.
manifest
написанного вопроса> bikedetections service.java
package com.example.bikedistancetracker;
import android.Manifest;
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.location.Location;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import com.google.android.gms.location.ActivityRecognition;
import com.google.android.gms.location.ActivityRecognitionClient;
import com.google.android.gms.location.DetectedActivity;
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;
public class BikeDetectionService extends Service {
private static final String CHANNEL_ID = "BikeTrackingChannel";
private ActivityRecognitionClient activityRecognitionClient;
private FusedLocationProviderClient fusedLocationClient;
private Location lastLocation;
private float totalDistance = 0f;
private boolean isRiding = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int type = intent.getIntExtra("activityType", -1);
int confidence = intent.getIntExtra("confidence", -1);
handleActivity(type, confidence);
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
// Start foreground service
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Bike Tracker")
.setContentText("Monitoring activity…")
.setSmallIcon(R.drawable.ic_bike)
.build();
startForeground(1, notification);
activityRecognitionClient = ActivityRecognition.getClient(this);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// Start listening for activity changes
requestActivityUpdates();
}
private void requestActivityUpdates() {
Intent intent = new Intent(this, BikeTransitionReceiver.class);
intent.setAction("BIKE_ACTIVITY_UPDATE");
// PendingIntent must target a BroadcastReceiver
android.app.PendingIntent pendingIntent = android.app.PendingIntent.getBroadcast(
this,
0,
intent,
android.app.PendingIntent.FLAG_UPDATE_CURRENT | android.app.PendingIntent.FLAG_IMMUTABLE
);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != 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.
Toast.makeText(this, "activity update permission denied", Toast.LENGTH_LONG).show();
return;
}
activityRecognitionClient.requestActivityUpdates(5000, pendingIntent);
}
// Called externally from BikeTransitionReceiver
public void handleActivity(int activityType, int confidence) {
if (activityType == DetectedActivity.ON_BICYCLE && confidence > 70) {
if (!isRiding) {
startRide();
}
} else if (isRiding && (activityType == DetectedActivity.STILL || activityType == DetectedActivity.IN_VEHICLE)) {
stopRide();
}
}
private void startRide() {
isRiding = true;
totalDistance = 0f;
lastLocation = null;
LocationRequest locationRequest = LocationRequest.create()
.setInterval(5000)
.setFastestInterval(2000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}
private void stopRide() {
isRiding = false;
fusedLocationClient.removeLocationUpdates(locationCallback);
// Save ride data to DB here (distance, time, etc.)
// Example: RideRepository.saveRide(totalDistance);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification stoppedNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Ride Finished")
.setContentText("Distance: " + totalDistance + " meters")
.setSmallIcon(R.drawable.ic_bike)
.build();
manager.notify(2, stoppedNotification);
}
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
if (lastLocation != null) {
totalDistance += lastLocation.distanceTo(location);
}
lastLocation = location;
}
}
};
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Bike Tracking",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannel(channel);
}
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null; // not a bound service
}
}
Транслярный приемник для обнаружения велосипедных переходов
package com.example.bikedistancetracker;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
public class BikeTransitionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity activity = result.getMostProbableActivity();
Intent serviceIntent = new Intent(context, BikeDetectionService.class);
serviceIntent.putExtra("activityType", activity.getType());
serviceIntent.putExtra("confidence", activity.getConfidence());
context.startService(serviceIntent);
}
}
}
Я ожидал, что код будет обнаружен при переходе на велосипед, начинает рассчитывать расстояние и публикует его в качестве уведомления, но единственным опубликованным уведомлением является деятельность по мониторингу ...
Я программировал все соответствующие разрешения от пользователя при выполнении выполнения в моей активности
private void requestAllPermissions() {
// Collect all the permissions you need
// (BOOT_COMPLETED is manifest-only, no runtime dialog)
String[] basePermissions = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACTIVITY_RECOGNITION
};
// Add POST_NOTIFICATIONS only if Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
basePermissions = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACTIVITY_RECOGNITION,
Manifest.permission.POST_NOTIFICATIONS,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
};
}
// Request them
ActivityCompat.requestPermissions(this, basePermissions, REQ_PERMISSIONS);
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -travelled
Приложение Android для обнаружения пользователя на велосипеде, а затем вычисляет общее расстояние, пройденное, когда на ⇐ Android
Форум для тех, кто программирует под Android
1758515929
Anonymous
Я пытаюсь создать приложение для Android, которое работает в качестве услуги на заднем плане, он обнаруживает, если я еду на велосипеде, а затем начинает расчет общего пройденного расстояния и останавливается, когда он обнаруживает AM пешком. У меня есть сервис, вещательный приемник и основное действие для запроса разрешений у пользователя. Я объявил все соответствующие перемещения в манифесте, но он просто опубликовал одно уведомление под названием [b] Monitoring Activity [/b], которое является результатом некоторого кода в службе.
manifest
написанного вопроса> bikedetections service.java
package com.example.bikedistancetracker;
import android.Manifest;
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.location.Location;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import com.google.android.gms.location.ActivityRecognition;
import com.google.android.gms.location.ActivityRecognitionClient;
import com.google.android.gms.location.DetectedActivity;
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;
public class BikeDetectionService extends Service {
private static final String CHANNEL_ID = "BikeTrackingChannel";
private ActivityRecognitionClient activityRecognitionClient;
private FusedLocationProviderClient fusedLocationClient;
private Location lastLocation;
private float totalDistance = 0f;
private boolean isRiding = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int type = intent.getIntExtra("activityType", -1);
int confidence = intent.getIntExtra("confidence", -1);
handleActivity(type, confidence);
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
// Start foreground service
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Bike Tracker")
.setContentText("Monitoring activity…")
.setSmallIcon(R.drawable.ic_bike)
.build();
startForeground(1, notification);
activityRecognitionClient = ActivityRecognition.getClient(this);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// Start listening for activity changes
requestActivityUpdates();
}
private void requestActivityUpdates() {
Intent intent = new Intent(this, BikeTransitionReceiver.class);
intent.setAction("BIKE_ACTIVITY_UPDATE");
// PendingIntent must target a BroadcastReceiver
android.app.PendingIntent pendingIntent = android.app.PendingIntent.getBroadcast(
this,
0,
intent,
android.app.PendingIntent.FLAG_UPDATE_CURRENT | android.app.PendingIntent.FLAG_IMMUTABLE
);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != 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.
Toast.makeText(this, "activity update permission denied", Toast.LENGTH_LONG).show();
return;
}
activityRecognitionClient.requestActivityUpdates(5000, pendingIntent);
}
// Called externally from BikeTransitionReceiver
public void handleActivity(int activityType, int confidence) {
if (activityType == DetectedActivity.ON_BICYCLE && confidence > 70) {
if (!isRiding) {
startRide();
}
} else if (isRiding && (activityType == DetectedActivity.STILL || activityType == DetectedActivity.IN_VEHICLE)) {
stopRide();
}
}
private void startRide() {
isRiding = true;
totalDistance = 0f;
lastLocation = null;
LocationRequest locationRequest = LocationRequest.create()
.setInterval(5000)
.setFastestInterval(2000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}
private void stopRide() {
isRiding = false;
fusedLocationClient.removeLocationUpdates(locationCallback);
// Save ride data to DB here (distance, time, etc.)
// Example: RideRepository.saveRide(totalDistance);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification stoppedNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Ride Finished")
.setContentText("Distance: " + totalDistance + " meters")
.setSmallIcon(R.drawable.ic_bike)
.build();
manager.notify(2, stoppedNotification);
}
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
if (lastLocation != null) {
totalDistance += lastLocation.distanceTo(location);
}
lastLocation = location;
}
}
};
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Bike Tracking",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannel(channel);
}
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null; // not a bound service
}
}
Транслярный приемник для обнаружения велосипедных переходов
package com.example.bikedistancetracker;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
public class BikeTransitionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity activity = result.getMostProbableActivity();
Intent serviceIntent = new Intent(context, BikeDetectionService.class);
serviceIntent.putExtra("activityType", activity.getType());
serviceIntent.putExtra("confidence", activity.getConfidence());
context.startService(serviceIntent);
}
}
}
Я ожидал, что код будет обнаружен при переходе на велосипед, начинает рассчитывать расстояние и публикует его в качестве уведомления, но единственным опубликованным уведомлением является [b] деятельность по мониторингу ... [/b]
Я программировал все соответствующие разрешения от пользователя при выполнении выполнения в моей активности
private void requestAllPermissions() {
// Collect all the permissions you need
// (BOOT_COMPLETED is manifest-only, no runtime dialog)
String[] basePermissions = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACTIVITY_RECOGNITION
};
// Add POST_NOTIFICATIONS only if Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
basePermissions = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACTIVITY_RECOGNITION,
Manifest.permission.POST_NOTIFICATIONS,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
};
}
// Request them
ActivityCompat.requestPermissions(this, basePermissions, REQ_PERMISSIONS);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79771233/android-app-for-detecting-user-on-bike-then-calculates-total-distance-travelled[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия