Example usage for android.text.format DateUtils MINUTE_IN_MILLIS

List of usage examples for android.text.format DateUtils MINUTE_IN_MILLIS

Introduction

In this page you can find the example usage for android.text.format DateUtils MINUTE_IN_MILLIS.

Prototype

long MINUTE_IN_MILLIS

To view the source code for android.text.format DateUtils MINUTE_IN_MILLIS.

Click Source Link

Usage

From source file:org.hopestarter.wallet.WalletApplication.java

public static void scheduleStartBlockchainService(final Context context) {
    final Configuration config = new Configuration(PreferenceManager.getDefaultSharedPreferences(context),
            context.getResources());//from   www  .j av  a2 s  . c  o m
    final long lastUsedAgo = config.getLastUsedAgo();

    // apply some backoff
    final long alarmInterval;
    if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS)
        alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
    else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS)
        alarmInterval = AlarmManager.INTERVAL_HALF_DAY;
    else
        alarmInterval = AlarmManager.INTERVAL_DAY;

    log.info("last used {} minutes ago, rescheduling blockchain sync in roughly {} minutes",
            lastUsedAgo / DateUtils.MINUTE_IN_MILLIS, alarmInterval / DateUtils.MINUTE_IN_MILLIS);

    final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    final PendingIntent alarmIntent = PendingIntent.getService(context, 0,
            new Intent(context, BlockchainServiceImpl.class), 0);
    alarmManager.cancel(alarmIntent);

    // workaround for no inexact set() before KitKat
    final long now = System.currentTimeMillis();
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now + alarmInterval, AlarmManager.INTERVAL_DAY,
            alarmIntent);
}

From source file:com.nextgis.firereporter.SettingsSupport.java

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    CharSequence newVal = "";
    Preference Pref = screen.findPreference(key);
    if (key.equals(SettingsActivity.KEY_PREF_INTERVAL)) {
        newVal = sharedPreferences.getString(key, "35");
        Editor editor = screen.getSharedPreferences().edit();
        long nVal = Long.parseLong((String) newVal) * DateUtils.MINUTE_IN_MILLIS;
        editor.putLong(key + "_long", nVal);
        editor.commit();/*from  w ww  .  j  a  v  a  2  s .  c o  m*/

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putLong(key + "_long", nVal);
        editor1.commit();

        int nIndex = mSendDataIntervalPref.findIndexOfValue((String) newVal);
        if (nIndex >= 0) {
            mSendDataIntervalPref.setSummary((String) mSendDataIntervalPref.getEntries()[nIndex]);
        }
        return;
    } else if (key.equals(SettingsActivity.KEY_PREF_SEARCH_DAY_INTERVAL)) {
        newVal = sharedPreferences.getString(key, "5");
        Editor editor = screen.getSharedPreferences().edit();
        int nVal = Integer.parseInt((String) newVal);
        editor.putInt(key + "_int", nVal);
        editor.commit();

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putInt(key + "_int", nVal);
        editor1.commit();

        int nIndex = mDayIntervalPref.findIndexOfValue((String) newVal);
        if (nIndex >= 0) {
            mDayIntervalPref.setSummary((String) mDayIntervalPref.getEntries()[nIndex]);
        }
        return;
    } else if (key.equals(SettingsActivity.KEY_PREF_ROW_COUNT)) {
        newVal = sharedPreferences.getString(key, "");
        int nVal = Integer.parseInt((String) newVal);
        Editor editor = screen.getSharedPreferences().edit();
        editor.putInt(key + "_int", nVal);
        editor.commit();

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putInt(key + "_int", nVal);
        editor1.commit();

    } else if (key.equals(SettingsActivity.KEY_PREF_FIRE_SEARCH_RADIUS)) {
        newVal = sharedPreferences.getString(key, "");
        int nVal = Integer.parseInt((String) newVal);
        Editor editor = screen.getSharedPreferences().edit();
        editor.putInt(key + "_int", nVal);
        editor.commit();

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putInt(key + "_int", nVal);
        editor1.commit();

        Pref.setSummary(newVal + " " + context.getString(R.string.km));
        return;
    } else if (key.equals(SettingsActivity.KEY_PREF_SEARCH_CURR_DAY)) {
        boolean bPref = sharedPreferences.getBoolean(key, false);
        newVal = bPref ? context.getString(R.string.stSearchCurrentDayOn)
                : context.getString(R.string.stSearchCurrentDayOff);

        SharedPreferences.Editor editor = screen.getSharedPreferences().edit();
        editor.putBoolean(key, bPref);
        editor.commit();

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putBoolean(key, bPref);
        editor1.commit();
    } else if (key.equals(SettingsActivity.KEY_PREF_SERVICE_BATT_SAVE)
            || key.equals(SettingsActivity.KEY_PREF_NOTIFY_LED)
            || key.equals(SettingsActivity.KEY_PREF_NOTIFY_SOUND)
            || key.equals(SettingsActivity.KEY_PREF_NOTIFY_VIBRO)) {
        boolean bPref = sharedPreferences.getBoolean(key, false);
        newVal = bPref ? context.getString(R.string.stOn) : context.getString(R.string.stOff);

        SharedPreferences.Editor editor = screen.getSharedPreferences().edit();
        editor.putBoolean(key, bPref);
        editor.commit();

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putBoolean(key, bPref);
        editor1.commit();
    } else if (key.equals(SettingsActivity.KEY_PREF_SRV_NASA)
            || key.equals(SettingsActivity.KEY_PREF_SRV_USER)) {
        newVal = sharedPreferences.getString(key, "");
        String sURL = newVal.toString();
        if (sURL.startsWith("http://") || sURL.startsWith("HTTP://")) {
            //ok
        } else {
            sURL = "http://" + sURL;
            Editor editor = screen.getSharedPreferences().edit();
            editor.putString(key, sURL);
            editor.commit();

            newVal = sURL;
        }
        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putString(key, sURL);
        editor1.commit();
    } else if (key.equals(SettingsActivity.KEY_PREF_SRV_NASA_USER)
            || key.equals(SettingsActivity.KEY_PREF_SRV_USER_USER)
            || key.equals(SettingsActivity.KEY_PREF_SRV_SCAN_USER)) {
        newVal = sharedPreferences.getString(key, "");

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putString(key, newVal.toString());
        editor1.commit();
    }

    else if (key.equals(SettingsActivity.KEY_PREF_COORD_FORMAT)) {
        newVal = sharedPreferences.getString(key, "");

        SharedPreferences mySharedPreferences = context.getSharedPreferences(MainActivity.PREFERENCES,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
        editor1.putString(key, newVal.toString());
        editor1.commit();
    }

    if (newVal.length() > 0)
        Pref.setSummary(newVal);
}

