Example usage for android.text.format DateUtils SECOND_IN_MILLIS

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

Introduction

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

Prototype

long SECOND_IN_MILLIS

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

Click Source Link

Usage

From source file:net.simonvt.cathode.ui.fragment.MovieFragment.java

@Override
public Loader<SimpleCursor> onCreateLoader(int i, Bundle bundle) {
    SimpleCursorLoader loader = new SimpleCursorLoader(getActivity(), Movies.withId(movieId), null, null, null,
            null);// w  ww  . j  a  v a  2  s  . co  m
    loader.setUpdateThrottle(2 * DateUtils.SECOND_IN_MILLIS);
    return loader;
}

From source file:net.niyonkuru.koodroid.ui.PageFragment.java

/**
 * Sync immediately or delay 5 seconds/*from w  w w  . j a  v  a  2 s .com*/
 */
protected void sync(boolean immediate) {
    if (immediate) {
        new Thread(mSyncTask).run();

        Toast.makeText(mContext, R.string.toast_sync_start, Toast.LENGTH_LONG).show();
    } else {
        /* delay the synchronization by 5 seconds */

        sHandler.postDelayed(mSyncTask, DateUtils.SECOND_IN_MILLIS * 5);
    }
}

From source file:gov.whitehouse.services.LiveService.java

private void scheduleNextUpdate() {
    Intent intent = new Intent(this, this.getClass());
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    long now = System.currentTimeMillis();
    int intervalSeconds = getResources().getInteger(R.integer.live_feed_update_interval_seconds);
    long intervalMillis = intervalSeconds * DateUtils.SECOND_IN_MILLIS;
    long nextUpdateTimeMillis = now + intervalMillis;

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
}

From source file:com.androidinspain.deskclock.timer.TimerSetupView.java

public long getTimeInMillis() {
    final int seconds = mInput[1] * 10 + mInput[0];
    final int minutes = mInput[3] * 10 + mInput[2];
    final int hours = mInput[5] * 10 + mInput[4];
    return seconds * DateUtils.SECOND_IN_MILLIS + minutes * DateUtils.MINUTE_IN_MILLIS
            + hours * DateUtils.HOUR_IN_MILLIS;
}

From source file:net.simonvt.cathode.ui.fragment.UpcomingShowsFragment.java

