this is an old conversation between me and you : To achieve this, you can use the…
- User
this is an old conversation between me and you : To achieve this, you can use the Activity Recognition API provided by Google Play services. Here’s how you can create a new interface to recognize user activities and display the confidence values:
Step 1: Add Google Play services to your project.
Add the following to your app’s build.gradle file, under the dependencies section:
implementation ‘com.google.android.gms:play-services-location:18.0.0’
Step 2: Create a new class for detecting activities.
Create a new class called ActivityRecognitionService and extend it from IntentService:
import android.app.IntentService; import android.content.Intent; import com.google.android.gms.location.ActivityRecognitionResult; import com.google.android.gms.location.DetectedActivity;
public class ActivityRecognitionService extends IntentService {
public ActivityRecognitionService() { super(“ActivityRecognitionService”); } @Override protected void onHandleIntent(Intent intent) { if (ActivityRecognitionResult.hasResult(intent)) { ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); DetectedActivity mostProbableActivity = result.getMostProbableActivity(); int confidence = mostProbableActivity.getConfidence(); int activityType = mostProbableActivity.getType(); // TODO: Handle the detected activity here } }}
Step 3: Update your AndroidManifest.xml.
Add the following service inside the <application> tag of your AndroidManifest.xml:
Step 4: Request activity recognition updates in your MainActivity.
In your MainActivity class, add the following code to request activity recognition updates:
private final int REQUEST_CODE_ACTIVITY_RECOGNITION = 100; private PendingIntent activityRecognitionPendingIntent; private ActivityRecognitionClient activityRecognitionClient;
private void requestActivityUpdates() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, REQUEST_CODE_ACTIVITY_RECOGNITION); return; }
activityRecognitionClient = new ActivityRecognitionClient(this); Intent intent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionClient.requestActivityUpdates(1000, activityRecognitionPendingIntent);}
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_ACTIVITY_RECOGNITION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { requestActivityUpdates(); } // Handle other permission results here }
Now, when you call requestActivityUpdates() method, it will request for activity recognition updates. Handle the detected activities in the onHandleIntent() method of your ActivityRecognitionService class.
Step 5: Create a new Activity to display confidence values.
Create a new activity called ActivityConfidenceActivity with a layout that contains a TextView for each activity (walking, running, sitting, and jumping). Update the TextView with the confidence values in the onHandleIntent() method of the ActivityRecognitionService.
Don’t forget to add your new activity to your AndroidManifest.xml. Now, when the user opens this activity, they will see the confidence values for each detected activity. j’ai une error la activityRecognitionClient = new ActivityRecognitionClient(this); dit que ‘ActivityRecognitionClient’ is abstract; cannot be instantiated I apologize for the confusion. You should use ActivityRecognition.getClient(this) instead of instantiating ActivityRecognitionClient. Here’s how to update the requestActivityUpdates() method:
Change this line:
activityRecognitionClient = new ActivityRecognitionClient(this);
to:
activityRecognitionClient = ActivityRecognition.getClient(this);
So, the updated requestActivityUpdates() method should look like this:
private void requestActivityUpdates() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, REQUEST_CODE_ACTIVITY_RECOGNITION); return; }
activityRecognitionClient = ActivityRecognition.getClient(this); Intent intent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionClient.requestActivityUpdates(1000, activityRecognitionPendingIntent);}
Now, you should no longer encounter the error. so know i added an activity ActivityConfidenceActivity contient textView for (walking, running, sitting, and jumping how can you provide the code that should out in onHandleIntent In order to update the TextViews in ActivityConfidenceActivity from ActivityRecognitionService, you can use a BroadcastReceiver. Here’s how you can do it:
Step 1: Create a BroadcastReceiver in your ActivityConfidenceActivity.
public class ActivityConfidenceActivity extends AppCompatActivity { private BroadcastReceiver activityReceiver;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confidence); activityReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int type = intent.getIntExtra(“type”, -1); int confidence = intent.getIntExtra(“confidence”, 0); // Update the TextViews according to the activity type and confidence } }; }}
Step 2: Register and unregister the BroadcastReceiver.
@Override protected void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter(“activity_update”)); }
@Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(activityReceiver); }
Step 3: Update the onHandleIntent() method in ActivityRecognitionService.
@Override protected void onHandleIntent(Intent intent) { if (ActivityRecognitionResult.hasResult(intent)) { ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); DetectedActivity mostProbableActivity = result.getMostProbableActivity(); int confidence = mostProbableActivity.getConfidence(); int activityType = mostProbableActivity.getType();
// Send a broadcast with the activity type and confidence Intent broadcastIntent = new Intent(“activity_update”); broadcastIntent.putExtra(“type”, activityType); broadcastIntent.putExtra(“confidence”, confidence); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent); }}
Now, your ActivityConfidenceActivity will receive updates from the ActivityRecognitionService. Update the TextViews according to the received activityType and confidence values in the onReceive() method of the BroadcastReceiver.
Please make sure you have added the required import statements for BroadcastReceiver, LocalBroadcastManager, and other classes used in the code snippets. can you give me // Update the TextViews according to the activity type and confidence code Certainly! First, you need to add the TextViews for walking, running, sitting, and jumping in your activity_confidence.xml layout file. Add the following to your layout:
<TextView android:id=“@+id/tv_walking” android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Walking: " />
<TextView android:id=”@+id/tv_running" android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Running: " />
<TextView android:id=”@+id/tv_sitting" android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Sitting: " />
<TextView android:id=”@+id/tv_jumping" android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Jumping: " />
Now, you can reference these TextViews in your ActivityConfidenceActivity. Update the onReceive() method in the BroadcastReceiver as follows:
activityReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int type = intent.getIntExtra(“type”, -1); int confidence = intent.getIntExtra(“confidence”, 0);
TextView tvWalking = findViewById(R.id.tv_walking); TextView tvRunning = findViewById(R.id.tv_running); TextView tvSitting = findViewById(R.id.tv_sitting); TextView tvJumping = findViewById(R.id.tv_jumping); String confidenceText = " (” + confidence + “%)”; switch (type) { case DetectedActivity.WALKING: tvWalking.setText(“Walking:” + confidenceText); break; case DetectedActivity.RUNNING: tvRunning.setText(“Running:” + confidenceText); break; case DetectedActivity.STILL: tvSitting.setText(“Sitting:” + confidenceText); break; case DetectedActivity.ON_FOOT: // You can use this as an approximation for jumping tvJumping.setText(“Jumping:” + confidenceText); break; default: // Handle other activity types if needed break; } }};
This code will update the corresponding TextView based on the detected activity type and display the confidence value in the format “Activity: (Confidence%)”. Adjust the case values and other code parts if necessary according to your specific activity types and layout structure. ==> this is my main package org.project.ayoub_akanoun_projet;
import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat;
import android.app.PendingIntent; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.widget.Button; import android.widget.Toast;
import com.google.android.gms.location.ActivityRecognition; import com.google.android.gms.location.ActivityRecognitionClient;
import org.project.ayoub_akanoun_projet.activitiesRecognition.ActivityConfidenceActivity; import org.project.ayoub_akanoun_projet.activitiesRecognition.ActivityRecognitionService;
public class Main2Activity extends AppCompatActivity { private final int REQUEST_CODE_ACTIVITY_RECOGNITION = 100; private PendingIntent activityRecognitionPendingIntent; private ActivityRecognitionClient activityRecognitionClient; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestActivityUpdates(); } button = findViewById(R.id.button); button.setOnClickListener(v -> { Intent intent = new Intent(Main2Activity.this, ActivityConfidenceActivity.class); startActivity(intent); }); } @RequiresApi(api = Build.VERSION_CODES.Q) private void requestActivityUpdates() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACTIVITY_RECOGNITION}, REQUEST_CODE_ACTIVITY_RECOGNITION); Toast.makeText(this, "permession diened", Toast.LENGTH_SHORT).show(); return; } activityRecognitionClient = ActivityRecognition.getClient(this); Intent intent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionClient.requestActivityUpdates(1000, activityRecognitionPendingIntent); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_ACTIVITY_RECOGNITION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestActivityUpdates(); } } }}
when the ActivityConfidence showed it didn't updates
- Assistant
My apologies for the inconvenience. I understand that the ActivityConfidenceActivity is not updating properly. Let's make sure that the BroadcastReceiver is registered and working correctly.
Please try adding a Log statement in the
onReceive()method of the BroadcastReceiver in ActivityConfidenceActivity to check if it is receiving updates:activityReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d("ActivityUpdate", "Received update"); // Add this line int type = intent.getIntExtra("type", -1); int confidence = intent.getIntExtra("confidence", 0); ... } };Don't forget to add
import android.util.Log;statement at the beginning of your ActivityConfidenceActivity.Now, while running your app on a device, open Logcat in Android Studio by clicking the "Logcat" tab at the bottom of the IDE. Then, filter the logs by typing "ActivityUpdate" in the search bar. It will show you the logs with the "Received update" message whenever an update is received in the BroadcastReceiver.
Please make sure you have these necessary sections in ActivityConfidenceActivity:
-
onCreate()method in which you initializeactivityReceiver. -
onResume()method in which you register the BroadcastReceiver usingLocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter("activity_update")); -
onPause()method in which you unregister the BroadcastReceiver usingLocalBroadcastManager.getInstance(this).unregisterReceiver(activityReceiver);
If you can see the "Received update" log message in Logcat, it means that the BroadcastReceiver is working correctly. If TextViews are still not updating, double-check the findViewById() and setText() sections in the
onReceive()method.If you don't see the "Received update" message in Logcat, it could be an issue with the BroadcastReceiver registration or sending updates from ActivityRecognitionService. Double-check the registration and unregistration of the BroadcastReceiver in
onResume()andonPause()methods and ensure thatLocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);is called inside theonHandleIntent()method of ActivityRecognitionService.If the issue persists, please provide any additional details, error messages, or unusual behavior you have encountered to help me understand the problem better.
-
- User
this is my ActivityRecognitionService :public class ActivityRecognitionService extends IntentService {
public ActivityRecognitionService() { super("ActivityRecognitionService"); } @Override protected void onHandleIntent(Intent intent) { if (ActivityRecognitionResult.hasResult(intent)) { ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); DetectedActivity mostProbableActivity = result.getMostProbableActivity(); int confidence = mostProbableActivity.getConfidence(); int activityType = mostProbableActivity.getType(); Intent broadcastIntent = new Intent("activity_update"); broadcastIntent.putExtra("type", activityType); broadcastIntent.putExtra("confidence", confidence); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent); } }} and this is my ActivityConfidence public class ActivityConfidenceActivity extends AppCompatActivity {
private BroadcastReceiver activityReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confidence); activityReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d("ActivityUpdate", "Received update"); int type = intent.getIntExtra("type", -1); int confidence = intent.getIntExtra("confidence", 0); // Update the TextViews according to the activity type and confidence TextView tvWalking = findViewById(R.id.textViewWalking); TextView tvRunning = findViewById(R.id.textViewRunning); TextView tvSitting = findViewById(R.id.textViewSitting); TextView tvJumping = findViewById(R.id.textViewJumping); String confidenceText = " (" + confidence + "%)"; switch (type) { case DetectedActivity.WALKING: tvWalking.setText("Walking:" + confidenceText); break; case DetectedActivity.RUNNING: tvRunning.setText("Running:" + confidenceText); break; case DetectedActivity.STILL: tvSitting.setText("Sitting:" + confidenceText); break; case DetectedActivity.ON_FOOT: tvJumping.setText("Jumping:" + confidenceText); break; default: break; } } }; } @Override protected void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter("activity_update")); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(activityReceiver); }} and this is my main public class Main2Activity extends AppCompatActivity {
private final int REQUEST_CODE_ACTIVITY_RECOGNITION = 100; private PendingIntent activityRecognitionPendingIntent; private ActivityRecognitionClient activityRecognitionClient; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestActivityUpdates(); } button = findViewById(R.id.button); button.setOnClickListener(v -> { Intent intent = new Intent(Main2Activity.this, ActivityConfidenceActivity.class); startActivity(intent); }); } @RequiresApi(api = Build.VERSION_CODES.Q) private void requestActivityUpdates() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACTIVITY_RECOGNITION}, REQUEST_CODE_ACTIVITY_RECOGNITION); Toast.makeText(this, "permession diened", Toast.LENGTH_SHORT).show(); return; } activityRecognitionClient = ActivityRecognition.getClient(this); Intent intent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionClient.requestActivityUpdates(1000, activityRecognitionPendingIntent); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_ACTIVITY_RECOGNITION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestActivityUpdates(); } } }}in manifist : no log for ActivityUpdate was detected
- Assistant
Thank you for sharing the code. Let's try changing the IntentFilter's action string to a more defined name to avoid potential conflicts with other receivers.
First, update your
ActivityConfidenceActivityclass:Replace this line:
LocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter("activity_update"));with:
LocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter("org.project.ayoub_akanoun_projet.ACTIVITY_UPDATE"));And do the same for the
ActivityRecognitionServiceclass:Replace this line:
Intent broadcastIntent = new Intent("activity_update");with:
Intent broadcastIntent = new Intent("org.project.ayoub_akanoun_projet.ACTIVITY_UPDATE");By changing the action string to a more defined name, we want to make sure there's no conflict with other IntentFilters that might have the same "activity_update" action string.
After making these changes, run your app, and now check the Logcat for "ActivityUpdate" logs. If the issue persists, please let me know, and we can investigate further.
- User
i guess the problem was solved after turning on the location on the phone can you modifier my code to ask for turning the location on too
- Assistant
Great to hear that the problem is solved! To prompt the user to turn on their location, you can use the
SettingsApito display a dialog asking the user to enable it. Here's how you can do it in yourMain2Activity:Step 1: Implement the
GoogleApiClient.ConnectionCallbacksandGoogleApiClient.OnConnectionFailedListenerinterfaces in yourMain2Activity.public class Main2Activity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {Step 2: Add the
GoogleApiClientobject and thecheckLocationSettings()method.private GoogleApiClient googleApiClient; private static final int LOCATION_SETTINGS_REQUEST = 2000; private void checkLocationSettings() { if (googleApiClient == null) { googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); googleApiClient.connect(); } LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(1000); locationRequest.setFastestInterval(1000 / 2); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest); builder.setAlwaysShow(true); Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build()); result.addOnCompleteListener(task -> { try { LocationSettingsResponse response = task.getResult(ApiException.class); // Location settings are satisfactory, no need to show the dialog } catch (ApiException e) { switch (e.getStatusCode()) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { // Show the dialog to turn on the location ResolvableApiException resolvableApiException = (ResolvableApiException) e; resolvableApiException.startResolutionForResult(Main2Activity.this, LOCATION_SETTINGS_REQUEST); } catch (IntentSender.SendIntentException exception) { // Handle the error } break; } } }); }Add
import com.google.android.gms.common.api.ResolvableApiException;and other required imports for the classes used.Step 3: Call the
checkLocationSettings()method in youronCreate()method:@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestActivityUpdates(); } button = findViewById(R.id.button); button.setOnClickListener(v -> { Intent intent = new Intent(Main2Activity.this, ActivityConfidenceActivity.class); startActivity(intent); }); checkLocationSettings(); // Add this line }Step 4: Override
onActivityResultmethod:@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == LOCATION_SETTINGS_REQUEST) { if (resultCode == RESULT_OK) { // The user accepted to turn on the location } else { // The user didn't accept to turn on the location } } }Now, when you run the app, it will prompt the user to turn on their location if it's not already enabled.