Java Code Examples for android.os.SystemClock#elapsedRealtimeNanos()

The following examples show how to use android.os.SystemClock#elapsedRealtimeNanos() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BackgroundJobsController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void updateJobRestrictionsLocked(int filterUid, int newActiveState) {
    final UpdateJobFunctor updateTrackedJobs = new UpdateJobFunctor(newActiveState);

    final long start = DEBUG ? SystemClock.elapsedRealtimeNanos() : 0;

    final JobStore store = mService.getJobStore();
    if (filterUid > 0) {
        store.forEachJobForSourceUid(filterUid, updateTrackedJobs);
    } else {
        store.forEachJob(updateTrackedJobs);
    }

    final long time = DEBUG ? (SystemClock.elapsedRealtimeNanos() - start) : 0;
    if (DEBUG) {
        Slog.d(TAG, String.format(
                "Job status updated: %d/%d checked/total jobs, %d us",
                updateTrackedJobs.mCheckedCount,
                updateTrackedJobs.mTotalCount,
                (time / 1000)
                ));
    }

    if (updateTrackedJobs.mChanged) {
        mStateChangedListener.onControllerStateChanged();
    }
}
 
Example 2
Source File: HARecognizerApiLogger.java    From DataLogger with MIT License 6 votes vote down vote up
public void logDetectedActivities (ArrayList<DetectedActivity> detectedActivities){
    HashMap<Integer, Integer> detectedActivitiesMap = new HashMap<>();
    for (DetectedActivity activity : detectedActivities) {
        detectedActivitiesMap.put(activity.getType(), activity.getConfidence());
    }

    // Timestamp in system nanoseconds since boot, including time spent in sleep.
    long nanoTime = SystemClock.elapsedRealtimeNanos() + mNanosOffset;

    // System local time in millis
    long currentMillis = (new Date()).getTime();

    String message = String.format("%s", currentMillis) + ";"
            + String.format("%s", nanoTime) + ";"
            + String.format("%s", mNanosOffset);
    for (int i = 0; i < Constants.API_ACTIVITY_RECOGNIZER_LIST.length; i++) {
        message += ";" + Integer.toString(
                detectedActivitiesMap.containsKey(Constants.API_ACTIVITY_RECOGNIZER_LIST[i]) ?
                        detectedActivitiesMap.get(Constants.API_ACTIVITY_RECOGNIZER_LIST[i]) : 0);
    }

    log(message);
    log(System.lineSeparator());
}
 
Example 3
Source File: ScanResultAdapter.java    From connectivity-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Takes in a number of nanoseconds and returns a human-readable string giving a vague
 * description of how long ago that was.
 */
public static String getTimeSinceString(Context context, long timeNanoseconds) {
    String lastSeenText = context.getResources().getString(R.string.last_seen) + " ";

    long timeSince = SystemClock.elapsedRealtimeNanos() - timeNanoseconds;
    long secondsSince = TimeUnit.SECONDS.convert(timeSince, TimeUnit.NANOSECONDS);

    if (secondsSince < 5) {
        lastSeenText += context.getResources().getString(R.string.just_now);
    } else if (secondsSince < 60) {
        lastSeenText += secondsSince + " " + context.getResources()
                .getString(R.string.seconds_ago);
    } else {
        long minutesSince = TimeUnit.MINUTES.convert(secondsSince, TimeUnit.SECONDS);
        if (minutesSince < 60) {
            if (minutesSince == 1) {
                lastSeenText += minutesSince + " " + context.getResources()
                        .getString(R.string.minute_ago);
            } else {
                lastSeenText += minutesSince + " " + context.getResources()
                        .getString(R.string.minutes_ago);
            }
        } else {
            long hoursSince = TimeUnit.HOURS.convert(minutesSince, TimeUnit.MINUTES);
            if (hoursSince == 1) {
                lastSeenText += hoursSince + " " + context.getResources()
                        .getString(R.string.hour_ago);
            } else {
                lastSeenText += hoursSince + " " + context.getResources()
                        .getString(R.string.hours_ago);
            }
        }
    }

    return lastSeenText;
}
 
Example 4
Source File: StatsCompanionService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void pullBluetoothActivityInfo(int tagId, List<StatsLogEventWrapper> pulledData) {
    BluetoothActivityEnergyInfo info = pullBluetoothData();
    StatsLogEventWrapper e = new StatsLogEventWrapper(SystemClock.elapsedRealtimeNanos(), tagId, 6);
    e.writeLong(info.getTimeStamp());
    e.writeInt(info.getBluetoothStackState());
    e.writeLong(info.getControllerTxTimeMillis());
    e.writeLong(info.getControllerRxTimeMillis());
    e.writeLong(info.getControllerIdleTimeMillis());
    e.writeLong(info.getControllerEnergyUsed());
    pulledData.add(e);
}
 
