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:de.schildbach.wallet.service.BlockchainService.java

public static void scheduleStart(final WalletApplication application) {
    final Configuration config = application.getConfiguration();
    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// w  w w  .  ja v  a2 s.c  om
        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) application.getSystemService(Context.ALARM_SERVICE);
    final PendingIntent alarmIntent = PendingIntent.getService(application, 0,
            new Intent(application, BlockchainService.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.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

@SuppressLint("SdCardPath")
@Override//from w w w  . j a v  a  2s .co m
public void bindView(View view, Context context, Cursor cursor) {
    System.out.println("MessageAdapter.java in bindView() ");
    final MessageListItemViews tagView = (MessageListItemViews) view.getTag();
    v = view;
    this.context = context;
    SipMessage msg = new SipMessage(cursor);
    // System.out.println("msg:"+msg);

    System.out.println("Cursor row count:" + cursor.getCount());

    String number = msg.getRemoteNumber();
    long date = msg.getDate();
    String message = msg.getBodyContent();
    subject = message;
    System.out.println("subject--" + subject);
    if (message.contains("[Offline message -") && !number.equals("sip:registrar@kamailio.org")) {
        System.out.println("offline message");
        String[] finalMessage = message.split("]");
        subject = finalMessage[finalMessage.length - 1];
    } else {
        subject = message;
    }

    String errorTxt = msg.getErrorContent();
    String mimeType = msg.getMimeType();
    int type = msg.getType();

    Log.setLogLevel(6);
    Log.d("Col count", cursor.getColumnCount() + " @");

    String[] columnname = cursor.getColumnNames();
    for (int i = 0; i < columnname.length; i++) {
        Log.d("columnname " + i, columnname[i] + " @");
        Log.d(columnname[i], cursor.getString(cursor.getColumnIndex(columnname[i])) + " @");

    }

    tv_msg_info = (TextView) view.findViewById(R.id.tv_msg_info);
    pb_uploading = (ProgressBar) view.findViewById(R.id.pb_uploading);

    String timestamp = "";
    if (System.currentTimeMillis() - date > 1000 * 60 * 60 * 24) {
        // If it was recieved one day ago or more display relative
        // timestamp - SMS like behavior
        int flags = DateUtils.FORMAT_ABBREV_RELATIVE;
        timestamp = (String) DateUtils.getRelativeTimeSpanString(date, System.currentTimeMillis(),
                DateUtils.MINUTE_IN_MILLIS, flags);
    } else {
        // If it has been recieved recently show time of reception - IM
        // like behavior
        timestamp = dateFormatter.format(new Date(date));
    }

    tagView.dateView.setText(timestamp);

    // Delivery state
    if (type == SipMessage.MESSAGE_TYPE_QUEUED) {
        tagView.deliveredIndicator.setVisibility(View.VISIBLE);
        tagView.deliveredIndicator.setImageResource(R.drawable.error_watch_not_send);
        tagView.deliveredIndicator.setContentDescription("");
    } else if (type == SipMessage.MESSAGE_TYPE_FAILED) {
        tagView.deliveredIndicator.setVisibility(View.VISIBLE);
        tagView.deliveredIndicator.setImageResource(R.drawable.error_watch_not_send);
        tagView.deliveredIndicator.setContentDescription("");
    } else {
        tagView.deliveredIndicator.setVisibility(View.VISIBLE);
        tagView.deliveredIndicator.setImageResource(R.drawable.todo_send);
        tagView.deliveredIndicator.setContentDescription("");
    }

    if (TextUtils.isEmpty(errorTxt)) {
        tagView.errorView.setVisibility(View.GONE);
    } else {
        tagView.errorView.setVisibility(View.GONE);
        tagView.errorView.setText(errorTxt);
    }

    // Subject
    tagView.contentView.setText(formatMessage(number, subject, mimeType));
    if (msg.isOutgoing()) {
        setPhotoSide(tagView, ArrowPosition.LEFT);
        LinearLayout linerLayout = (LinearLayout) view.findViewById(R.id.message_block);
        linerLayout.setBackgroundResource(R.drawable.chatedittextdesign);
        text_view = (TextView) view.findViewById(R.id.text_view);
        text_view.setTextColor(Color.BLACK);

        // Photo
        tagView.quickContactView.assignContactUri(personalInfo.contactContentUri);
        /*
        ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, 
            tagView.quickContactView.getImageView(),
            personalInfo,
            R.drawable.ic_contact_picture_holo_dark);
         */

        System.out.println("msg adp out - 0");
        String path = "/sdcard/R4W/ProfilePic/ProfilePic.png";
        File user_imageFile = new File(path);
        if (user_imageFile.exists()) {
            try {
                if (bm != null) {
                    //      bm = null;
                }
                bm = BitmapFactory.decodeFile(path);
                bm = ImageHelperCircular.getRoundedCornerBitmap(bm, bm.getWidth());
                tagView.quickContactView.getImageView().setImageBitmap(bm);
            } catch (Exception e) {
                // TODO: handle exception
                try {
                    tagView.quickContactView.getImageView().setImageURI(Uri.parse(path));

                } catch (Exception e2) {
                    ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                            tagView.quickContactView.getImageView(), personalInfo,
                            R.drawable.ic_contact_picture_holo_dark);
                    // TODO: handle exception
                }
            }
        } else {
            ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                    tagView.quickContactView.getImageView(), personalInfo,
                    R.drawable.ic_contact_picture_holo_dark);

        }

        outgoingImage(number);

    } else {

        setPhotoSide(tagView, ArrowPosition.RIGHT);
        LinearLayout linerLayout = (LinearLayout) view.findViewById(R.id.message_block);
        linerLayout.setBackgroundResource(R.drawable.messagebodyleft);

        // Contact
        CallerInfo info = CallerInfo.getCallerInfoFromSipUri(mContext, msg.getFullFrom());

        text_view = (TextView) view.findViewById(R.id.text_view);
        text_view.setTextColor(Color.BLACK);
        pb_uploading.setVisibility(ProgressBar.GONE);

        // Photo
        tagView.quickContactView.assignContactUri(info.contactContentUri);
        /*
        ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, 
            tagView.quickContactView.getImageView(),
            info,
            R.drawable.ic_contact_picture_holo_dark);
           */
        System.out.println("msg adp in - 1");
        String nu = stripNumber(number);
        String path = "/sdcard/R4W/ProfilePic/" + nu + ".png";
        System.out.println("msg adp out - path=" + path);
        File user_imageFile = new File(path);
        if (user_imageFile.exists()) {
            try {
                if (bm != null) {
                    //      bm = null;
                }
                bm = BitmapFactory.decodeFile(path);
                bm = ImageHelperCircular.getRoundedCornerBitmap(bm, bm.getWidth());
                tagView.quickContactView.getImageView().setImageBitmap(bm);
            } catch (Exception e) {
                // TODO: handle exception
                try {
                    tagView.quickContactView.getImageView().setImageURI(Uri.parse(path));

                } catch (Exception e2) {
                    ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                            tagView.quickContactView.getImageView(), info,
                            R.drawable.ic_contact_picture_holo_dark); // TODO: handle exception
                }
            }
        } else {
            ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                    tagView.quickContactView.getImageView(), info, R.drawable.ic_contact_picture_holo_dark);
        }
        incomingImage();
    }

}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override/*from   w  w  w . ja  v a2 s . c o m*/
protected void onHandleIntent(Intent intent) {
    Timber.d("Waking up...");
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
        return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
        Timber.d("Notification service disabled, removing wakup-up alarm");
        // cancel any pending alarm
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, OnAlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        am.cancel(pi);

        resetLastEpisodeAirtime(prefs);

        return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    Timber.d("Do notify about " + (isFavsOnly ? "favorites ONLY" : "ALL"));
    if (isFavsOnly) {
        selection.append(" AND ").append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    Timber.d("Do " + (isNoSpecials ? "NOT " : "") + "notify about specials");
    if (isNoSpecials) {
        selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS);
    }
    // always exclude hidden shows
    selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN);

    final long customCurrentTime = TimeTools.getCurrentTime(this);
    final Cursor upcomingEpisodes = getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, PROJECTION,
            selection.toString(),
            new String[] { String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS) }, SORTING);

    if (upcomingEpisodes != null) {
        int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
        if (DEBUG) {
            Timber.d("DEBUG MODE: notification threshold is 1 week");
            // a week, for debugging (use only one show to get single
            // episode notifications)
            notificationThreshold = 10080;
            // notify again for same episodes
            resetLastEpisodeAirtime(prefs);
        }

        final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this);
        // wake user-defined amount of time earlier than next episode release time
        final long plannedWakeUpTime = TimeTools.getEpisodeReleaseTime(this, nextEpisodeReleaseTime).getTime()
                - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

        /*
         * Set to -1 as on first run nextTimePlanned will be 0. This assures
         * we still see notifications of upcoming episodes then.
         */
        int newEpisodesAvailable = -1;

        // Check if we did wake up earlier than planned
        if (System.currentTimeMillis() < plannedWakeUpTime) {
            Timber.d("Woke up earlier than planned, checking for new episodes");
            newEpisodesAvailable = 0;
            long latestTimeNotified = NotificationSettings.getLastNotified(this);

            // Check if there are any earlier episodes to notify about
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime < nextEpisodeReleaseTime) {
                    if (releaseTime > latestTimeNotified) {
                        /**
                         * This will not get new episodes which would have
                         * aired the same time as the last one we notified
                         * about. Sad, but the best we can do right now.
                         */
                        newEpisodesAvailable = 1;
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        if (newEpisodesAvailable == 0) {
            // Go to sleep, wake up as planned
            Timber.d("No new episodes, going to sleep.");
            wakeUpTime = plannedWakeUpTime;
        } else {
            // Get episodes which are within the notification threshold
            // (user set) and not yet cleared
            final List<Integer> notifyPositions = new ArrayList<>();
            final long latestTimeCleared = NotificationSettings.getLastCleared(this);
            final long latestTimeToInclude = customCurrentTime
                    + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            int position = -1;
            upcomingEpisodes.moveToPosition(position);
            while (upcomingEpisodes.moveToNext()) {
                position++;

                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime <= latestTimeToInclude) {
                    /*
                     * Only add those after the last one the user cleared.
                     * At most those of the last 24 hours (see query above).
                     */
                    if (releaseTime > latestTimeCleared) {
                        notifyPositions.add(position);
                    }
                } else {
                    // Too far into the future, stop!
                    break;
                }
            }

            // Notify if we found any episodes
            if (notifyPositions.size() > 0) {
                // store latest air time of all episodes we notified about
                upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
                long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (!AndroidUtils.isHoneycombOrHigher()) {
                    /*
                     * Everything below HC does not have delete intents, so
                     * we just never notify about the same episode twice.
                     */
                    Timber.d("Delete intent NOT supported, setting last cleared to: " + latestAirtime);
                    prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
                }
                Timber.d("Found " + notifyPositions.size() + " new episodes, setting last notified to: "
                        + latestAirtime);
                prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

                onNotify(upcomingEpisodes, notifyPositions, latestAirtime);
            }

            /*
             * Plan next episode to notify about, calc wake-up alarm as
             * early as user wants.
             */
            upcomingEpisodes.moveToPosition(-1);
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime > latestTimeToInclude) {
                    // store next episode we plan to notify about
                    Timber.d("Storing next episode time to notify about: " + releaseTime);
                    prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime).commit();

                    // calc actual wake up time
                    wakeUpTime = TimeTools.getEpisodeReleaseTime(this, releaseTime).getTime()
                            - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

                    break;
                }
            }
        }

        upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
        wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
        Timber.d("No future episodes found, wake up in 6 hours");
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Timber.d("Going to sleep, setting wake-up alarm to: " + wakeUpTime);
    if (AndroidUtils.isKitKatOrHigher()) {
        am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
}