From source file:com.vuze.android.remote.fragment.TorrentListFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    fragView = inflater.inflate(R.layout.frag_torrent_list, container, false);

    setupActionModeCallback();/*from   w  w w .  j  a v a2s  .  c o  m*/

    final SwipeRefreshLayoutExtra swipeRefresh = (SwipeRefreshLayoutExtra) fragView
            .findViewById(R.id.swipe_container);
    if (swipeRefresh != null) {
        swipeRefresh.setExtraLayout(R.layout.swipe_layout_extra);

        LastUpdatedInfo lui = getLastUpdatedString();
        if (lui != null) {
            View extraView = swipeRefresh.getExtraView();
            if (extraView != null) {
                TextView tvSwipeText = (TextView) extraView.findViewById(R.id.swipe_text);
                tvSwipeText.setText(lui.s);
            }
        }
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (sessionInfo == null) {
                    return;
                }
                sessionInfo.addTorrentListReceivedListener(new TorrentListReceivedListener() {

                    @Override
                    public void rpcTorrentListReceived(String callID, List<?> addedTorrentMaps,
                            List<?> removedTorrentIDs) {
                        AndroidUtils.runOnUIThread(TorrentListFragment.this, new Runnable() {
                            @Override
                            public void run() {
                                if (getActivity() == null) {
                                    return;
                                }
                                swipeRefresh.setRefreshing(false);
                                LastUpdatedInfo lui = getLastUpdatedString();
                                View extraView = swipeRefresh.getExtraView();
                                if (extraView != null) {
                                    TextView tvSwipeText = (TextView) extraView.findViewById(R.id.swipe_text);
                                    tvSwipeText.setText(lui.s);
                                }
                            }
                        });
                        sessionInfo.removeTorrentListReceivedListener(this);
                    }
                }, false);
                sessionInfo.triggerRefresh(true);
            }
        });
        swipeRefresh.setOnExtraViewVisibilityChange(
                new SwipeRefreshLayoutExtra.OnExtraViewVisibilityChangeListener() {
                    private Handler pullRefreshHandler;

                    @Override
                    public void onExtraViewVisibilityChange(final View view, int visibility) {
                        if (pullRefreshHandler != null) {
                            pullRefreshHandler.removeCallbacksAndMessages(null);
                            pullRefreshHandler = null;
                        }
                        if (visibility != View.VISIBLE) {
                            return;
                        }

                        pullRefreshHandler = new Handler(Looper.getMainLooper());

                        pullRefreshHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (getActivity() == null) {
                                    return;
                                }
                                LastUpdatedInfo lui = getLastUpdatedString();
                                if (lui == null) {
                                    return;
                                }
                                TextView tvSwipeText = (TextView) view.findViewById(R.id.swipe_text);
                                tvSwipeText.setText(lui.s);

                                if (pullRefreshHandler != null) {
                                    pullRefreshHandler.postDelayed(this,
                                            lui.sinceMS < DateUtils.MINUTE_IN_MILLIS
                                                    ? DateUtils.SECOND_IN_MILLIS
                                                    : lui.sinceMS < DateUtils.HOUR_IN_MILLIS
                                                            ? DateUtils.MINUTE_IN_MILLIS
                                                            : DateUtils.HOUR_IN_MILLIS);
                                }
                            }
                        }, 0);
                    }
                });
    }

    listview = (RecyclerView) fragView.findViewById(R.id.listTorrents);
    listview.setLayoutManager(new PreCachingLayoutManager(getContext()));
    listview.setAdapter(torrentListAdapter);

    if (AndroidUtils.isTV()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            listview.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT);
        }
        ((FastScrollRecyclerView) listview).setEnableFastScrolling(false);
        ((FlexibleRecyclerView) listview).setFixedVerticalHeight(AndroidUtilsUI.dpToPx(48));
        listview.setVerticalFadingEdgeEnabled(true);
        listview.setFadingEdgeLength(AndroidUtilsUI.dpToPx((int) (48 * 1.5)));
    }

    filterEditText = (EditText) fragView.findViewById(R.id.filterText);
    filterEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Filter filter = torrentListAdapter.getFilter();
            filter.filter(s);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    setupSideListArea(fragView);

    /** Handy code to watch the states of row 2
     listview.postDelayed(new Runnable() {
     String oldS = "";
            
     @Override public void run() {
            
     String s = (listview.getChildCount() < 3 ? ""
     : AndroidUtils.getStatesString(listview.getChildAt(2).getDrawableState
     ()));
            
     if (!s.equals(oldS)) {
     oldS = s;
     Log.e(TAG, "States of 2: " + s);
     }
            
     listview.postDelayed(this, 500);
     }
     }, 500);
     */

    setHasOptionsMenu(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        onCreateViewHC(fragView);
    }

    if (sideListArea != null) {
        fragView.post(new Runnable() {
            @Override
            public void run() {
                FragmentActivity activity = getActivity();
                if (activity == null) {
                    return;
                }
                Window window = activity.getWindow();
                if (window == null) {
                    return;
                }
                int dpHeight = window.getDecorView().getHeight();
                hideUnselectedSideHeaders = dpHeight < SIDELIST_HIDE_UNSELECTED_HEADERS_MAX_PX;
                expandSideListWidth(sidelistInFocus);
                if (AndroidUtils.DEBUG) {
                    Log.d(TAG, "onAttach: hide? " + hideUnselectedSideHeaders + ";" + dpHeight);
                }
            }
        });
    }

    return fragView;

}

