Android如何计算时间?

How to measure time in Android?

我正在开发一个人类 Activity 识别 Android 应用程序,我必须测量久坐(静态)时间和活动时间。起初,我想在 sharedPreferences 中存储一个 long 变量并每 5 秒递增一次(我每 5 秒对用户 activity 进行分类)增加 5000(5 秒以毫秒为单位)。

但是,当我启动我的服务时(我正在使用后台服务进行分类并将其存储在 SharedPreferences 中)并稍后检查 - 比如 2 小时后,我在 sharedPreferences 中的时间和实际过去的时间差异很大。例如,我将在中午 12 点开始我的服务并在下午 2 点检查,共享首选项中的值大约为 40 分钟(从毫秒转换为 - value/1000/60 分钟)。

P.S.: 我的服务是这样的:

public class MyService extends Service implements SensorEventListener {
public static final String COUNTER_KEY = "counterKey3";
public int counter = 0;
private static final long WINDOW_LENGTH = 5000;
private long windowBegTime = -1;
private SensorManager mSensorManager;
private Sensor accSensor;
private ArrayList<Double> xValues = new ArrayList<>();
private ArrayList<Double> yValues = new ArrayList<>();
private ArrayList<Double> zValues = new ArrayList<>();

private SharedPreferences mSharedPreferences;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mSensorManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_GAME);
    return START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();
    mSharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
    counter = mSharedPreferences.getInt(COUNTER_KEY, 0);

}


@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    xValues.add((double) sensorEvent.values[0]);
    yValues.add((double) sensorEvent.values[1]);
    zValues.add((double) sensorEvent.values[2]);

    if (SystemClock.elapsedRealtime() - windowBegTime > WINDOW_LENGTH) {
        if (windowBegTime > 0) {
            mSharedPreferences.edit().putInt(COUNTER_KEY, mSharedPreferences.getInt(COUNTER_KEY, 0) + 5).apply();
            Log.i("MyService", "WindowTimeIssue! " + mSharedPreferences.getInt(COUNTER_KEY, 0));
                // DETECT ACTIVITY - store it in a db

        }

        windowBegTime = SystemClock.elapsedRealtime();
    }
}


}

您需要将您的服务设为前台服务。当需要资源时,后台服务被 OS 终止。

Intent intent = new Intent(this, MyActivityApp.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,   PendingIntent.FLAG_UPDATE_CURRENT);    

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setSmallIcon(Resource.Drawable.my_icon);
    builder.setTicker("My Activity App");
    builder.setContentIntent(pi);
    builder.setOngoing(true);
    builder.setOnlyAlertOnce(true);

    Notification notification = builder.build();   
    startForeground(SERVICE_NOTIFICATION_ID, notification);

此外,您应该查看 Activity 识别 API (https://developers.google.com/android/reference/com/google/android/gms/location/ActivityRecognitionApi)