From source file:com.nextgis.mobile.TrackerService.java

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

    Log.d(MainActivity.TAG, "Received start id " + startId + ": " + intent);

    super.onStartCommand(intent, flags, startId);

    if (intent == null)
        return START_STICKY;

    String action = intent.getAction();
    if (action == null)
        return START_STICKY;

    Log.d(MainActivity.TAG, "action " + action);
    if (action.equals(ACTION_STOP)) {
        trackerLocationListener.setWritePostion(false);
        if (dbHelper != null)
            dbHelper.close();/*from   www .  j a  v  a  2  s  .c  o m*/
        if (!trackerLocationListener.isWriteTrack())
            stopSelf();
    } else if (action.equals(ACTION_STOP_GPX)) {
        m_TrakAddPointHandler = null;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(mNotifyId);

        trackerLocationListener.StoreTrack(false);
        trackerLocationListener.setWriteTrack(false);
        if (!trackerLocationListener.isWritePostion())
            stopSelf();
    } else if (action.equals(ACTION_START)) {
        SharedPreferences prefs = getSharedPreferences(PreferencesActivity.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_TRACK_SRV, false);

        if (isStrarted) {
            if (!trackerLocationListener.isWritePostion()) {
                trackerLocationListener.setWritePostion(true);

                dbHelper = new PositionDatabase(getApplicationContext());
                PositionDB = dbHelper.getWritableDatabase();

                long nMinDistChangeForUpdates = prefs
                        .getLong(PreferencesActivity.KEY_PREF_MIN_DIST_CHNG_UPD + "_long", 25);
                long nMinTimeBetweenUpdates = prefs.getLong(PreferencesActivity.KEY_PREF_MIN_TIME_UPD + "_long",
                        0);

                Log.d(MainActivity.TAG, "start LocationManager MinDist:" + nMinDistChangeForUpdates
                        + " MinTime:" + nMinTimeBetweenUpdates);

                Log.d(MainActivity.TAG, "start LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(MainActivity.TAG, "start LocationManager.NETWORK_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(MainActivity.TAG, "request end");

            }
            boolean bEnergyEconomy = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_ENERGY_ECO, true);
            long nMinTimeBetweenSend = prefs.getLong(PreferencesActivity.KEY_PREF_TIME_DATASEND + "_long",
                    DateUtils.MINUTE_IN_MILLIS);
            ScheduleNextUpdate(this.getApplicationContext(), TrackerService.ACTION_START, nMinTimeBetweenSend,
                    bEnergyEconomy, isStrarted);
        }
    } else if (action.equals(ACTION_START_GPX)) {
        SharedPreferences prefs = getSharedPreferences(PreferencesActivity.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted_GPX = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_TRACKGPX_SRV, false);

        if (isStrarted_GPX) {
            if (!trackerLocationListener.isWriteTrack()) {
                trackerLocationListener.setWriteTrack(true);

                long nMinDistChangeForUpdates = prefs
                        .getLong(PreferencesActivity.KEY_PREF_MIN_DIST_CHNG_UPD + "_long", 25);
                long nMinTimeBetweenUpdates = prefs.getLong(PreferencesActivity.KEY_PREF_MIN_TIME_UPD + "_long",
                        0);

                Log.d(MainActivity.TAG, "start GPX LocationManager MinDist:" + nMinDistChangeForUpdates
                        + " MinTime:" + nMinTimeBetweenUpdates);

                Log.d(MainActivity.TAG, "start GPX LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);

                Intent resultIntent = new Intent(this, MainActivity.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(MainActivity.class)
                        .addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.record_start_notify)
                        .setContentTitle(getString(R.string.app_name)).setOngoing(true)
                        .setContentText(getString(R.string.gpx_recording))
                        .setContentIntent(resultPendingIntent);

                Notification noti = mBuilder.getNotification();
                //noti.flags |= Notification.FLAG_FOREGROUND_SERVICE;//Notification.FLAG_NO_CLEAR | 
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(mNotifyId, noti);

            }
        }
        boolean bEnergyEconomy = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_ENERGY_ECO, true);
        long nMinTimeBetweenSend = prefs.getLong(PreferencesActivity.KEY_PREF_TIME_DATASEND + "_long",
                DateUtils.MINUTE_IN_MILLIS);
        ScheduleNextUpdate(getApplicationContext(), TrackerService.ACTION_START_GPX, nMinTimeBetweenSend,
                bEnergyEconomy, isStrarted_GPX);
    }
    return START_STICKY;
}

