Example usage for android.os SystemClock uptimeMillis

List of usage examples for android.os SystemClock uptimeMillis

Introduction

In this page you can find the example usage for android.os SystemClock uptimeMillis.

Prototype

@CriticalNative
native public static long uptimeMillis();

Source Link

Document

Returns milliseconds since boot, not counting time spent in deep sleep.

Usage

From source file:com.android.strictmodetest.StrictModeActivity.java

/** Called when the activity is first created. */
@Override/*from   www  .  j  a  v  a2s.c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    cr = getContentResolver();
    final SQLiteDatabase db = openOrCreateDatabase("foo.db", MODE_PRIVATE, null);

    final Button readButton = (Button) findViewById(R.id.read_button);
    readButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Cursor c = null;
            try {
                c = db.rawQuery("SELECT * FROM foo", null);
            } finally {
                if (c != null)
                    c.close();
            }
        }
    });

    final Button writeButton = (Button) findViewById(R.id.write_button);
    writeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
        }
    });

    final Button writeLoopButton = (Button) findViewById(R.id.write_loop_button);
    writeLoopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            long startTime = SystemClock.uptimeMillis();
            int iters = 1000;
            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
            for (int i = 0; i < iters; ++i) {
                policy.onWriteToDisk();
            }
            long endTime = SystemClock.uptimeMillis();
            Log.d(TAG, "Time for " + iters + ": " + (endTime - startTime) + ", avg="
                    + (endTime - startTime) / (double) iters);
        }
    });

    final Button dnsButton = (Button) findViewById(R.id.dns_button);
    dnsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "Doing DNS lookup for www.l.google.com... " + "(may be cached by InetAddress)");
            try {
                InetAddress[] addrs = InetAddress.getAllByName("www.l.google.com");
                for (int i = 0; i < addrs.length; ++i) {
                    Log.d(TAG, "got: " + addrs[i]);
                }
            } catch (java.net.UnknownHostException e) {
                Log.d(TAG, "DNS error: " + e);
            }
        }
    });

    final Button httpButton = (Button) findViewById(R.id.http_button);
    httpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Note: not using AndroidHttpClient, as that comes with its
                // own pre-StrictMode network-on-Looper thread check.  The
                // intent of this test is that we test the network stack's
                // instrumentation for StrictMode instead.
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse res = httpClient.execute(new HttpGet("http://www.android.com/favicon.ico"));
                Log.d(TAG, "Fetched http response: " + res);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http2Button = (Button) findViewById(R.id.http2_button);
    http2Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Usually this ends up tripping in DNS resolution,
                // so see http3Button below, which connects directly to an IP
                InputStream is = new URL("http://www.android.com/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http3Button = (Button) findViewById(R.id.http3_button);
    http3Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // One of Google's web IPs, as of 2010-06-16....
                InputStream is = new URL("http://74.125.19.14/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button binderLocalButton = (Button) findViewById(R.id.binder_local_button);
    binderLocalButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mLocalServiceConn.stub.doDiskWrite(123 /* dummy */);
                Log.d(TAG, "local writeToDisk returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "local binderButton error: " + e);
            }
        }
    });

    final Button binderRemoteButton = (Button) findViewById(R.id.binder_remote_button);
    binderRemoteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mRemoteServiceConn.stub.doDiskWrite(1);
                Log.d(TAG, "remote writeToDisk #1 returned: " + value);
                value = mRemoteServiceConn.stub.doDiskWrite(2);
                Log.d(TAG, "remote writeToDisk #2 returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderOneWayButton = (Button) findViewById(R.id.binder_oneway_button);
    binderOneWayButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                Log.d(TAG, "doing oneway disk write over Binder.");
                mRemoteServiceConn.stub.doDiskOneWay();
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderCheckButton = (Button) findViewById(R.id.binder_check_button);
    binderCheckButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int policy;
            try {
                policy = mLocalServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "local service policy: " + policy);
                policy = mRemoteServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "remote service policy: " + policy);
            } catch (RemoteException e) {
                Log.d(TAG, "binderCheckButton error: " + e);
            }
        }
    });

    final Button serviceDumpButton = (Button) findViewById(R.id.service_dump);
    serviceDumpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "About to do a service dump...");
            File file = new File("/sdcard/strictmode-service-dump.txt");
            FileOutputStream output = null;
            final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
            try {
                StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
                output = new FileOutputStream(file);
                StrictMode.setThreadPolicy(oldPolicy);
                boolean dumped = Debug.dumpService("cpuinfo", output.getFD(), new String[0]);
                Log.d(TAG, "Dumped = " + dumped);
            } catch (IOException e) {
                Log.e(TAG, "Can't dump service", e);
            } finally {
                StrictMode.setThreadPolicy(oldPolicy);
            }
            Log.d(TAG, "Did service dump.");
        }
    });

    final Button lingerCloseButton = (Button) findViewById(R.id.linger_close_button);
    lingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(true);
        }
    });

    final Button nonlingerCloseButton = (Button) findViewById(R.id.nonlinger_close_button);
    nonlingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(false);
        }
    });

    final Button leakCursorButton = (Button) findViewById(R.id.leak_cursor_button);
    leakCursorButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            final StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
            try {
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                        .penaltyLog().penaltyDropBox().build());
                db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
                Cursor c = db.rawQuery("SELECT * FROM foo", null);
                c = null; // never close it
                Runtime.getRuntime().gc();
            } finally {
                StrictMode.setVmPolicy(oldPolicy);
            }

        }
    });

    final CheckBox checkNoWrite = (CheckBox) findViewById(R.id.policy_no_write);
    final CheckBox checkNoRead = (CheckBox) findViewById(R.id.policy_no_reads);
    final CheckBox checkNoNetwork = (CheckBox) findViewById(R.id.policy_no_network);
    final CheckBox checkPenaltyLog = (CheckBox) findViewById(R.id.policy_penalty_log);
    final CheckBox checkPenaltyDialog = (CheckBox) findViewById(R.id.policy_penalty_dialog);
    final CheckBox checkPenaltyDeath = (CheckBox) findViewById(R.id.policy_penalty_death);
    final CheckBox checkPenaltyDropBox = (CheckBox) findViewById(R.id.policy_penalty_dropbox);

    View.OnClickListener changePolicy = new View.OnClickListener() {
        public void onClick(View v) {
            StrictMode.ThreadPolicy.Builder newPolicy = new StrictMode.ThreadPolicy.Builder();
            if (checkNoWrite.isChecked())
                newPolicy.detectDiskWrites();
            if (checkNoRead.isChecked())
                newPolicy.detectDiskReads();
            if (checkNoNetwork.isChecked())
                newPolicy.detectNetwork();
            if (checkPenaltyLog.isChecked())
                newPolicy.penaltyLog();
            if (checkPenaltyDialog.isChecked())
                newPolicy.penaltyDialog();
            if (checkPenaltyDeath.isChecked())
                newPolicy.penaltyDeath();
            if (checkPenaltyDropBox.isChecked())
                newPolicy.penaltyDropBox();
            StrictMode.ThreadPolicy policy = newPolicy.build();
            Log.v(TAG, "Changing policy to: " + policy);
            StrictMode.setThreadPolicy(policy);
        }
    };
    checkNoWrite.setOnClickListener(changePolicy);
    checkNoRead.setOnClickListener(changePolicy);
    checkNoNetwork.setOnClickListener(changePolicy);
    checkPenaltyLog.setOnClickListener(changePolicy);
    checkPenaltyDialog.setOnClickListener(changePolicy);
    checkPenaltyDeath.setOnClickListener(changePolicy);
    checkPenaltyDropBox.setOnClickListener(changePolicy);
}

