0

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

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

PS:我的服务是这样的:

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


}
4

1 回答 1

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

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

于 2016-12-26T17:11:58.860 回答