activityrecognition不会每秒返回活动

时间:2018-03-05 03:02:23

标签: android

我正在开发可穿戴式应用程序,它必须在每一秒都返回识别用户活动并将其写入数据库。我在评估服务中使用ActivityRecognitionClient(是的,我不想要这样的活动),并对requestActivityUpdates(..)使用DETECTION_INTERVAL_IN_MILLISECONDS = 0,但它返回的活动结果大约是56secs。

这是代码:

        public class MovementSensorService extends AccessibilityService {
private static final String TAG = "MovementSensorService";
BroadcastReceiver broadcastReceiver;
//private Intent mIntentService;
private PendingIntent mPendingIntent;
private ActivityRecognitionClient mActivityRecognitionClient;
static final long DETECTION_INTERVAL_IN_MILLISECONDS = 0;

public static class MyServiceHandler extends IntentService {
    public MyServiceHandler() {
        super("ActivityRecognitionIntentService");
    }


    protected void onHandleIntent(Intent intent) {
//            Log.i(TAG, "inside handler");
        if(ActivityRecognitionResult.hasResult(intent)) {
//                Log.i(TAG, "intent: " 
+ActivityRecognitionResult.hasResult(intent));
            //Extract the result from the Response
            ActivityRecognitionResult result = 
ActivityRecognitionResult.extractResult(intent);
            ArrayList<DetectedActivity> detectedActivity = (ArrayList) 
result.getProbableActivities();

            //Get the Confidence and Name of Activity
            for (DetectedActivity activity : detectedActivity) {
                int confidence = activity.getConfidence();
                String mostProbableName = 
getActivityName(activity.getType());
                //Fire the intent with activity name & confidence
                Intent i = new Intent("ImActive");
                i.putExtra("activity", mostProbableName);
                i.putExtra("confidence", confidence);

//                    Log.d(TAG, "Most Probable Name : " + 
mostProbableName);
//                    Log.d(TAG, "Confidence : " + confidence);

                //Send Broadcast to be listen in MainActivity

LocalBroadcastManager.getInstance(this).sendBroadcast(i);
            }





        }else {
            Log.d(TAG, "Intent had no data returned");
        }
    }
    //Get the activity name
    private String getActivityName(int type) {
        switch (type)
        {
            case DetectedActivity.IN_VEHICLE:
                return "In Vehicle";
            case DetectedActivity.ON_BICYCLE:
                return "On Bicycle";
            case DetectedActivity.ON_FOOT:
                return "On Foot";
            case DetectedActivity.WALKING:
                return "Walking";
            case DetectedActivity.STILL:
                return "Still";
            case DetectedActivity.TILTING:
                return "Tilting";
            case DetectedActivity.RUNNING:
                return "Running";
            case DetectedActivity.UNKNOWN:
                return "Unknown";
        }
        return "N/A";
    }
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {

}

//fun to check if activity update is success or fail
public void requestActivityUpdatesButtonHandler() {
    Task<Void> task = 
mActivityRecognitionClient.requestActivityUpdates(
            DETECTION_INTERVAL_IN_MILLISECONDS,
            mPendingIntent);

    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            Toast.makeText(getApplicationContext(),
                    "Successfully requested activity updates",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(getApplicationContext(),
                    "Requesting activity updates failed to start",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    });
}
@Override
protected void onServiceConnected() {
    // Create an overlay and display the action bar
    //used to create the view for assessiblity service
    //we can do initialisations and call other methods from here
    Log.i(TAG, "inside onServiceConnected");
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("ImActive")) {
                String type = intent.getStringExtra("activity");
                int confidence = intent.getIntExtra("confidence", 0);
                Calendar rightNow = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss 
a");
                String strDate = sdf.format(rightNow.getTime());
                String v =  strDate + " " +
                        type + " " +
                        "Confidence : " + confidence + "\n";
                Log.d(TAG, v);

//                    Toast.makeText(getApplicationContext(),
//                            "activity: "+ type+"and confidence:" + 
confidence,
//                            Toast.LENGTH_SHORT)
//                            .show();
            }
        }
    };

LocalBroadcastManager.getInstance(本).registerReceiver(广播接收器     ,                 新的IntentFilter(&#34; ImActive&#34;));         mActivityRecognitionClient = new ActivityRecognitionClient(this);         Intent i = new Intent(this,MyServiceHandler.class);         mPendingIntent = PendingIntent                 .getService(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

    //Log.d(TAG, "connected to ActivityRecognition");
    requestActivityUpdatesButtonHandler();

}

@Override
public void onInterrupt() {

}
@Override
public void onDestroy() {
    super.onDestroy();
    removeActivityUpdatesButtonHandler();

LocalBroadcastManager.getInstance(本).unregisterReceiver(广播接收器);     }

//unregistering pendingIntent if user kills the service
public void removeActivityUpdatesButtonHandler() {
    Task<Void> task = mActivityRecognitionClient.removeActivityUpdates(
            mPendingIntent);
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            Toast.makeText(getApplicationContext(),
                    "Removed activity updates successfully!",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(getApplicationContext(), "Failed to remove 
activity updates!",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

您应该将DETECTION_INTERVAL_IN_MILLISECONDS设置为1000(以毫秒为单位),而不是0。我不确定是否定义了更新间隔为0ms的行为。