如何在Android中测量时间?

时间:2016-12-26 16:35:26

标签: android android-timer

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

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


}

1 个答案:

答案 0 :(得分:1)

您需要将服务作为前台服务。当需要资源时,后台服务会被操作系统杀死。

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

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