Example 5
Source File: QuickActivity.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
@Override
protected final void onCreate(Bundle bundle)
{
    mExecutionStartNanoTime = SystemClock.elapsedRealtimeNanos();
    logLifecycle("onCreate", true);
    mStartupOnCreate = true;
    super.onCreate(bundle);
    mMainHandler = new Handler(getMainLooper());
    onCreateTasks(bundle);
    logLifecycle("onCreate", false);
}
 
Example 6
Source File: DeviceLocation.java    From ARCore-Location with MIT License 5 votes vote down vote up
private long getLocationAge(Location newLocation) {
    long locationAge;
    if (android.os.Build.VERSION.SDK_INT >= 17) {
        long currentTimeInMilli = (long) (SystemClock.elapsedRealtimeNanos() / 1000000);
        long locationTimeInMilli = (long) (newLocation.getElapsedRealtimeNanos() / 1000000);
        locationAge = currentTimeInMilli - locationTimeInMilli;
    } else {
        locationAge = System.currentTimeMillis() - newLocation.getTime();
    }
    return locationAge;
}
 
Example 7
Source File: LogTime.java    From HttpInfo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the current time in either millis or nanos depending on the api level to be used with
 * {@link #getElapsedMillis(long)}.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static long getLogTime() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    return SystemClock.elapsedRealtimeNanos();
  } else {
    return SystemClock.uptimeMillis();
  }
}
 
Example 8
Source File: Observation.java    From DejaVu with GNU General Public License v3.0 5 votes vote down vote up
Observation(String id, RfEmitter.EmitterType t) {
    ident = new RfIdentification(id, t);
    note = "";
    asu = BackendService.MINIMUM_ASU;
    mLastUpdateTimeMs = System.currentTimeMillis();
    mElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();
}
 
Example 9
Source File: WiFiDataCollector.java    From DataLogger with MIT License 5 votes vote down vote up
private void logWifiInfo(List<ScanResult> scanList){
    // System local time in millis
    long currentMillis = (new Date()).getTime();

    // System nanoseconds since boot, including time spent in sleep.
    long nanoTime = SystemClock.elapsedRealtimeNanos() + mNanosOffset;

    String message = String.format("%s", currentMillis) + ";"
            + String.format("%s", nanoTime) + ";"
            + String.format("%s", mNanosOffset) + ";"
            + scanList.size();

    for (ScanResult scan : scanList){

        // The address of the access point.
        String BSSID = scan.BSSID;

        // The network name.
        String SSID = scan.SSID;

        // The detected signal level in dBm, also known as the RSSI.
        int level = scan.level;

        // The primary 20 MHz frequency (in MHz) of the channel over which the client is communicating with the access point.
        int frequency = scan.frequency;

        // Describes the authentication, key management, and encryption schemes supported by the access point.
        String capabilities = scan.capabilities;

        message += ";"
                + BSSID + ";"
                + SSID + ";"
                + level + ";"
                + frequency + ";"
                + capabilities;
    }

    logger.log(message);
    logger.log(System.lineSeparator());
}
 
Example 10
Source File: StatsCompanionService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void pullKernelWakelock(int tagId, List<StatsLogEventWrapper> pulledData) {
    final KernelWakelockStats wakelockStats =
            mKernelWakelockReader.readKernelWakelockStats(mTmpWakelockStats);
    long elapsedNanos = SystemClock.elapsedRealtimeNanos();
    for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
        String name = ent.getKey();
        KernelWakelockStats.Entry kws = ent.getValue();
        StatsLogEventWrapper e = new StatsLogEventWrapper(elapsedNanos, tagId, 4);
        e.writeString(name);
        e.writeInt(kws.mCount);
        e.writeInt(kws.mVersion);
        e.writeLong(kws.mTotalTime);
        pulledData.add(e);
    }
}
 