From source file:com.nextgis.mobile.services.TrackerService.java

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

    Log.d(TAG, "Received start id " + startId + ": " + intent);

    super.onStartCommand(intent, flags, startId);

    if (intent == null)
        return START_STICKY;

    String action = intent.getAction();
    if (action == null)
        return START_STICKY;

    Log.d(TAG, "action " + action);
    if (action.equals(ACTION_STOP)) {
        trackerLocationListener.setWritePostion(false);
        if (dbHelper != null)
            dbHelper.close();/*from  w w  w  .j  av a2 s  .co  m*/
        if (!trackerLocationListener.isWriteTrack())
            stopSelf();
    } else if (action.equals(ACTION_STOP_GPX)) {
        m_TrakAddPointHandler = null;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(mNotifyId);

        trackerLocationListener.StoreTrack(false);
        trackerLocationListener.setWriteTrack(false);
        if (!trackerLocationListener.isWritePostion())
            stopSelf();
    } else if (action.equals(ACTION_START)) {
        SharedPreferences prefs = getSharedPreferences(Constants.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted = prefs.getBoolean(Constants.KEY_PREF_SW_TRACK_SRV, false);

        if (isStrarted) {
            if (!trackerLocationListener.isWritePostion()) {
                trackerLocationListener.setWritePostion(true);

                dbHelper = new PositionDatabase(getApplicationContext());
                PositionDB = dbHelper.getWritableDatabase();

                long nMinDistChangeForUpdates = prefs.getLong(Constants.KEY_PREF_MIN_DIST_CHNG_UPD + "_long",
                        25);
                long nMinTimeBetweenUpdates = prefs.getLong(Constants.KEY_PREF_MIN_TIME_UPD + "_long", 0);

                Log.d(TAG, "start LocationManager MinDist:" + nMinDistChangeForUpdates + " MinTime:"
                        + nMinTimeBetweenUpdates);

                Log.d(TAG, "start LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(TAG, "start LocationManager.NETWORK_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);
                Log.d(TAG, "request end");

            }
            boolean bEnergyEconomy = prefs.getBoolean(Constants.KEY_PREF_SW_ENERGY_ECO, true);
            long nMinTimeBetweenSend = prefs.getLong(Constants.KEY_PREF_TIME_DATASEND + "_long",
                    DateUtils.MINUTE_IN_MILLIS);
            ScheduleNextUpdate(this.getApplicationContext(), TrackerService.ACTION_START, nMinTimeBetweenSend,
                    bEnergyEconomy, isStrarted);
        }
    } else if (action.equals(ACTION_START_GPX)) {
        SharedPreferences prefs = getSharedPreferences(Constants.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean isStrarted_GPX = prefs.getBoolean(Constants.KEY_PREF_SW_TRACKGPX_SRV, false);

        if (isStrarted_GPX) {
            if (!trackerLocationListener.isWriteTrack()) {
                trackerLocationListener.setWriteTrack(true);

                long nMinDistChangeForUpdates = prefs.getLong(Constants.KEY_PREF_MIN_DIST_CHNG_UPD + "_long",
                        25);
                long nMinTimeBetweenUpdates = prefs.getLong(Constants.KEY_PREF_MIN_TIME_UPD + "_long", 0);

                Log.d(TAG, "start GPX LocationManager MinDist:" + nMinDistChangeForUpdates + " MinTime:"
                        + nMinTimeBetweenUpdates);

                Log.d(TAG, "start GPX LocationManager.GPS_PROVIDER");
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, nMinTimeBetweenUpdates,
                        nMinDistChangeForUpdates, trackerLocationListener);

                Intent resultIntent = new Intent(this, MainActivity.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(MainActivity.class)
                        .addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.record_start_notify)
                        .setContentTitle(getString(R.string.app_name)).setOngoing(true)
                        .setContentText(getString(R.string.gpx_recording))
                        .setContentIntent(resultPendingIntent);

                Notification noti = mBuilder.getNotification();
                //noti.flags |= Notification.FLAG_FOREGROUND_SERVICE;//Notification.FLAG_NO_CLEAR | 
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(mNotifyId, noti);

            }
        }
        boolean bEnergyEconomy = prefs.getBoolean(Constants.KEY_PREF_SW_ENERGY_ECO, true);
        long nMinTimeBetweenSend = prefs.getLong(Constants.KEY_PREF_TIME_DATASEND + "_long",
                DateUtils.MINUTE_IN_MILLIS);
        ScheduleNextUpdate(getApplicationContext(), TrackerService.ACTION_START_GPX, nMinTimeBetweenSend,
                bEnergyEconomy, isStrarted_GPX);
    }
    return START_STICKY;
}