@Override
public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
    final Uri contentUri = Shows.SHOWS_UPCOMING;
    String where = null;/*from   ww w .j  av a  2s .  c om*/
    if (!showHidden) {
        where = ShowColumns.HIDDEN + "=0";
    }
    SimpleCursorLoader cl = new SimpleCursorLoader(getActivity(), contentUri, UpcomingAdapter.PROJECTION, where,
            null, sortBy.getSortOrder());
    cl.setUpdateThrottle(2 * DateUtils.SECOND_IN_MILLIS);
    return cl;
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from w w  w  . j  a va 2 s . c o m*/

    Context context = getContext();

    App.getApiManager().getEarthquakeService().getData().enqueue(new Callback<EarthquakeObject>() {
        @Override
        public void onResponse(Call<EarthquakeObject> call, Response<EarthquakeObject> response) {
            EarthquakeObject earthquake = response.body();

            Vector<ContentValues> cVVector = new Vector<>(earthquake.getFeatures().size());

            double currentBiggest = 0.0;
            ContentValues notifyValues = null;

            for (Feature each : earthquake.getFeatures()) {

                ContentValues earthquakeValues = new ContentValues();

                earthquakeValues.put(EarthquakeColumns.PLACE, each.getProperties().getPlace());
                earthquakeValues.put(EarthquakeColumns.ID_EARTH, each.getId());
                earthquakeValues.put(EarthquakeColumns.MAG, each.getProperties().getMag());
                earthquakeValues.put(EarthquakeColumns.TYPE, each.getProperties().getType());
                earthquakeValues.put(EarthquakeColumns.ALERT, each.getProperties().getAlert());
                earthquakeValues.put(EarthquakeColumns.TIME, each.getProperties().getTime());
                earthquakeValues.put(EarthquakeColumns.URL, each.getProperties().getUrl());
                earthquakeValues.put(EarthquakeColumns.DETAIL, each.getProperties().getDetail());
                earthquakeValues.put(EarthquakeColumns.DEPTH, each.getGeometry().getCoordinates().get(2));
                earthquakeValues.put(EarthquakeColumns.LONGITUDE, each.getGeometry().getCoordinates().get(0));
                earthquakeValues.put(EarthquakeColumns.LATITUDE, each.getGeometry().getCoordinates().get(1));

                LatLng latLng = new LatLng(each.getGeometry().getCoordinates().get(1),
                        each.getGeometry().getCoordinates().get(0));
                LatLng location = LocationUtils.getLocation(context);
                earthquakeValues.put(EarthquakeColumns.DISTANCE, LocationUtils.getDistance(latLng, location));

                cVVector.add(earthquakeValues);

                if (each.getProperties().getMag() != null && each.getProperties().getMag() > currentBiggest) {
                    currentBiggest = each.getProperties().getMag();
                    notifyValues = new ContentValues(earthquakeValues);
                    notifyValues.put(EarthquakeColumns.PLACE,
                            Utilities.formatEarthquakePlace(each.getProperties().getPlace()));
                }
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = context.getContentResolver();

            if (cVVector.size() > 0) {
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(EarthquakeColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus one to delete old data from the database
            Date date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS);

            int deleted = resolver.delete(EarthquakeColumns.CONTENT_URI, EarthquakeColumns.TIME + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
            Log.v(TAG, "Service Complete. " + inserted + " Inserted, " + deleted + " deleted");
            sendNotification(notifyValues);
        }

        @Override
        public void onFailure(Call<EarthquakeObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    App.getNewsManager().getNewsService().getNews().enqueue(new Callback<Rss>() {
        @Override
        public void onResponse(Call<Rss> call, Response<Rss> response) {
            Channel news = response.body().getChannel();

            Vector<ContentValues> cVVector = new Vector<>(news.getItem().size());

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",
                    Locale.getDefault());
            Date date = new Date();

            for (Item each : news.getItem()) {

                ContentValues weatherValues = new ContentValues();

                try {
                    date = simpleDateFormat.parse(each.getPubDate());
                } catch (ParseException e) {
                    Log.e(TAG, "e:" + e);
                }

                weatherValues.put(NewsColumns.DATE, date.getTime());
                weatherValues.put(NewsColumns.TITLE, each.getTitle());
                weatherValues.put(NewsColumns.DESCRIPTION,
                        Html.toHtml(new SpannedString(each.getDescription())));
                weatherValues.put(NewsColumns.URL, each.getLink());
                weatherValues.put(NewsColumns.GUID, each.getGuid().getContent());

                cVVector.add(weatherValues);
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = getContext().getContentResolver();

            if (cVVector.size() > 0) {

                // Student: call bulkInsert to add the weatherEntries to the database here
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(NewsColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus two to delete old data from the database
            date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS * 3);

            int deleted = resolver.delete(NewsColumns.CONTENT_URI, NewsColumns.DATE + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
        }

        @Override
        public void onFailure(Call<Rss> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    // TODO: 4/22/16 possible refactoring 
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String lastNotificationKey = context.getString(R.string.sharedprefs_key_last_countupdate);
    long lastSync = prefs.getLong(lastNotificationKey, DateUtils.DAY_IN_MILLIS);

    if (System.currentTimeMillis() - lastSync >= Utilities.getSyncIntervalPrefs(context)
            * DateUtils.SECOND_IN_MILLIS) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        Date date = new Date(System.currentTimeMillis());

        String startTime[] = new String[] { simpleDateFormat.format(date.getTime() - DateUtils.YEAR_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS * 30),
                simpleDateFormat.format(date.getTime() - DateUtils.WEEK_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS) };

        String endTime = simpleDateFormat.format(date);

        int iterator = 1;
        while (iterator < CountColumns.ALL_COLUMNS.length) {
            final int round = iterator;

            App.getApiManager().getEarthquakeService().getEarthquakeStats(startTime[round - 1], endTime)
                    .enqueue(new Callback<CountEarthquakes>() {
                        @Override
                        public void onResponse(Call<CountEarthquakes> call,
                                Response<CountEarthquakes> response) {
                            ContentValues count = new ContentValues();
                            count.put(CountColumns.ALL_COLUMNS[round], response.body().getCount());

                            ContentResolver contentResolver = context.getContentResolver();

                            Cursor cursor = contentResolver.query(CountColumns.CONTENT_URI, null, null, null,
                                    null);

                            if (cursor != null) {
                                if (cursor.getCount() < 1) {
                                    long inserted = ContentUris
                                            .parseId(contentResolver.insert(CountColumns.CONTENT_URI, count));
                                    //Log.d(TAG, "inserted:" + inserted);
                                } else {
                                    int updated = contentResolver.update(CountColumns.CONTENT_URI, count,
                                            CountColumns._ID + " = ?", new String[] { "1" });
                                    //Log.d(TAG, "updated: " + updated);
                                }
                                cursor.close();
                            }

                        }

                        @Override
                        public void onFailure(Call<CountEarthquakes> call, Throwable t) {
                            Log.e(TAG, "Error: " + t);
                        }
                    });
            iterator++;
        }

        //refreshing last sync
        prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).apply();
    }

    // notify PagerActivity that data has been updated
    context.getContentResolver().notifyChange(EarthquakeColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(NewsColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(CountColumns.CONTENT_URI, null, false);

    updateWidgets();
}

From source file:io.plaidapp.ui.DribbbleShot.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dribbble_shot);
    shot = getIntent().getParcelableExtra(EXTRA_SHOT);
    setupDribbble();/*from w  w  w  .  j av  a 2s  .  com*/
    setExitSharedElementCallback(fabLoginSharedElementCallback);
    getWindow().getSharedElementReturnTransition().addListener(shotReturnHomeListener);
    circleTransform = new CircleTransform(this);
    Resources res = getResources();

    ButterKnife.bind(this);
    View shotDescription = getLayoutInflater().inflate(R.layout.dribbble_shot_description, commentsList, false);
    shotSpacer = shotDescription.findViewById(R.id.shot_spacer);
    title = shotDescription.findViewById(R.id.shot_title);
    description = shotDescription.findViewById(R.id.shot_description);
    shotActions = (LinearLayout) shotDescription.findViewById(R.id.shot_actions);
    likeCount = (Button) shotDescription.findViewById(R.id.shot_like_count);
    viewCount = (Button) shotDescription.findViewById(R.id.shot_view_count);
    share = (Button) shotDescription.findViewById(R.id.shot_share_action);
    playerName = (TextView) shotDescription.findViewById(R.id.player_name);
    playerAvatar = (ImageView) shotDescription.findViewById(R.id.player_avatar);
    shotTimeAgo = (TextView) shotDescription.findViewById(R.id.shot_time_ago);
    commentsList = (ListView) findViewById(R.id.dribbble_comments);
    commentsList.addHeaderView(shotDescription);
    setupCommenting();
    commentsList.setOnScrollListener(scrollListener);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            expandImageAndFinish();
        }
    });
    fab.setOnClickListener(fabClick);
    chromeFader = new ElasticDragDismissFrameLayout.SystemChromeFader(getWindow()) {
        @Override
        public void onDragDismissed() {
            expandImageAndFinish();
        }
    };

    // load the main image
    final int[] imageSize = shot.images.bestSize();
    Glide.with(this).load(shot.images.best()).listener(shotLoadListener)
            .diskCacheStrategy(DiskCacheStrategy.SOURCE).priority(Priority.IMMEDIATE)
            .override(imageSize[0], imageSize[1]).into(imageView);
    imageView.setOnClickListener(shotClick);
    shotSpacer.setOnClickListener(shotClick);

    postponeEnterTransition();
    imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            calculateFabPosition();
            enterAnimation(savedInstanceState != null);
            startPostponedEnterTransition();
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ((FabOverlapTextView) title).setText(shot.title);
    } else {
        ((TextView) title).setText(shot.title);
    }
    if (!TextUtils.isEmpty(shot.description)) {
        final Spanned descText = shot.getParsedDescription(
                ContextCompat.getColorStateList(this, R.color.dribbble_links),
                ContextCompat.getColor(this, R.color.dribbble_link_highlight));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ((FabOverlapTextView) description).setText(descText);
        } else {
            HtmlUtils.setTextWithNiceLinks((TextView) description, descText);
        }
    } else {
        description.setVisibility(View.GONE);
    }
    NumberFormat nf = NumberFormat.getInstance();
    likeCount.setText(
            res.getQuantityString(R.plurals.likes, (int) shot.likes_count, nf.format(shot.likes_count)));
    // TODO onClick show likes
    viewCount.setText(
            res.getQuantityString(R.plurals.views, (int) shot.views_count, nf.format(shot.views_count)));
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ShareDribbbleImageTask(DribbbleShot.this, shot).execute();
        }
    });
    if (shot.user != null) {
        playerName.setText("" + shot.user.name);
        Glide.with(this).load(shot.user.avatar_url).transform(circleTransform)
                .placeholder(R.drawable.avatar_placeholder).into(playerAvatar);
        playerAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DribbbleShot.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(shot.user.html_url)));
            }
        });
        if (shot.created_at != null) {
            shotTimeAgo.setText(DateUtils.getRelativeTimeSpanString(shot.created_at.getTime(),
                    System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS));
        }
    } else {
        playerName.setVisibility(View.GONE);
        playerAvatar.setVisibility(View.GONE);
        shotTimeAgo.setVisibility(View.GONE);
    }

    if (shot.comments_count > 0) {
        loadComments();
    } else {
        commentsList.setAdapter(getNoCommentsAdapter());
    }
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static List<ECKey> readKeys(@Nonnull final BufferedReader in) throws IOException {
    try {//from  w w  w.  ja v  a2  s .  c o m
        final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        final List<ECKey> keys = new LinkedList<ECKey>();

        while (true) {
            final String line = in.readLine();
            if (line == null)
                break; // eof
            if (line.trim().isEmpty() || line.charAt(0) == '#')
                continue; // skip comment

            final String[] parts = line.split(" ");

            final ECKey key = new DumpedPrivateKey(Constants.NETWORK_PARAMETERS, parts[0]).getKey();
            key.setCreationTimeSeconds(
                    parts.length >= 2 ? format.parse(parts[1]).getTime() / DateUtils.SECOND_IN_MILLIS : 0);

            keys.add(key);
        }

        return keys;
    } catch (final AddressFormatException x) {
        throw new IOException("cannot read keys", x);
    } catch (final ParseException x) {
        throw new IOException("cannot read keys", x);
    }
}