From source file:com.gsma.rcs.ri.messaging.adapter.TalkCursorAdapter.java

private RcsChatInViewHolder bindRcsChatView(View view, Cursor cursor) {
    RcsChatInViewHolder holder = (RcsChatInViewHolder) view.getTag();
    holder.getTimestampText()/*  ww w .j a  va  2  s .c o m*/
            .setText(DateUtils.getRelativeTimeSpanString(cursor.getLong(holder.getColumnTimestampIdx()),
                    System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE));
    String mimeType = cursor.getString(holder.getColumnMimetypeIdx());
    TextView contentText = holder.getContentText();
    String data = cursor.getString(holder.getColumnContentIdx());
    if (MimeType.TEXT_MESSAGE.equals(mimeType)) {
        contentText.setText(formatMessageWithSmiley(data));
    } else {
        contentText.setText(formatGeolocation(mContext, new Geoloc(data)));
    }
    holder.getStatusText().setText(getRcsChatStatus(cursor, holder));
    return holder;
}

From source file:com.matthewmitchell.peercoin_android_wallet.WalletApplication.java

public void scheduleStartBlockchainService() {

    final WalletApplication wa = this;

    this.setOnLoadedCallback(new Runnable() {

        @Override/*w w w  .j  av  a2s  .  c  o  m*/
        public void run() {

            final long lastUsedAgo = config.getLastUsedAgo();

            // apply some backoff
            final long alarmInterval;
            if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS)
                alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS)
                alarmInterval = AlarmManager.INTERVAL_HALF_DAY;
            else
                alarmInterval = AlarmManager.INTERVAL_DAY;

            log.info("last used {} minutes ago, rescheduling blockchain sync in roughly {} minutes",
                    lastUsedAgo / DateUtils.MINUTE_IN_MILLIS, alarmInterval / DateUtils.MINUTE_IN_MILLIS);
            assertTrue(config != null);
            final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            final PendingIntent alarmIntent = PendingIntent.getService(wa, 0,
                    new Intent(wa, BlockchainServiceImpl.class), 0);
            alarmManager.cancel(alarmIntent);

            // workaround for no inexact set() before KitKat
            final long now = System.currentTimeMillis();
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now + alarmInterval,
                    AlarmManager.INTERVAL_DAY, alarmIntent);

        }

    });

}