From source file:gov.wa.wsdot.android.wsdot.ui.ferries.departures.FerriesRouteSchedulesDayDeparturesFragment.java

@Override
public void onResume() {
    super.onResume();
    mHandler.postDelayed(runnable, (DateUtils.MINUTE_IN_MILLIS)); // Check every minute.
}

From source file:org.telegram.ui.Components.TwilightManager.java

private void updateState(@NonNull Location location) {
    final TwilightState state = mTwilightState;
    final long now = System.currentTimeMillis();
    final TwilightCalculator calculator = TwilightCalculator.getInstance();

    // calculate yesterday's twilight
    calculator.calculateTwilight(now - DateUtils.DAY_IN_MILLIS, location.getLatitude(),
            location.getLongitude());/*from   w w  w . ja  v a 2  s .  c  o m*/
    final long yesterdaySunset = calculator.sunset;

    // calculate today's twilight
    calculator.calculateTwilight(now, location.getLatitude(), location.getLongitude());
    final boolean isNight = (calculator.state == TwilightCalculator.NIGHT);
    final long todaySunrise = calculator.sunrise;
    final long todaySunset = calculator.sunset;

    // calculate tomorrow's twilight
    calculator.calculateTwilight(now + DateUtils.DAY_IN_MILLIS, location.getLatitude(),
            location.getLongitude());
    final long tomorrowSunrise = calculator.sunrise;

    // Set next update
    long nextUpdate = 0;
    if (todaySunrise == -1 || todaySunset == -1) {
        // In the case the day or night never ends the update is scheduled 12 hours later.
        nextUpdate = now + 12 * DateUtils.HOUR_IN_MILLIS;
    } else {
        if (now > todaySunset) {
            nextUpdate += tomorrowSunrise;
        } else if (now > todaySunrise) {
            nextUpdate += todaySunset;
        } else {
            nextUpdate += todaySunrise;
        }
        // add some extra time to be on the safe side.
        nextUpdate += DateUtils.MINUTE_IN_MILLIS;
    }

    // Update the twilight state
    state.isNight = isNight;
    state.yesterdaySunset = yesterdaySunset;
    state.todaySunrise = todaySunrise;
    state.todaySunset = todaySunset;
    state.tomorrowSunrise = tomorrowSunrise;
    state.nextUpdate = nextUpdate;
}

