Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

i'm traying to implement google activty recognition api to to detect my activity i have…

  1. User

    i'm traying to implement google activty recognition api to to detect my activity i have those classes the app works in the android studio emulator (it detect activity) but not workin on my phone : import android.Manifest; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.widget.Toast;

    import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.app.ActivityCompat;

    import com.google.android.gms.location.ActivityRecognition; import com.google.android.gms.location.ActivityRecognitionClient; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task;

    public class BackgroundDetectedActivity extends Service {

    private PendingIntent pendingIntent;
    private ActivityRecognitionClient activityRecognitionClient;
    
    IBinder binder = new LocalBinder();
    
    public class LocalBinder extends Binder {
    
        public BackgroundDetectedActivity getServerInstance() {
            return BackgroundDetectedActivity.this;
        }
    }
    
    public BackgroundDetectedActivity() {
    
    }
    
    @SuppressLint("UnspecifiedImmutableFlag")
    @Override
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void onCreate() {
        super.onCreate();
        activityRecognitionClient = ActivityRecognition.getClient(this);
        Intent intentService = new Intent(this, ActivityRecognitionService.class);
       // pendingIntent = PendingIntent.getService(this, 1, intentService, PendingIntent.FLAG_UPDATE_CURRENT);
        pendingIntent = PendingIntent.getService(this, 1, intentService, PendingIntent.FLAG_UPDATE_CURRENT);
        requestActivityUpdatesButtonHandler();
    }
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }
    
    public void requestActivityUpdatesButtonHandler() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Task<Void> task = activityRecognitionClient.requestActivityUpdates(1000, pendingIntent);
        task.addOnSuccessListener(new OnSuccessListener<Void>() {
    
            @Override
            public void onSuccess(Void result) {
                Toast.makeText(getApplicationContext(), "Mises à jour d'activité demandées avec succès", Toast.LENGTH_SHORT).show();
            }
        });
    
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getApplicationContext(), "La demande de mises à jour d'activité n'a pas pu démarrer", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        removeActivityUpdate();
    }
    
    public void removeActivityUpdate() {
        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.
            return;
        }
        Task<Void> task = activityRecognitionClient.removeActivityUpdates(pendingIntent);
    
        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void result) {
                Toast.makeText(getApplicationContext(), "Mises à jour d'activité supprimées avec succès !", Toast.LENGTH_SHORT).show();
            }
        });
    
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getApplicationContext(), "Échec de la suppression des mises à jour d'activité!", Toast.LENGTH_SHORT).show();
            }
        });
    }
    

    }

    import static android.content.ContentValues.TAG;

    import android.app.IntentService; import android.content.Intent; import android.util.Log;

    import androidx.localbroadcastmanager.content.LocalBroadcastManager;

    import com.google.android.gms.location.ActivityRecognitionResult; import com.google.android.gms.location.DetectedActivity;

    import java.util.ArrayList;

    public class ActivityRecognitionService extends IntentService {

    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);
    }
    

    }

    @RequiresApi(api = Build.VERSION_CODES.Q) public class ActivityConfidenceActivity extends AppCompatActivity { private Button btnStart, btnStop; private TextView txt_activity, txt_confidence; private ImageView img_activity; DatabaseHelper db; String email;

    private BroadcastReceiver activityReceiver;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confidence);
        txt_activity = findViewById(R.id.txt_activity);
        txt_confidence = findViewById(R.id.txt_confidence);
        img_activity = findViewById(R.id.img_activity);
        btnStart = findViewById(R.id.btn_start);
        btnStop = findViewById(R.id.btn_stop);
        db = new DatabaseHelper(this);
        if (ActivityCompat.checkSelfPermission(ActivityConfidenceActivity.this,
                Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED) {
            // When permission grated
            // call Method
            btnStart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    txt_activity.setText("starting the service may take a while  ...");
                    txt_confidence.setText("");
                    img_activity.setImageResource(0);
                    requestActivityUpdates();
    
                }
    
            });
    
        } else {
            // When permission denied
            // Request permission
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.ACTIVITY_RECOGNITION
            }, 44);
        }
    
    
        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
                handleUserActivity(type, confidence);
    
    
            }
        };
    
        btnStop.setOnClickListener((v) -> {
                    Intent intent1 = new Intent(ActivityConfidenceActivity.this, BackgroundDetectedActivity.class);
                    stopService(intent1);
                    txt_activity.setText("Service stopped");
                    txt_confidence.setText("To start the service click on start button");
                    img_activity.setImageResource(0);
                    if (!TextUtils.isEmpty(db.getLastActivity()[4])){
                        db.updateEndDate(new Date().toString(),Long.parseLong(db.getLastActivity()[0]));
                    }
    
                }
        );
    }
    
    
    private void handleUserActivity(int type, int confidence) {
        String label = "unknown";
        int icon = R.drawable.activity_unknown;
        switch (type) {
            case DetectedActivity.IN_VEHICLE: {
                icon = R.drawable.activity_driving;
                label = "in_vehicle";
                break;
            }
            case DetectedActivity.ON_BICYCLE: {
                icon = R.drawable.activity_on_bicycle;
                label = "on_bicycle";
                break;
            }
            case DetectedActivity.ON_FOOT: {
                icon = R.drawable.activity_jumpping;
                label = "on_foot";
                break;
            }
    
            case DetectedActivity.RUNNING: {
                icon = R.drawable.activity_running;
                label = "running";
                break;
            }
            case DetectedActivity.STILL: {
                icon = R.drawable.activity_still;
                label = "still";
                break;
            }
            case DetectedActivity.WALKING: {
                icon = R.drawable.activity_walking;
                label = "walking";
                break;
            }
            case DetectedActivity.UNKNOWN: {
                icon = R.drawable.activity_unknown;
                label = "unknown";
                break;
            }
        }
        Log.d("ActivityUpdate", "User activity: " + label + ", Confidence: " + confidence);
    
        if (confidence > 50) {
            txt_activity.setText(label);
            txt_confidence.setText("" + confidence);
            img_activity.setImageResource(icon);
    
            if(!TextUtils.isEmpty(label)){
              String []data=  db.getLastActivity();
              if(data[4]=="" && !data[2].equals(label)){
                  db.updateEndDate(new Date().toString(),Long.parseLong(data[0]));
                  db.addActivity(new Activity(email,label,new Date().toString(),""));
              }else{
                  db.addActivity(new Activity(email,label,new Date().toString(),""));
              }
            }
    
            // notification
            NotificationCompat.Builder builder = new NotificationCompat.Builder(ActivityConfidenceActivity.this, NotificationManager.EXTRA_NOTIFICATION_CHANNEL_GROUP_ID)
                    .setSmallIcon(icon)
                    .setContentTitle("Activity changed")
                    .setContentText("Activity changed to " + label + " with confidence " + confidence + "%")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(ActivityConfidenceActivity.this);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "permession den", Toast.LENGTH_SHORT).show();
                return;
            }
            notificationManager.notify(0, builder.build());
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter("activity_intent"));
    }
    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(activityReceiver);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 44) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
              return;
            }
        }
    }
    
    private void requestActivityUpdates() {
        Intent intent1 = new Intent(ActivityConfidenceActivity.this, BackgroundDetectedActivity.class);
        startService(intent1);
    }
    

    }

  2. Assistant

    It appears that your code doesn't have any major issues and it should work properly on a real device. However, it's possible that there might be some device-specific or configuration issues that are causing the app to not work on your phone.

    To debug the issue, you can try the following steps:

    1. Ensure that your phone has the necessary permissions granted. Go to your phone's Settings > Apps > Your App > Permissions, and make sure that the "Physical activity" permission is enabled.

    2. Check the logcat for any errors, warnings, or messages related to your app. You can use Android Studio Logcat (View > Tool Windows > Logcat) for this purpose. Filtering logcat messages with your app's package name or the tags (e.g., "ActivityUpdate") can help you find relevant logs.

    3. Test the app on other devices to rule out a device-specific issue. If possible, try testing the app on different Android phones and different Android versions.

    4. Verify that Google Play Services is up-to-date on your phone. Google Play Services should be installed and updated for the Location API to work correctly. You can check the version of Google Play Services in your phone's Settings > Apps > Google Play Services.

    5. Make sure that location services are enabled on your phone. Some APIs might need location services to work correctly.

    If none of these suggestions work, consider providing more information about your phone's model, Android version, and any error messages you encounter so that the issue can be narrowed down further.

  3. User

    i check out all those seggestons still not work on my phone even in the emulator it take a lots time to detect is there any way to decrease the response time

  4. Assistant

    Decreasing the response time for activity recognition might not always be possible, as it depends on Google Play Services and the device's capabilities. However, you can try these options to potentially optimize the response time:

    1. Increase the activity recognition update interval: In your BackgroundDetectedActivity class, change the activity recognition request interval to a lower value. Currently, it's set to 1000ms (1 second).
    Task<Void> task = activityRecognitionClient.requestActivityUpdates(1000, pendingIntent);
    

    Change the value to a lower one, for example, 500ms:

    Task<Void> task = activityRecognitionClient.requestActivityUpdates(500, pendingIntent);
    

    Keep in mind that decreasing the interval might increase battery usage.

    1. Optimize your BroadcastReceiver: Ensure that your BroadcastReceiver's onReceive method is optimized and doesn't perform any long-running or heavy operations, as this could affect the responsiveness of the app.

    2. Use a foreground service: A foreground service is less likely to be killed by the Android system when resources are low. You can convert your BackgroundDetectedActivity class into a foreground service by using startForeground method. Although this will show a persistent notification to the user, it might help with responsiveness.

    3. Manage device power settings: Some devices have aggressive battery optimization settings that can affect the performance of background services. Ensure that your app is exempt from any battery optimization settings on the device.

    Keep in mind that responsiveness may still vary depending on the device and its capabilities. In some cases, it may be normal for the activity recognition to take some time to provide accurate results.

  5. User

    can you provide me a code source to create an interface android (.java and .xml) that containt 4 TextView still, running, walking , jumping ad it give the confidence for each one using sensors (provide the code)

  6. Assistant

    Here is a basic Android layout file containing 4 TextViews for still, running, walking, and jumping, along with another 4 TextViews to display the confidence for each activity:

    activity_main.xml:

    <?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/tv_still"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Still" />
    
        <TextView
            android:id="@+id/tv_still_confidence"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Confidence: " />
    
        <TextView
            android:id="@+id/tv_running"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Running" />
    
        <TextView
            android:id="@+id/tv_running_confidence"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Confidence: " />
    
        <TextView
            android:id="@+id/tv_walking"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Walking" />
    
        <TextView
            android:id="@+id/tv_walking_confidence"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Confidence: " />
    
        <TextView
            android:id="@+id/tv_jumping"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Jumping" />
    
        <TextView
            android:id="@+id/tv_jumping_confidence"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Confidence: " />
    </LinearLayout>
    

    MainActivity.java:

    package com.example.myactivityrecognition;
    
    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.os.Bundle;
    import android.widget.TextView;
    
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.app.ActivityCompat;
    
    public class MainActivity extends AppCompatActivity {
    
        TextView tvStill, tvStillConfidence, tvRunning, tvRunningConfidence, tvWalking, tvWalkingConfidence, tvJumping, tvJumpingConfidence;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tvStill = findViewById(R.id.tv_still);
            tvStillConfidence = findViewById(R.id.tv_still_confidence);
            tvRunning = findViewById(R.id.tv_running);
            tvRunningConfidence = findViewById(R.id.tv_running_confidence);
            tvWalking = findViewById(R.id.tv_walking);
            tvWalkingConfidence = findViewById(R.id.tv_walking_confidence);
            tvJumping = findViewById(R.id.tv_jumping);
            tvJumpingConfidence = findViewById(R.id.tv_jumping_confidence);
    
            // Request ACTIVITY_RECOGNITION permission if not granted
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, 44);
            }
    
            // Your sensor code to detect activities and update confidence values
            // Update the TextViews with confidence values when the activity recognition results are received
        }
    }
    

    Replace the "Your sensor code to detect activities and update confidence values" comment with your activity recognition logic using the available sensors on your device. Once you have detected the activities and their confidence values, update the corresponding TextViews accordingly.

    Note that the Google Activity Recognition API as mentioned in your previous code is recommended for activity detection instead of manually using device sensors. But if you would like to create a custom solution, you can use Android Sensor API to access device sensors like accelerometer and gyroscope and then analyze the sensor data to recognize the activities. This process can be complex and requires a good understanding of signal processing and machine learning approaches to detect activities reliably.

  7. User

    give from your choice a logic of how implement // Your sensor code to detect activities and update confidence values // Update the TextViews with confidence values when the activity recognition results are received

  8. Assistant

    Implementing custom activity recognition logic using the Android Sensor API requires a good understanding of signal processing and machine learning approaches. However, to provide you with a basic understanding of how you can do this, here's an example that uses the accelerometer sensor to detect if the user is walking or still:

    MainActivity.java (add this code to the onCreate method after the comment "Your sensor code to detect activities..."):

    final SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    final Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    final float alpha = 0.8f;
    final float[] gravity = new float[3];
    final float[] linearAcceleration = new float[3];
    final float threshold = 1.0f;
    
    SensorEventListener accelerometerListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            // Remove gravity contribution with a high-pass filter
            gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
            gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
            gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
    
            linearAcceleration[0] = event.values[0] - gravity[0];
            linearAcceleration[1] = event.values[1] - gravity[1];
            linearAcceleration[2] = event.values[2] - gravity[2];
    
            float magnitude = (float) Math.sqrt(Math.pow(linearAcceleration[0], 2) +
                    Math.pow(linearAcceleration[1], 2) +
                    Math.pow(linearAcceleration[2], 2));
    
            if (magnitude > threshold) {
                tvWalkingConfidence.setText("Confidence: High");
                tvStillConfidence.setText("Confidence: Low");
            } else {
                tvWalkingConfidence.setText("Confidence: Low");
                tvStillConfidence.setText("Confidence: High");
            }
        }
    
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // We don't need to do anything when accuracy changes
        }
    };
    
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED) {
        sensorManager.registerListener(accelerometerListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, 44);
    }
    

    This code registers a SensorEventListener for the accelerometer sensor and calculates the linear acceleration by excluding the gravity component using a high-pass filter. Then, it calculates the magnitude of acceleration and compares it with a threshold value. If the magnitude is greater than the threshold, the activity is considered as walking, otherwise, it's considered as still.

    Keep in mind that this is a basic example, and it's not a reliable or efficient way to recognize activities. In a real-world application, you should use more advanced techniques like machine learning models to analyze the sensor data and recognize activities. Also, as previously mentioned, Google's Activity Recognition API is recommended for recognizing activities reliably.