Example 11
Source File: StatsCompanionService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void pullBluetoothBytesTransfer(int tagId, List<StatsLogEventWrapper> pulledData) {
    BluetoothActivityEnergyInfo info = pullBluetoothData();
    long elapsedNanos = SystemClock.elapsedRealtimeNanos();
    if (info.getUidTraffic() != null) {
        for (UidTraffic traffic : info.getUidTraffic()) {
            StatsLogEventWrapper e = new StatsLogEventWrapper(elapsedNanos, tagId, 3);
            e.writeInt(traffic.getUid());
            e.writeLong(traffic.getRxBytes());
            e.writeLong(traffic.getTxBytes());
            pulledData.add(e);
        }
    }
}
 
Example 12
Source File: SoundRecorder.java    From AAVT with Apache License 2.0 5 votes vote down vote up
private synchronized boolean audioEncodeStep(boolean isEnd){
    if(isStarted){
        AvLog.d("audioEncodeStep");
        int inputIndex=mAudioEncoder.dequeueInputBuffer(TIME_OUT);
        if(inputIndex>=0){
            ByteBuffer buffer= CodecUtil.getInputBuffer(mAudioEncoder,inputIndex);
            buffer.clear();
            long time= (SystemClock.elapsedRealtimeNanos()-startTime)/1000;
            int length=mRecord.read(buffer,mRecordBufferSize);
            if(length>=0){
                mAudioEncoder.queueInputBuffer(inputIndex,0,length,time,
                        isEnd?MediaCodec.BUFFER_FLAG_END_OF_STREAM:0);
            }
        }
        MediaCodec.BufferInfo info=new MediaCodec.BufferInfo();
        while (true){
            int outputIndex=mAudioEncoder.dequeueOutputBuffer(info,TIME_OUT);
            if(outputIndex>=0){
                if(mStore!=null){
                    mStore.addData(mAudioTrack,new HardMediaData(CodecUtil.getOutputBuffer(mAudioEncoder,outputIndex),info));
                }
                mAudioEncoder.releaseOutputBuffer(outputIndex,false);
                if(info.flags==MediaCodec.BUFFER_FLAG_END_OF_STREAM){
                    AvLog.d("CameraRecorder get audio encode end of stream");
                    stop();
                    return true;
                }
            }else if(outputIndex==MediaCodec.INFO_TRY_AGAIN_LATER){
                break;
            }else if(outputIndex==MediaCodec.INFO_OUTPUT_FORMAT_CHANGED){
                AvLog.d("get audio output format changed ->"+mAudioEncoder.getOutputFormat().toString());
                mAudioTrack=mStore.addTrack(mAudioEncoder.getOutputFormat());
            }
        }
    }
    return false;
}
 
Example 13
Source File: ScanResultAdapter.java    From android-BluetoothAdvertisements with Apache License 2.0 5 votes vote down vote up
/**
 * Takes in a number of nanoseconds and returns a human-readable string giving a vague
 * description of how long ago that was.
 */
public static String getTimeSinceString(Context context, long timeNanoseconds) {
    String lastSeenText = context.getResources().getString(R.string.last_seen) + " ";

    long timeSince = SystemClock.elapsedRealtimeNanos() - timeNanoseconds;
    long secondsSince = TimeUnit.SECONDS.convert(timeSince, TimeUnit.NANOSECONDS);

    if (secondsSince < 5) {
        lastSeenText += context.getResources().getString(R.string.just_now);
    } else if (secondsSince < 60) {
        lastSeenText += secondsSince + " " + context.getResources()
                .getString(R.string.seconds_ago);
    } else {
        long minutesSince = TimeUnit.MINUTES.convert(secondsSince, TimeUnit.SECONDS);
        if (minutesSince < 60) {
            if (minutesSince == 1) {
                lastSeenText += minutesSince + " " + context.getResources()
                        .getString(R.string.minute_ago);
            } else {
                lastSeenText += minutesSince + " " + context.getResources()
                        .getString(R.string.minutes_ago);
            }
        } else {
            long hoursSince = TimeUnit.HOURS.convert(minutesSince, TimeUnit.MINUTES);
            if (hoursSince == 1) {
                lastSeenText += hoursSince + " " + context.getResources()
                        .getString(R.string.hour_ago);
            } else {
                lastSeenText += hoursSince + " " + context.getResources()
                        .getString(R.string.hours_ago);
            }
        }
    }

    return lastSeenText;
}
 
Example 14
Source File: HeifReader.java    From heifreader with MIT License 5 votes vote down vote up
/**
 * Decode an input stream into a bitmap.
 *
 * This method save input stream to temporary file on cache directory, because HEIF data
 * structure requires multi-pass parsing.
 *
 * @param is The input stream that holds the raw data to be decoded into a bitmap.
 * @return The decoded bitmap, or null if the image could not be decoded.
 */