From source file:com.sonaive.v2ex.ui.ReviewsFragment.java

private void initHeader(View header) {
    if (mFeed != null) {
        ImageLoader imageLoader = new ImageLoader(getActivity(), R.drawable.person_image_empty);
        TextView title = (TextView) header.findViewById(R.id.title);
        HtmlTextView content = (HtmlTextView) header.findViewById(R.id.content);
        ImageView avatar = (ImageView) header.findViewById(R.id.avatar);
        TextView name = (TextView) header.findViewById(R.id.name);
        TextView time = (TextView) header.findViewById(R.id.time);
        TextView replies = (TextView) header.findViewById(R.id.replies);
        TextView nodeTitle = (TextView) header.findViewById(R.id.node_title);

        title.setText(mFeed.title);//  w  w  w. j  a v a  2 s. co  m
        content.setVisibility(View.VISIBLE);
        content.setText(
                Html.fromHtml(mFeed.content_rendered, new URLImageParser(getActivity(), content), null));
        if (mFeed.member != null) {
            String avatarUrl = mFeed.member.avatar_large;
            if (avatarUrl != null) {
                avatarUrl = avatarUrl.startsWith("http:") ? avatarUrl : "http:" + avatarUrl;
            } else {
                avatarUrl = "";
            }
            imageLoader.loadImage(avatarUrl, avatar);
            name.setText(mFeed.member.username);
        }

        if (mFeed.member != null) {
            nodeTitle.setText(mFeed.node.title);
        }
        time.setText(DateUtils.getRelativeTimeSpanString(mFeed.created * 1000, System.currentTimeMillis(),
                DateUtils.MINUTE_IN_MILLIS));
        replies.setText(mFeed.replies + getString(R.string.noun_reply));
    }
}

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

