2016-12-26 66 views
0

我正在開發一個人類活動識別android應用程序,我必須測量時間久坐(靜態)和花費時間。起初,我希望在sharedPreferences中存儲一個長變量,並每5秒增加一次(我每5秒對用戶活動進行分類)5000(5毫秒)。然而,現在,當我開始我的服務時(我使用後臺服務來執行分類並將其存儲在SharedPreferences中)並在稍後的時間點檢查 - 比如2小時後,我在sharedPreferences中的時間和實際通過差異的時間顯着。例如,我會在晚上12點開始我的服務,並在下午2點檢查,共享偏好的值將是40分鐘左右(當濃度前面毫秒 - 值/ 1000/60分鐘)時。我將不勝感激關於如何以上述方式測量時間的任何想法。先謝謝你!如何在Android中測量時間?

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

你需要讓你的服務前臺服務。後臺服務在需要資源時被操作系統殺死。

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

+0

謝謝您的回答!我將定義考慮將我的服務改爲預訂服務。至於活動識別API。我沒有使用它,因爲我的申請將被設計爲承認不活動(對於久坐的人)而不是積極。這就是爲什麼我使用weka for android實現我自己的活動識別系統。 –