From source file:org.zoumbox.mh_dla_notifier.Receiver.java

protected Predicate<Context> shouldUpdateBecauseOfRestart(final String trollId) {
    Predicate<Context> predicate = new Predicate<Context>() {
        @Override/*from  w ww. j a v  a  2s .c om*/
        public boolean apply(Context context) {
            boolean result = false;
            // Check if the device restarted since last update
            Long elapsedSinceLastSuccess = getProfileProxy().getElapsedSinceLastUpdateSuccess(context, trollId);
            if (elapsedSinceLastSuccess != null) {
                Log.d(TAG, "Elapsed since last update success: " + elapsedSinceLastSuccess + "ms ~= "
                        + (elapsedSinceLastSuccess / 60000) + "min");

                long uptime = SystemClock.uptimeMillis();
                Log.d(TAG, "Uptime: " + uptime + "ms ~= " + (uptime / 60000) + "min");

                result = elapsedSinceLastSuccess > uptime; // Device restarted since last update
                Log.d(TAG, "shouldUpdateBecauseOfRestart: " + result);
                result &= elapsedSinceLastSuccess > (1000l * 60l * 60l * 2l); // 2 hours
                Log.d(TAG, "shouldUpdateBecauseOfRestart (<=2hours): " + result);
            }
            return result;
        }
    };
    return predicate;
}

From source file:com.tapcentive.sdk.touchpoint.nfc.SEManager.java

/**
 * Do tapcentive interaction.//from   w w  w  .  j  a va2  s . co  m
 *
 * @param storage the storage
 * @return the interaction response
 * @throws TapcentiveException the tapcentive exception
 */