private void fillTimeline(FragmentActivity a, Map<?, ?> mapTorrent) {
    String s;/*from  www  .  j  a  v a 2 s  . com*/
    long addedOn = MapUtils.getMapLong(mapTorrent, TransmissionVars.FIELD_TORRENT_DATE_ADDED, 0);
    s = addedOn <= 0 ? ""
            : DateUtils.getRelativeDateTimeString(getActivity(), addedOn * 1000, DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.WEEK_IN_MILLIS * 2, 0).toString();
    fillRow(a, R.id.torrentInfo_row_addedOn, R.id.torrentInfo_val_addedOn, s);

    long activeOn = MapUtils.getMapLong(mapTorrent, TransmissionVars.FIELD_TORRENT_DATE_ACTIVITY, 0);
    s = activeOn <= 0 ? ""
            : DateUtils.getRelativeDateTimeString(getActivity(), activeOn * 1000, DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.WEEK_IN_MILLIS * 2, 0).toString();
    fillRow(a, R.id.torrentInfo_row_lastActiveOn, R.id.torrentInfo_val_lastActiveOn, s);

    long doneOn = MapUtils.getMapLong(mapTorrent, TransmissionVars.FIELD_TORRENT_DATE_DONE, 0);
    s = doneOn <= 0 ? ""
            : DateUtils.getRelativeDateTimeString(getActivity(), doneOn * 1000, DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.WEEK_IN_MILLIS * 2, 0).toString();
    fillRow(a, R.id.torrentInfo_row_completedOn, R.id.torrentInfo_val_completedOn, s);

    long startedOn = MapUtils.getMapLong(mapTorrent, TransmissionVars.FIELD_TORRENT_DATE_STARTED, 0);
    s = startedOn <= 0 ? ""
            : DateUtils.getRelativeDateTimeString(getActivity(), startedOn * 1000, DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.WEEK_IN_MILLIS * 2, 0).toString();
    fillRow(a, R.id.torrentInfo_row_startedOn, R.id.torrentInfo_val_startedOn, s);

    long secondsDownloading = MapUtils.getMapLong(mapTorrent,
            TransmissionVars.FIELD_TORRENT_SECONDS_DOWNLOADING, 0);
    s = secondsDownloading <= 0 ? "" : DisplayFormatters.prettyFormat(secondsDownloading);
    fillRow(a, R.id.torrentInfo_row_downloadingFor, R.id.torrentInfo_val_downloadingFor, s);

    long secondsUploading = MapUtils.getMapLong(mapTorrent, TransmissionVars.FIELD_TORRENT_SECONDS_SEEDING, 0);
    s = secondsUploading <= 0 ? "" : DisplayFormatters.prettyFormat(secondsUploading);
    fillRow(a, R.id.torrentInfo_row_seedingFor, R.id.torrentInfo_val_seedingFor, s);

    long etaSecs = MapUtils.getMapLong(mapTorrent, TransmissionVars.FIELD_TORRENT_ETA, -1);
    s = etaSecs > 0 && etaSecs * 1000 < DateUtils.WEEK_IN_MILLIS ? DisplayFormatters.prettyFormat(etaSecs) : "";
    fillRow(a, R.id.torrentInfo_row_eta, R.id.torrentInfo_val_eta, s);

}

