计算后台服务的时间

时间:2017-12-19 14:53:18

标签: java android android-service

我已经创建了一个正在运行的应用程序,为此,我已经创建了一个Service类来更新用户位置(删除了不重要的代码):

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, ILocationConstants {

    private static final String TAG = LocationService.class.getSimpleName();
    protected GoogleApiClient mGoogleApiClient;
    protected LocationRequest mLocationRequest;

    private LocationData data;

    @Override
    public void onCreate() {
        super.onCreate();

        data = new LocationData();

        startForeground();
    }

    private void startForeground() {
        //BUIDLING A NOTIFICATION

        startForeground(101, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        data = Parcels.unwrap(intent.getParcelableExtra(LOCATION_MESSAGE));

        buildGoogleApiClient();

        mGoogleApiClient.connect();

        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }

        return START_STICKY;
    }

    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        createLocationRequest();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();

        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void startLocationUpdates() {

        try {

            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);

        } catch (SecurityException ex) {


        } catch (Exception e) {

        }
    }

    private void sendUpdates() {

        data.millisecondTime = SystemClock.uptimeMillis() - data.startTime;
        data.updateTime = data.timeBuff + data.millisecondTime;
        data.seconds = (int) (data.updateTime / 1000);
        data.minutes = data.seconds / 60;
        data.hours = data.minutes / 60;
        data.minutes = data.minutes % 60;
        data.seconds = data.seconds % 60;
        data.milliSeconds = (int) (data.updateTime % 1000);

        Intent locationIntent = new Intent();
        locationIntent.setAction(LOACTION_ACTION);
        locationIntent.putExtra(LOCATION_MESSAGE, Parcels.wrap(data));

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

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    @Override
    public void onDestroy() {
        stopLocationUpdates();

        mGoogleApiClient.disconnect();

        super.onDestroy();
    }

    @Override
    public void onConnected(Bundle connectionHint) throws SecurityException {
        Log.i(TAG, "Connected to GoogleApiClient");

        if (data.mLastLocation == null) {
            data.mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            sendUpdates();
        }

        startLocationUpdates();

    }

    @Override
    public void onLocationChanged(Location location) {

        sendLocationChanged(location);

        Log.d(TAG, "onLocationChanged: " + location.getLatitude() + ", " + location.getLongitude());

        sendUpdates();

    }

    public void sendLocationChanged(Location location) {
        //SEND DATA TO THE SERVER
    }

    @Override
    public void onConnectionSuspended(int cause) {

        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

}

在每次位置更新后,我还计算经过的时间(我必须通过添加来完成此操作,因为用户可能暂停活动)。问题是我在办公室运行应用程序的时间是准确的(例如35分钟),但是当我骑自行车的时间太短时(显示15分钟,实际上约30分钟过去)。对于时间的推移,唯一的区别是它被更频繁地调用(在办公室gps中每次只刷新10-20秒,但外部甚至可以每2秒刷新一次)。路线和距离很好 - 服务没有被杀死或类似的东西。我也在更新活动时间,但是在每次更新时用广播(按服务)时间替换它,但即使删除它也没有解决问题。为什么会这样?

2 个答案:

答案 0 :(得分:1)

SystemClock documentation中所述,

  自引导系统以来,

uptimeMillis()以毫秒为单位计算。   当系统进入深度睡眠状态时此时钟停止(CPU关闭,显示   黑暗,设备等待外部输入)

这可能是你得到不同时代的原因。另一方面,有elapsedRealtime()elapsedRealtimeNanos()方法,

  

返回自系统启动以来的时间,并包括深度睡眠。   这个时钟保证是单调的,并且继续打勾   当CPU处于省电模式时,建议的基础也是如此   通用间隔时间

尝试使用其中一个。

答案 1 :(得分:0)

我建议您使用 onLocationChanged()中的每个位置更新时间,并将其传递给 sendUpdates()方法

int elapsedSeconds=int((currentTime-data.StartTime)/1000);
data.hours=int(elapsedSeconds/3600);
data.minutes=int(elapsedSeconds/60)-60*data.hours;
data.seconds=elapsedSeconds-60*(data.minutes+60*data.hours);

然后在 sendUpdates(long currentTime)进行时间计算。如果我理解正确,您只对应用程序启动后经过的时间感兴趣。在这种情况下,我猜你可以通过仅使用data.startTime,data.seconds,data.minutes和data.hours来简化你的数据对象。您可以从应用程序启动后的第一个修复位置获取开始时间(使用标记或类似方法检测第一个修复)。

然后在 sendUpdates(long currentTime)中,我会像这样计算经过时间的秒,分,小时:

"content":[" \n \n date 2008-11-13T13:35:51Z  \n pdf:PDFVersion 1.3  \n xmp:CreatorTool Microsoft Word  \n stream_content_type application/pdf  \n Keywords solr, word, pdf  \n access_permission:modify_annotations true  \n access_permission:can_print_degraded true  \n subject solr word  \n AAPL:Keywords solr, word, pdf  \n dc:creator Grant Ingersoll  \n dcterms:created 2008-11-13T13:35:51Z  \n Last-Modified 2008-11-13T13:35:51Z  \n dcterms:modified 2008-11-13T13:35:51Z  \n dc:format application/pdf; version=1.3  \n Last-Save-Date 2008-11-13T13:35:51Z  \n access_permission:fill_in_form true  \n meta:save-date 2008-11-13T13:35:51Z  \n pdf:encrypted false  \n dc:title solr-word  \n modified 2008-11-13T13:35:51Z  \n cp:subject solr word  \n Content-Type application/pdf  \n stream_size 21052  \n X-Parsed-By org.apache.tika.parser.DefaultParser  \n X-Parsed-By org.apache.tika.parser.pdf.PDFParser  \n creator Grant Ingersoll  \n meta:author Grant Ingersoll  \n dc:subject solr, word, pdf  \n meta:creation-date 2008-11-13T13:35:51Z  \n created Thu Nov 13 13:35:51 UTC 2008  \n access_permission:extract_for_accessibility true  \n access_permission:assemble_document true  \n xmpTPg:NPages 1  \n Creation-Date 2008-11-13T13:35:51Z  \n resourceName /opt/fogcutter/solr-6.6.0/example/exampledocs/solr-word.pdf  \n access_permission:extract_content true  \n access_permission:can_print true  \n meta:keyword solr, word, pdf  \n Author Grant Ingersoll  \n producer Mac OS X 10.5.5 Quartz PDFContext  \n access_permission:can_modify true  \n solr-word \n \n  page   \n This is a test of PDF and Word extraction in Solr, it is only a test.  Do not panic.  \n  \n \n  "],