From source file:com.tasomaniac.openwith.resolver.ResolverActivity.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private String getCallerPackageLollipop() {
    UsageStatsManager mUsm = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    // We get usage stats for the last 10 seconds
    List<UsageStats> stats = mUsm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
            time - 10 * DateUtils.SECOND_IN_MILLIS, time);
    if (stats == null) {
        return null;
    }//from ww  w. j  a  va 2 s  . c om

    UsageStats lastUsage = null;
    for (UsageStats currentUsage : stats) {
        String currentPackage = currentUsage.getPackageName();
        if (BuildConfig.APPLICATION_ID.equals(currentPackage) || "android".equals(currentPackage)) {
            continue;
        }
        if (lastUsage == null || lastUsage.getLastTimeUsed() < currentUsage.getLastTimeUsed()) {
            lastUsage = currentUsage;
        }
    }
    if (lastUsage != null) {
        return lastUsage.getPackageName();
    }

    return null;
}

From source file:net.niyonkuru.koodroid.ui.UsageFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    switch (id) {
    case AIRTIME_TOKEN: {
        final Uri uri = Airtimes.buildAirtimeUri(getSubscriber());
        return new CursorLoader(mContext, uri, AirtimesQuery.PROJECTION, null, null, null);
    }/*  ww  w  . java  2s.c o  m*/
    case TEXT_TOKEN: {
        final Resources resources = mContext.getResources();

        final String textUsage = resources.getString(R.string.parser_usage_service_text);
        final String intlTextUsage = resources.getString(R.string.parser_usage_service_intl);

        final String selection = Usages.USAGE_SERVICE + "='" + textUsage + "'" + " OR " + Usages.USAGE_SERVICE
                + "='" + intlTextUsage + "'";

        CursorLoader loader = new CursorLoader(mContext, Subscribers.buildUsagesUri(getSubscriber()),
                UsagesQuery.PROJECTION, selection, null, null);
        loader.setUpdateThrottle(DateUtils.SECOND_IN_MILLIS);

        return loader;
    }
    case DATA_TOKEN: {
        final String dataUsage = getResources().getString(R.string.parser_usage_service_data);

        final String selection = Usages.USAGE_SERVICE + "='" + dataUsage + "'";

        CursorLoader loader = new CursorLoader(mContext, Subscribers.buildUsagesUri(getSubscriber()),
                UsagesQuery.PROJECTION, selection, null, null);
        loader.setUpdateThrottle(DateUtils.SECOND_IN_MILLIS);

        return loader;
    }
    }

    return null;
}