public static Bitmap decodeStream(InputStream is) {
    assertPrecondition();
    try {
        // write stream to temporary file
        long beginTime = SystemClock.elapsedRealtimeNanos();
        File heifFile = File.createTempFile("heifreader", "heif", mCacheDir);
        try (FileOutputStream fos = new FileOutputStream(heifFile)) {
            byte[] buf = new byte[4096];
            int totalLength = 0;
            int len;
            while ((len = is.read(buf)) > 0) {
                fos.write(buf, 0, len);
                totalLength += len;
                if (LIMIT_FILESIZE < totalLength) {
                    Log.e(TAG, "data size exceeds limit(" + LIMIT_FILESIZE + ")");
                    return null;
                }
            }
        }
        long endTime = SystemClock.elapsedRealtimeNanos();
        Log.i(TAG, "HEIC caching elapsed=" + (endTime - beginTime) / 1000000.f + "[msec]");
        return decodeFile(heifFile.getAbsolutePath());
    } catch (IOException ex) {
        Log.e(TAG, "decodeStream failure", ex);
        return null;
    }
}
 
Example 15
Source File: StatsCompanionService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void pullSystemElapsedRealtime(int tagId, List<StatsLogEventWrapper> pulledData) {
    StatsLogEventWrapper e = new StatsLogEventWrapper(SystemClock.elapsedRealtimeNanos(), tagId, 1);
    e.writeLong(SystemClock.elapsedRealtime());
    pulledData.add(e);
}
 
Example 16
Source File: SoundRecorder.java    From AAVT with Apache License 2.0 4 votes vote down vote up
public void start(){
    if(!isStarted){
        stopFlag=false;

        mRecordBufferSize = AudioRecord.getMinBufferSize(mRecordSampleRate,
                mRecordChannelConfig, mRecordAudioFormat)*2;
        mRecord=new AudioRecord(MediaRecorder.AudioSource.MIC,mRecordSampleRate,mRecordChannelConfig,
                mRecordAudioFormat,mRecordBufferSize);
        mRecord.startRecording();
        try {
            MediaFormat format=convertAudioConfigToFormat(mConfig.mAudio);
            mAudioEncoder=MediaCodec.createEncoderByType(format.getString(MediaFormat.KEY_MIME));
            mAudioEncoder.configure(format,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
            mAudioEncoder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                while (!stopFlag&&!audioEncodeStep(false)){};
                audioEncodeStep(true);
                Log.e("wuwang","audio stop");
                if(isStarted){
                    mRecord.stop();
                    mRecord.release();
                    mRecord=null;
                }
                if(mAudioEncoder!=null){
                    mAudioEncoder.stop();
                    mAudioEncoder.release();
                    mAudioEncoder=null;
                }
                isStarted=false;
            }
        });
        thread.start();
        startTime=SystemClock.elapsedRealtimeNanos();
        isStarted=true;
    }
}
 
Example 17
Source File: GpsIconData.java    From Status with Apache License 2.0 4 votes vote down vote up
private long getElapsedTime(@NonNull Location location) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
        return location.getElapsedRealtimeNanos() - SystemClock.elapsedRealtimeNanos();
    else return location.getTime() - System.currentTimeMillis();
}
 
Example 18
Source File: BrightnessTracker.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public long elapsedRealtimeNanos() {
    return SystemClock.elapsedRealtimeNanos();
}
 
Example 19
Source File: BenchmarkUtil.java    From Dali with Apache License 2.0 4 votes vote down vote up
public static long elapsedRealTimeNanos() {
    if (Build.VERSION.SDK_INT >= 17) {
        return SystemClock.elapsedRealtimeNanos();
    }
    return SystemClock.elapsedRealtime() * 1000000L;
}
 
Example 20
Source File: PerfMeasurement.java    From android_9.0.0_r45 with Apache License 2.0 2 votes vote down vote up
/**
 * Start a GPU/CPU timing measurement.
 *
 * <p>Call before starting a rendering pass. Only one timing measurement can be active at once,
 * so {@link #stopTimer} must be called before the next call to this method.</p>
 *
 * @throws IllegalStateException if the maximum number of queries are in progress already,
 *                               or the method is called multiple times in a row, or there is
 *                               a GPU error.
 */
public void startTimer() {
    nativeStartGlTimer(mNativeContext);
    mStartTimeNs = SystemClock.elapsedRealtimeNanos();
}