From source file:com.android.deskclock.Utils.java

/**
 * Returns string denoting the timezone hour offset (e.g. GMT -8:00)
 * @param useShortForm Whether to return a short form of the header that rounds to the
 *                     nearest hour and excludes the "GMT" prefix
 *//*from  w w w  . j a  v  a2  s .c  o m*/
public static String getGMTHourOffset(TimeZone timezone, boolean useShortForm) {
    final int gmtOffset = timezone.getRawOffset();
    final long hour = gmtOffset / DateUtils.HOUR_IN_MILLIS;
    final long min = (Math.abs(gmtOffset) % DateUtils.HOUR_IN_MILLIS) / DateUtils.MINUTE_IN_MILLIS;

    if (useShortForm) {
        return String.format("%+d", hour);
    } else {
        return String.format("GMT %+d:%02d", hour, min);
    }
}

From source file:com.android.exchange.EasAccountService.java

private void runPingLoop()
        throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException {
    int pingHeartbeat = mPingHeartbeat;
    userLog("runPingLoop");
    // Do push for all sync services here
    long endTime = System.currentTimeMillis() + (30 * DateUtils.MINUTE_IN_MILLIS);
    HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>();
    ArrayList<String> readyMailboxes = new ArrayList<String>();
    ArrayList<String> notReadyMailboxes = new ArrayList<String>();
    int pingWaitCount = 0;
    long inboxId = -1;
    android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress,
            Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
    while ((System.currentTimeMillis() < endTime) && !isStopped()) {
        // Count of pushable mailboxes
        int pushCount = 0;
        // Count of mailboxes that can be pushed right now
        int canPushCount = 0;
        // Count of uninitialized boxes
        int uninitCount = 0;

        Serializer s = new Serializer();
        Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
                MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId
                        + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX,
                null, null);/*  ww  w  .  j  av a  2s  . c  o  m*/
        if (c == null)
            throw new ProviderUnavailableException();
        notReadyMailboxes.clear();
        readyMailboxes.clear();
        // Look for an inbox, and remember its id
        if (inboxId == -1) {
            inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX);
        }
        try {
            // Loop through our pushed boxes seeing what is available to push
            while (c.moveToNext()) {
                pushCount++;
                // Two requirements for push:
                // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped)
                // 2) The syncKey isn't "0" (i.e. it's synced at least once)
                long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
                String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);

                // See what type of box we've got and get authority
                int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
                String authority = EmailContent.AUTHORITY;
                switch (mailboxType) {
                case Mailbox.TYPE_CALENDAR:
                    authority = CalendarContract.AUTHORITY;
                    break;
                case Mailbox.TYPE_CONTACTS:
                    authority = ContactsContract.AUTHORITY;
                    break;
                }

                // See whether we can ping for this mailbox
                int pingStatus;
                if (!ContentResolver.getSyncAutomatically(amAccount, authority)) {
                    pingStatus = ExchangeService.PING_STATUS_DISABLED;
                } else {
                    pingStatus = ExchangeService.pingStatus(mailboxId);

                }

                if (pingStatus == ExchangeService.PING_STATUS_OK) {
                    String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN);
                    if ((syncKey == null) || syncKey.equals("0")) {
                        // We can't push until the initial sync is done
                        pushCount--;
                        uninitCount++;
                        continue;
                    }

                    if (canPushCount++ == 0) {
                        // Initialize the Ping command
                        s.start(Tags.PING_PING)
                                .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat))
                                .start(Tags.PING_FOLDERS);
                    }

                    String folderClass = getTargetCollectionClassFromCursor(c);
                    s.start(Tags.PING_FOLDER).data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN))
                            .data(Tags.PING_CLASS, folderClass).end();
                    readyMailboxes.add(mailboxName);
                } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING)
                        || (pingStatus == ExchangeService.PING_STATUS_WAITING)) {
                    notReadyMailboxes.add(mailboxName);
                } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) {
                    pushCount--;
                    userLog(mailboxName, " in error state; ignore");
                    continue;
                } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) {
                    pushCount--;
                    userLog(mailboxName, " disabled by user; ignore");
                    continue;
                }
            }
        } finally {
            c.close();
        }

        if (Eas.USER_LOG) {
            if (!notReadyMailboxes.isEmpty()) {
                userLog("Ping not ready for: " + notReadyMailboxes);
            }
            if (!readyMailboxes.isEmpty()) {
                userLog("Ping ready for: " + readyMailboxes);
            }
        }

        // If we've waited 10 seconds or more, just ping with whatever boxes are ready
        // But use a shorter than normal heartbeat
        boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5);

        if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) {
            // If all pingable boxes are ready for push, send Ping to the server
            s.end().end().done();
            pingWaitCount = 0;
            mPostAborted = false;
            mPostReset = false;

            // If we've been stopped, this is a good time to return
            if (isStopped())
                return;

            long pingTime = SystemClock.elapsedRealtime();
            try {
                // Send the ping, wrapped by appropriate timeout/alarm
                if (forcePing) {
                    userLog("Forcing ping after waiting for all boxes to be ready");
                }
                EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat);

                try {
                    int code = resp.getStatus();
                    userLog("Ping response: ", code);

                    // If we're not allowed to sync (e.g. roaming policy), terminate gracefully
                    // now; otherwise we might start a sync based on the response
                    if (!ExchangeService.canAutoSync(mAccount)) {
                        stop();
                    }

                    // Return immediately if we've been asked to stop during the ping
                    if (isStopped()) {
                        userLog("Stopping pingLoop");
                        return;
                    }

                    if (code == HttpStatus.SC_OK) {
                        if (!resp.isEmpty()) {
                            InputStream is = resp.getInputStream();
                            int pingResult = parsePingResult(is, mContentResolver, pingErrorMap);
                            // If our ping completed (status = 1), and wasn't forced and we're
                            // not at the maximum, try increasing timeout by two minutes
                            if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) {
                                if (pingHeartbeat > mPingHighWaterMark) {
                                    mPingHighWaterMark = pingHeartbeat;
                                    userLog("Setting high water mark at: ", mPingHighWaterMark);
                                }
                                if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) {
                                    pingHeartbeat += PING_HEARTBEAT_INCREMENT;
                                    if (pingHeartbeat > mPingMaxHeartbeat) {
                                        pingHeartbeat = mPingMaxHeartbeat;
                                    }
                                    userLog("Increase ping heartbeat to ", pingHeartbeat, "s");
                                }
                            } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS
                                    || pingResult == PROTOCOL_PING_STATUS_RETRY) {
                                // These errors appear to be server-related (I've seen a bad
                                // parameters result with known good parameters...)
                                userLog("Server error during Ping: " + pingResult);
                                // Act as if we have an IOException (backoff, etc.)
                                throw new IOException();
                            }
                            // Make sure to clear out any pending sync errors
                            ExchangeService.removeFromSyncErrorMap(mMailboxId);
                        } else {
                            userLog("Ping returned empty result; throwing IOException");
                            // Act as if we have an IOException (backoff, etc.)
                            throw new IOException();
                        }
                    } else if (resp.isAuthError()) {
                        mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE;
                        userLog("Authorization error during Ping: ", code);
                        throw new IOException();
                    }
                } finally {
                    resp.close();
                }
            } catch (IOException e) {
                String message = e.getMessage();
                // If we get the exception that is indicative of a NAT timeout and if we
                // haven't yet "fixed" the timeout, back off by two minutes and "fix" it
                boolean hasMessage = message != null;
                userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]"));
                if (mPostReset) {
                    // Nothing to do in this case; this is ExchangeService telling us to try
                    // another ping.
                } else if (mPostAborted || isLikelyNatFailure(message)) {
                    long pingLength = SystemClock.elapsedRealtime() - pingTime;
                    if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) {
                        pingHeartbeat -= PING_HEARTBEAT_INCREMENT;
                        mPingHeartbeatDropped = true;
                        if (pingHeartbeat < mPingMinHeartbeat) {
                            pingHeartbeat = mPingMinHeartbeat;
                        }
                        userLog("Decreased ping heartbeat to ", pingHeartbeat, "s");
                    } else if (mPostAborted) {
                        // There's no point in throwing here; this can happen in two cases
                        // 1) An alarm, which indicates minutes without activity; no sense
                        //    backing off
                        // 2) ExchangeService abort, due to sync of mailbox.  Again, we want to
                        //    keep on trying to ping
                        userLog("Ping aborted; retry");
                    } else if (pingLength < 2000) {
                        userLog("Abort or NAT type return < 2 seconds; throwing IOException");
                        throw e;
                    } else {
                        userLog("NAT type IOException");
                    }
                } else if (hasMessage && message.contains("roken pipe")) {
                    // The "broken pipe" error (uppercase or lowercase "b") seems to be an
                    // internal error, so let's not throw an exception (which leads to delays)
                    // but rather simply run through the loop again
                } else {
                    throw e;
                }
            }
        } else if (forcePing) {
            // In this case, there aren't any boxes that are pingable, but there are boxes
            // waiting (for IOExceptions)
            userLog("pingLoop waiting 60s for any pingable boxes");
            sleep(60 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (pushCount > 0) {
            // If we want to Ping, but can't just yet, wait a little bit
            // TODO Change sleep to wait and use notify from ExchangeService when a sync ends
            sleep(2 * DateUtils.SECOND_IN_MILLIS, false);
            pingWaitCount++;
            //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)");
        } else if (uninitCount > 0) {
            // In this case, we're doing an initial sync of at least one mailbox.  Since this
            // is typically a one-time case, I'm ok with trying again every 10 seconds until
            // we're in one of the other possible states.
            userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)");
            sleep(10 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (inboxId == -1) {
            // In this case, we're still syncing mailboxes, so sleep for only a short time
            sleep(45 * DateUtils.SECOND_IN_MILLIS, true);
        } else {
            // We've got nothing to do, so we'll check again in 20 minutes at which time
            // we'll update the folder list, check for policy changes and/or remote wipe, etc.
            // Let the device sleep in the meantime...
            userLog(ACCOUNT_MAILBOX_SLEEP_TEXT);
            sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true);
        }
    }

    // Save away the current heartbeat
    mPingHeartbeat = pingHeartbeat;
}