From source file:org.tigase.mobile.chat.ChatAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    ViewHolder holder = (ViewHolder) view.getTag();
    if (holder == null) {
        holder = new ViewHolder();
        view.setTag(holder);/*  w  w  w.j a va  2 s.  co m*/
        holder.nickname = (TextView) view.findViewById(R.id.chat_item_nickname);
        holder.webview = (TextView) view.findViewById(R.id.chat_item_body);
        holder.timestamp = (TextView) view.findViewById(R.id.chat_item_timestamp);
        holder.avatar = (ImageView) view.findViewById(R.id.user_avatar);
        holder.msgStatus = (ImageView) view.findViewById(R.id.msgStatus);
    }

    final int state = cursor.getInt(cursor.getColumnIndex(ChatTableMetaData.FIELD_STATE));

    if (state == ChatTableMetaData.STATE_INCOMING || state == ChatTableMetaData.STATE_INCOMING_UNREAD) {
        final BareJID account = BareJID
                .bareJIDInstance(cursor.getString(cursor.getColumnIndex(ChatTableMetaData.FIELD_ACCOUNT)));
        final BareJID jid = BareJID
                .bareJIDInstance(cursor.getString(cursor.getColumnIndex(ChatTableMetaData.FIELD_JID)));
        setAvatarForJid(holder.avatar, jid, cursor);
        JaxmppCore jaxmpp = ((MessengerApplication) context.getApplicationContext()).getMultiJaxmpp()
                .get(account);
        RosterItem ri = jaxmpp.getRoster().get(jid);
        holder.nickname.setText(ri == null ? jid.toString() : RosterDisplayTools.getDisplayName(ri));

        holder.nickname.setTextColor(context.getResources().getColor(R.color.message_his_text));
        holder.webview.setTextColor(context.getResources().getColor(R.color.message_his_text));
        holder.timestamp.setTextColor(context.getResources().getColor(R.color.message_his_text));

        view.setBackgroundColor(context.getResources().getColor(R.color.message_his_background));
        holder.msgStatus.setVisibility(View.GONE);
    } else if (state == ChatTableMetaData.STATE_OUT_NOT_SENT || state == ChatTableMetaData.STATE_OUT_SENT) {
        final BareJID jid = BareJID
                .bareJIDInstance(cursor.getString(cursor.getColumnIndex(ChatTableMetaData.FIELD_AUTHOR_JID)));
        setAvatarForJid(holder.avatar, jid, cursor);
        holder.nickname.setText(this.nickname == null ? jid.getLocalpart() : this.nickname);

        holder.nickname.setTextColor(context.getResources().getColor(R.color.message_mine_text));
        holder.webview.setTextColor(context.getResources().getColor(R.color.message_mine_text));
        holder.timestamp.setTextColor(context.getResources().getColor(R.color.message_mine_text));

        if (state == ChatTableMetaData.STATE_OUT_SENT) {
            int recpt = cursor.getInt(cursor.getColumnIndex(ChatTableMetaData.FIELD_RECEIPT_STATUS));
            if (recpt == 1) {
                holder.msgStatus.setImageResource(R.drawable.message_sent);
                holder.msgStatus.setVisibility(View.GONE);
            } else if (recpt == 2) {
                holder.msgStatus.setImageResource(R.drawable.message_delivered);
                holder.msgStatus.setVisibility(View.VISIBLE);
            } else
                holder.msgStatus.setVisibility(View.GONE);
        } else if (state == ChatTableMetaData.STATE_OUT_NOT_SENT) {
            holder.msgStatus.setImageResource(R.drawable.message_not_sent);
            holder.msgStatus.setVisibility(View.VISIBLE);
        }

        view.setBackgroundColor(context.getResources().getColor(R.color.message_mine_background));
    } else {
        holder.msgStatus.setVisibility(View.GONE);
        holder.nickname.setText("?");
    }

    // java.text.DateFormat df = DateFormat.getTimeFormat(context);
    final String txt = EscapeUtils
            .escape(cursor.getString(cursor.getColumnIndex(ChatTableMetaData.FIELD_BODY)));

    Spanned sp = Html.fromHtml(txt.replace("\n", "<br/>"));
    holder.webview.setText(sp);
    // webview.setMinimumHeight(webview.getMeasuredHeight());

    // Date t = new
    // Date(cursor.getLong(cursor.getColumnIndex(ChatTableMetaData.FIELD_TIMESTAMP)));
    // holder.timestamp.setText(df.format(t));
    long ts = cursor.getLong(cursor.getColumnIndex(ChatTableMetaData.FIELD_TIMESTAMP));
    CharSequence tsStr =
            // DateUtils.isToday(ts)
            // ? DateUtils.getRelativeTimeSpanString(ts, System.currentTimeMillis(),
            // DateUtils.MINUTE_IN_MILLIS) :
            DateUtils.getRelativeDateTimeString(mContext, ts, DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.WEEK_IN_MILLIS, 0);
    holder.timestamp.setText(tsStr);
}