this is my code to recognize user activity based on gyroscope and accelerometer firstly if you see any way to improve you are welcome to modifier my code the second thing is I want adding a jumping activity but i don’t know the thresholds
import androidx.appcompat.app.AppCompatActivity;
public class RecogniweWSensorActivity extends AppCompatActivity implements SensorEventListener {
code
Assistant
To add the recognition of the jumping activity, you can modify the updateActivity method with an additional condition based on the threshold values that best identify the jumping motion. Below is the modified version of the updateActivity method, with the jumping recognition included. You might need to adjust the threshold values based on your testing.
User
does the jumping should be more or less than running
Assistant
The jumping activity would typically have a higher accelerometer value than running because the body is exerting more force in a shorter amount of time during a jump. Therefore, the acceleration values during a jump should generally be higher compared to running.
In the provided example, the threshold for detecting a jump was set to require an average acceleration higher than 20, while the threshold for running was set to require an average acceleration higher than 15. The difference in the thresholds allows the code to distinguish between running and jumping.
However, these thresholds may need to be fine-tuned through testing to accurately identify and differentiate jumping and running in your specific use case and with your specific set of users. You can experiment with different threshold values and observe the results to decide which values work best to distinguish between jumping, running, and other activities.
User
Assistant
This code consists of several classes related to activity recognition in an Android application.
User
here is an recycle view to display the activities histories for a user but if there is no activities an error occured how can i make a message "no activities yet " showed instead of error :
public class ActionsActivity extends AppCompatActivity {
To display the message "No activities yet" when there are no activities, you can add a TextView to your layout, update its visibility based on the activities' count, and show the message when there are no activities. Follow these steps:
Add a TextView named txt_no_activities to your layout (e.g., activity_actions.xml) where you want the "No activities yet" message to be displayed.
ActivityRecogniweWsensorBinding binding;
private SensorManager sensorManager;
private Sensor accelerometerSensor, gyroscopeSensor;
private List<Float> accelerometerValues;
private List<Float> gyroscopeValues;
String email;
DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityRecogniweWsensorBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
email = getIntent().getStringExtra("email");
// Initialize sensor manager and sensors
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
accelerometerValues = new ArrayList<>();
gyroscopeValues = new ArrayList<>();
db = new DatabaseHelper(this);
}
@Override
protected void onResume() {
super.onResume();
// Register sensor listeners
sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, gyroscopeSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
// Unregister sensor listeners to save battery
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
/* The accelerometer measures the acceleration of the device in three axes (x, y, and z)
and adds the result to the list accelerometerValues */
if (event.sensor == accelerometerSensor) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
float acceleration = (float) Math.sqrt(x * x + y * y + z * z);
accelerometerValues.add(acceleration);
/* The gyroscope measures the rotation of the device in three axes (x, y, and z)
and adds the result to the list gyroscopeValues */
} else if (event.sensor == gyroscopeSensor) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
float rotation = (float) Math.sqrt(x * x + y * y + z * z);
gyroscopeValues.add(rotation);
}
// Update activity based on the average of the sensors values
updateActivity(getAverageAcceleration(), getAverageRotation());
}
//
private float getAverageAcceleration() {
float sumAccelerations = 0;
for (float acceleration : accelerometerValues) {
sumAccelerations += acceleration;
}
return accelerometerValues.isEmpty() ? 0 : sumAccelerations / accelerometerValues.size();
}
private float getAverageRotation() {
float sumRotations = 0;
for (float rotation : gyroscopeValues) {
sumRotations += rotation;
}
return gyroscopeValues.isEmpty() ? 0 : sumRotations / gyroscopeValues.size();
}
private long lastCleaningTime = 0;
/* compares values to predefined thresholds for each activity.
* If the average acceleration and rotation values are above the thresholds for a certain activity,
* that activity is recognized
* store the activity in the database
* then notify the user */
private void updateActivity(float averageAcceleration, float averageRotation) {
String activityText;
int icon = R.drawable.sitting;
// Clean sensor values every 20 seconds
long currentTime = System.currentTimeMillis();
if (currentTime - lastCleaningTime >= 5000) {
Toast.makeText(getApplicationContext(), "Update", Toast.LENGTH_SHORT).show();
accelerometerValues.clear();
gyroscopeValues.clear();
lastCleaningTime = currentTime;
}
if (averageAcceleration > 15 && averageRotation > 5) {
activityText = "Running";
icon = R.drawable.activity_running;
} else if (averageAcceleration > 10 && averageRotation > 2) {
activityText = "Walking";
icon = R.drawable.activity_walking;
} else if (averageAcceleration > 5 && averageRotation > 1) {
activityText = "Standing";
icon = R.drawable.activity_still;
} else {
activityText = "Sitting";
icon = R.drawable.sitting;
}
if(!binding.tvStill.getText().toString().equals(activityText)) {
Activity activity = db.getLastActivity();
if(activity.getEndDate().equals("")){
db.updateEndDate(new Date().toString(),activity.getId());
}
binding.tvStill.setText(activityText);
binding.imgActivity.setImageResource(icon);
db.addActivity(new Activity(email, activityText, new Date().toString(),""));
makeNotification(activityText);
}
}
public void makeNotification(String accActivity) {
String channelid = "CHANNEL_ID_NOTIFICATION";
NotificationCompat.Builder builder =
new NotificationCompat.Builder(getApplicationContext(), channelid)
.setSmallIcon(R.drawable.runner)
.setContentTitle("Activity changed")
.setContentText("Your are " + accActivity)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Intent intent = new Intent(getApplicationContext(), RecogniweWSensorActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_MUTABLE);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
NotificationChannel notificationChannel=
notificationManager.getNotificationChannel(channelid);
if(notificationChannel==null){
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelid, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
}
notificationManager.notify(0,builder.build());
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do nothing
}
Additionally, you would need to add the drawable icon for the jumping activity and include it in your project resources.
java
icon = R.drawable.activity_jumping;
You might need to adjust the threshold values (e.g., averageAcceleration > 20 and averageRotation > 7) according to your specific use case and testing results. This is just a starting point, and you can fine-tune those values to identify the jumping activity accurately.
comment this code : package org.project.ayoub_akanoun_projet.activitiesRecognition;
public class ActivityRecognitionService extends IntentService {
code
public ActivityRecognitionService() {
super("ActivityRecognitionService");
}
@Override
protected void onHandleIntent(Intent intent) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
// Get the list of the probable activities associated with the current state of the
// device. Each activity is associated with a confidence level, which is an int between
// 0 and 100.
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
for (DetectedActivity activity : detectedActivities) {
Log.e(TAG, "Detection d'activité: " + activity.getType() + ", " + activity.getConfidence());
broadcastActivity(activity);
}
}
private void broadcastActivity(DetectedActivity activity) {
Intent intent = new Intent("activity_intent");
intent.putExtra("type", activity.getType());
intent.putExtra("confidence", activity.getConfidence());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
ActivityConfidenceActivity: This class is the main activity class where the activity recognition permissions are requested. It incorporates start and stop buttons for initiating the activity recognition process, and sets up a BroadcastReceiver to listen for updates from the ActivityRecognitionService.
BackgroundDetectedActivity: This class is a service that starts and stops the activity recognition updates from Google's Activity Recognition API. It uses ActivityRecognitionClient to request activity updates and manage them through a PendingIntent.
ActivityRecognitionService: This class is an IntentService responsible for handling the activity updates sent by the Google Play Services. When an update is received, it extracts the result and sends a broadcast with the detected activity's type and confidence level. This broadcast is then captured by the ActivityConfidenceActivity's BroadcastReceiver.
In the main ActivityConfidenceActivity, the handleUserActivity method is responsible for displaying the recognized activity along with its confidence level. The recognized activities include in_vehicle, on_bicycle, on_foot, running, still, walking, and unknown states. A corresponding icon is set for each recognized activity. Furthermore, a notification is created every time the activity changes.
Here's a brief description of what each part of the code does:
ActivityConfidenceActivity:
Handles activity recognition permissions
Sets up click listeners for start and stop buttons
Initializes a BroadcastReceiver for receiving activity updates
Displays recognized activities and their confidence levels in the UI
Stores recognized activities in a local database
BackgroundDetectedActivity:
Manages activity recognition updates using ActivityRecognitionClient
Handles starting and stopping of recognition updates
ActivityRecognitionService:
Processes activity recognition updates from the API
Extracts the recognized activities and their confidence levels
Sends local broadcasts with recognized activity details
Overall, this code sample demonstrates how to recognize user activities in Android using the Google Play Services Activity Recognition API, and it updates the UI and creates notifications according to the detected activity types.
In your ActionsActivity class, find the txt_no_activities TextView and update its visibility based on the number of activities.
java
public class ActionsActivity extends AppCompatActivity {
private DatabaseHelper mydb;
private RecyclerView recyclerView;
ActivityActionsBinding binding;
String email;
TextView txt_no_activities;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityActionsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
email= getIntent().getStringExtra("email");
recyclerView = binding.idRecHistory;
txt_no_activities = binding.txt_no_activities; // Add this line to find the TextView
mydb = new DatabaseHelper(ActionsActivity.this);
List<Activity> activities = mydb.getActivities(email);
if (activities == null || activities.isEmpty()) {
txt_no_activities.setVisibility(View.VISIBLE);
} else {
txt_no_activities.setVisibility(View.GONE);
}
ActionAdapter adapter = new ActionAdapter(this, activities);
recyclerView.setAdapter(adapter);
}
}
When there are no activities, the txt_no_activities TextView will become visible and display the message "No activities yet." When there are activities, the TextView will be hidden, and only the RecyclerView will be visible.