From source file:com.androzic.MapFragment.java

private void onUpdateNavigationStatus() {
    if (!application.isNavigating())
        return;//  w  w w.ja v  a2 s.  c  o  m

    long now = System.currentTimeMillis();

    double distance = application.navigationService.navDistance;
    double bearing = application.navigationService.navBearing;
    long turn = application.navigationService.navTurn;
    double vmg = application.navigationService.navVMG;
    int ete = application.navigationService.navETE;

    String[] dist = StringFormatter.distanceC(distance, StringFormatter.precisionFormat);
    String eteString = (ete == Integer.MAX_VALUE) ? getString(R.string.never)
            : (String) DateUtils.getRelativeTimeSpanString(now + (ete + 1) * 60000, now,
                    DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);
    String extra = StringFormatter.speedH(vmg) + " | " + eteString;

    String trnsym = "";
    if (turn > 0) {
        trnsym = "R";
    } else if (turn < 0) {
        trnsym = "L";
        turn = -turn;
    }

    bearing = application.fixDeclination(bearing);
    distanceValue.setText(dist[0]);
    distanceUnit.setText(dist[1]);
    bearingValue.setText(StringFormatter.angleC(bearing));
    turnValue.setText(StringFormatter.angleC(turn) + trnsym);
    waypointExtra.setText(extra);

    if (application.navigationService.isNavigatingViaRoute()) {
        View rootView = getView();
        boolean hasNext = application.navigationService.hasNextRouteWaypoint();
        if (distance < application.navigationService.navProximity * 3 && !animationSet) {
            AnimationSet animation = new AnimationSet(true);
            animation.addAnimation(new AlphaAnimation(1.0f, 0.3f));
            animation.addAnimation(new AlphaAnimation(0.3f, 1.0f));
            animation.setDuration(500);
            animation.setRepeatCount(10);
            rootView.findViewById(R.id.waypointinfo).startAnimation(animation);
            if (!hasNext) {
                rootView.findViewById(R.id.routeinfo).startAnimation(animation);
            }
            animationSet = true;
        } else if (animationSet) {
            rootView.findViewById(R.id.waypointinfo).setAnimation(null);
            if (!hasNext) {
                rootView.findViewById(R.id.routeinfo).setAnimation(null);
            }
            animationSet = false;
        }

        if (application.navigationService.navXTK == Double.NEGATIVE_INFINITY) {
            xtkValue.setText("--");
            xtkUnit.setText("--");
        } else {
            String xtksym = application.navigationService.navXTK == 0 ? ""
                    : application.navigationService.navXTK > 0 ? "R" : "L";
            String[] xtks = StringFormatter.distanceC(Math.abs(application.navigationService.navXTK));
            xtkValue.setText(xtks[0] + xtksym);
            xtkUnit.setText(xtks[1]);
        }

        double navDistance = application.navigationService.navRouteDistanceLeft();
        int eta = application.navigationService.navRouteETE(navDistance);
        if (eta < Integer.MAX_VALUE)
            eta += application.navigationService.navETE;
        String etaString = (eta == Integer.MAX_VALUE) ? getString(R.string.never)
                : (String) DateUtils.getRelativeTimeSpanString(now + (eta + 1) * 60000, now,
                        DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);
        extra = StringFormatter.distanceH(navDistance + distance, 1000) + " | " + etaString;
        routeExtra.setText(extra);
    }
}