public InteractionResponse doTapcentiveInteraction(ProfileStorage storage) throws TapcentiveException {
    long time1 = SystemClock.uptimeMillis();

    @SuppressWarnings("unused")
    String prof = storage.getProfile();

    byte[] profile = Base64.decode(storage.getProfile(), Base64.DEFAULT);
    byte[] informationCommand = new byte[5 + profile.length];

    System.arraycopy(informationHeader, 0, informationCommand, 0, 5);
    System.arraycopy(profile, 0, informationCommand, 5, profile.length);

    informationCommand[4] = (byte) (profile.length);

    byte[] responseBuffer = sendAndReceive(informationCommand);

    long time2 = SystemClock.uptimeMillis();
    Log.d(TAG, "TIME: doTapcentiveIngeraction:sendAndReceive: " + (time2 - time1));

    InteractionResponse iResponse = new InteractionResponse(responseBuffer);
    long time3 = SystemClock.uptimeMillis();
    Log.d(TAG, "TIME: do TapcentiveInteraction:new InteractionResponse: " + (time3 - time2));

    return iResponse;
}

From source file:com.example.mapdemo.VisibleRegionDemoActivity.java

public void animatePadding(final int toLeft, final int toTop, final int toRight, final int toBottom) {

    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long duration = 1000;

    final Interpolator interpolator = new OvershootInterpolator();

    final int startLeft = currentLeft;
    final int startTop = currentTop;
    final int startRight = currentRight;
    final int startBottom = currentBottom;

    currentLeft = toLeft;//from   w w w.  j  a  v a2  s  .c  om
    currentTop = toTop;
    currentRight = toRight;
    currentBottom = toBottom;

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);

            int left = (int) (startLeft + ((toLeft - startLeft) * t));
            int top = (int) (startTop + ((toTop - startTop) * t));
            int right = (int) (startRight + ((toRight - startRight) * t));
            int bottom = (int) (startBottom + ((toBottom - startBottom) * t));

            mMap.setPadding(left, top, right, bottom);

            if (elapsed < duration) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}

From source file:android.example.com.visualizerpreferences.AudioVisuals.VisualizerView.java

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);

    // Setup all the view measurement code after the view is laid out. If this is done any
    // earlier the height and width are not yet determined
    mStartTime = SystemClock.uptimeMillis();

    float viewCenterX = getWidth() / 2.f;
    float viewCenterY = getHeight() / 2.f;
    float shortSide = viewCenterX < viewCenterY ? viewCenterX : viewCenterY;
    TrailedShape.setViewCenterX(viewCenterX);
    TrailedShape.setViewCenterY(viewCenterY);

    mBassCircle.setShapeRadiusFromCenter(shortSide * RADIUS_BASS);
    mMidSquare.setShapeRadiusFromCenter(shortSide * RADIUS_MID);
    mTrebleTriangle.setShapeRadiusFromCenter(shortSide * RADIUS_TREBLE);
}

From source file:org.peterbaldwin.client.android.delicious.DeliciousApiRequest.java

private static long now() {
    return SystemClock.uptimeMillis();
}

From source file:android.support.animation.AnimationHandler.java

private void doAnimationFrame(long frameTime) {
    long currentTime = SystemClock.uptimeMillis();
    for (int i = 0; i < mAnimationCallbacks.size(); i++) {
        final AnimationFrameCallback callback = mAnimationCallbacks.get(i);
        if (callback == null) {
            continue;
        }//from   ww w. j  a v  a2 s  . co  m
        if (isCallbackDue(callback, currentTime)) {
            callback.doAnimationFrame(frameTime);
        }
    }
    cleanUpList();
}

From source file:com.kohoh.AsyncTaskLoader.java

void executePendingTask() {
    if (mCancellingTask == null && mTask != null) {
        if (mTask.waiting) {
            mTask.waiting = false;/*from  www  .  ja v  a2  s. c  o m*/
            mHandler.removeCallbacks(mTask);
        }
        if (mUpdateThrottle > 0) {
            long now = SystemClock.uptimeMillis();
            if (now < (mLastLoadCompleteTime + mUpdateThrottle)) {
                // Not yet time to do another load.
                if (DEBUG)
                    Log.v(TAG, "Waiting until " + (mLastLoadCompleteTime + mUpdateThrottle) + " to execute: "
                            + mTask);
                mTask.waiting = true;
                mHandler.postAtTime(mTask, mLastLoadCompleteTime + mUpdateThrottle);
                return;
            }
        }
        if (DEBUG)
            Log.v(TAG, "Executing: " + mTask);
        mTask.executeOnExecutor(ModernAsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
    }
}

From source file:com.techjoynt.android.nxt.activity.RemoteControl.java

@Override
public void run() {
    if ((SystemClock.uptimeMillis() - lastActivity) > TIMEOUT_PERIOD) {
        content.setKeepScreenOn(false);//from w w  w.j  av a2  s .c  o m
    }
    content.postDelayed(this, TIMEOUT_POLL_PERIOD);
}

From source file:com.techjoynt.android.nxt.activity.RemoteControl.java

public void onClick(View v) {
    lastActivity = SystemClock.uptimeMillis();
}