From source file:com.hivewallet.androidclient.wallet.ui.WalletActivity.java

private void checkAlerts() {
    final PackageInfo packageInfo = getWalletApplication().packageInfo();
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    final String base = Constants.VERSION_URL
            + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : "");
    final String url = base + "?package=" + packageInfo.packageName + "&current=" + packageInfo.versionCode;

    new HttpGetThread(getAssets(), url, application.httpUserAgent()) {
        @Override//from  www  .  j a v a  2s  .c o  m
        protected void handleLine(final String line, final long serverTime) {
            final int serverVersionCode = Integer.parseInt(line.split("\\s+")[0]);

            log.info("according to \"" + url + "\", strongly recommended minimum app version is "
                    + serverVersionCode);

            if (serverTime > 0) {
                final long diffMinutes = Math
                        .abs((System.currentTimeMillis() - serverTime) / DateUtils.MINUTE_IN_MILLIS);

                if (diffMinutes >= 60) {
                    log.info(
                            "according to \"" + url + "\", system clock is off by " + diffMinutes + " minutes");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final Bundle args = new Bundle();
                            args.putLong("diff_minutes", diffMinutes);
                            showDialog(DIALOG_TIMESKEW_ALERT, args);
                        }
                    });

                    return;
                }
            }

            if (serverVersionCode > packageInfo.versionCode && Constants.ENABLE_VERSION_ALERT) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDialog(DIALOG_VERSION_ALERT);
                    }
                });

                return;
            }
        }

        @Override
        protected void handleException(final Exception x) {
            if (x instanceof UnknownHostException || x instanceof SocketException
                    || x instanceof SocketTimeoutException) {
                // swallow
                log.debug("problem reading", x);
            } else {
                CrashReporter.saveBackgroundTrace(new RuntimeException(url, x), packageInfo);
            }
        }
    }.start();

    if (CrashReporter.hasSavedCrashTrace()) {
        final StringBuilder stackTrace = new StringBuilder();

        try {
            CrashReporter.appendSavedCrashTrace(stackTrace);
        } catch (final IOException x) {
            log.info("problem appending crash info", x);
        }

        final ReportIssueDialogBuilder dialog = new ReportIssueDialogBuilder(this,
                R.string.report_issue_dialog_title_crash, R.string.report_issue_dialog_message_crash) {
            @Override
            protected CharSequence subject() {
                return Constants.REPORT_SUBJECT_CRASH + " " + packageInfo.versionName;
            }

            @Override
            protected CharSequence collectApplicationInfo() throws IOException {
                final StringBuilder applicationInfo = new StringBuilder();
                CrashReporter.appendApplicationInfo(applicationInfo, application);
                return applicationInfo;
            }

            @Override
            protected CharSequence collectStackTrace() throws IOException {
                if (stackTrace.length() > 0)
                    return stackTrace;
                else
                    return null;
            }

            @Override
            protected CharSequence collectDeviceInfo() throws IOException {
                final StringBuilder deviceInfo = new StringBuilder();
                CrashReporter.appendDeviceInfo(deviceInfo, WalletActivity.this);
                return deviceInfo;
            }

            @Override
            protected CharSequence collectWalletDump() {
                return wallet.toString(false, true, true, null);
            }
        };

        dialog.show();
    }
}

From source file:com.matthewmitchell.peercoin_android_wallet.ui.WalletActivity.java

private void checkAlerts() {
    final PackageInfo packageInfo = getWalletApplication().packageInfo();
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    final String base = Constants.VERSION_URL
            + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : "");
    final String url = base + "?package=" + packageInfo.packageName + "&current=" + packageInfo.versionCode;

    new HttpGetThread(getAssets(), url, application.httpUserAgent()) {
        @Override//  w ww  .j  ava  2s. c  o m
        protected void handleLine(final String line, final long serverTime) {
            final int serverVersionCode = Integer.parseInt(line.split("\\s+")[0]);

            log.info("according to \"" + url + "\", strongly recommended minimum app version is "
                    + serverVersionCode);

            if (serverTime > 0) {
                final long diffMinutes = Math
                        .abs((System.currentTimeMillis() - serverTime) / DateUtils.MINUTE_IN_MILLIS);

                if (diffMinutes >= 60) {
                    log.info(
                            "according to \"" + url + "\", system clock is off by " + diffMinutes + " minutes");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final Bundle args = new Bundle();
                            args.putLong("diff_minutes", diffMinutes);
                            showDialog(DIALOG_TIMESKEW_ALERT, args);
                        }
                    });

                    return;
                }
            }

            if (serverVersionCode > packageInfo.versionCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDialog(DIALOG_VERSION_ALERT);
                    }
                });

                return;
            }
        }

        @Override
        protected void handleException(final Exception x) {
            if (x instanceof UnknownHostException || x instanceof SocketException
                    || x instanceof SocketTimeoutException) {
                // swallow
                log.debug("problem reading", x);
            } else {
                CrashReporter.saveBackgroundTrace(new RuntimeException(url, x), packageInfo);
            }
        }
    }.start();

    if (CrashReporter.hasSavedCrashTrace()) {
        final StringBuilder stackTrace = new StringBuilder();

        try {
            CrashReporter.appendSavedCrashTrace(stackTrace);
        } catch (final IOException x) {
            log.info("problem appending crash info", x);
        }

        final ReportIssueDialogBuilder dialog = new ReportIssueDialogBuilder(this,
                R.string.report_issue_dialog_title_crash, R.string.report_issue_dialog_message_crash) {
            @Override
            protected CharSequence subject() {
                return Constants.REPORT_SUBJECT_CRASH + " " + packageInfo.versionName;
            }

            @Override
            protected CharSequence collectApplicationInfo() throws IOException {
                final StringBuilder applicationInfo = new StringBuilder();
                CrashReporter.appendApplicationInfo(applicationInfo, application);
                return applicationInfo;
            }

            @Override
            protected CharSequence collectStackTrace() throws IOException {
                if (stackTrace.length() > 0)
                    return stackTrace;
                else
                    return null;
            }

            @Override
            protected CharSequence collectDeviceInfo() throws IOException {
                final StringBuilder deviceInfo = new StringBuilder();
                CrashReporter.appendDeviceInfo(deviceInfo, WalletActivity.this);
                return deviceInfo;
            }

            @Override
            protected CharSequence collectWalletDump() {
                return application.getWallet().toString(false, true, true, null);
            }
        };

        dialog.show();
    }
}