aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/tv/util/Utils.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/com/android/tv/util/Utils.java')
-rw-r--r--src/com/android/tv/util/Utils.java484
1 files changed, 225 insertions, 259 deletions
diff --git a/src/com/android/tv/util/Utils.java b/src/com/android/tv/util/Utils.java
index d11bab3c..a75bd446 100644
--- a/src/com/android/tv/util/Utils.java
+++ b/src/com/android/tv/util/Utils.java
@@ -38,22 +38,16 @@ import android.support.annotation.VisibleForTesting;
import android.support.annotation.WorkerThread;
import android.text.TextUtils;
import android.text.format.DateUtils;
-import android.util.ArraySet;
import android.util.Log;
import android.view.View;
-
-import com.android.tv.ApplicationSingletons;
import com.android.tv.R;
-import com.android.tv.TvApplication;
-import com.android.tv.common.BuildConfig;
+import com.android.tv.TvSingletons;
import com.android.tv.common.SoftPreconditions;
-import com.android.tv.data.Channel;
+import com.android.tv.common.util.Clock;
import com.android.tv.data.GenreItems;
import com.android.tv.data.Program;
import com.android.tv.data.StreamInfo;
-import com.android.tv.experiments.Experiments;
-
-import java.io.File;
+import com.android.tv.data.api.Channel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
@@ -69,18 +63,13 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-/**
- * A class that includes convenience methods for accessing TvProvider database.
- */
+/** A class that includes convenience methods for accessing TvProvider database. */
public class Utils {
private static final String TAG = "Utils";
private static final boolean DEBUG = false;
- private static final SimpleDateFormat ISO_8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ",
- Locale.US);
-
public static final String EXTRA_KEY_ACTION = "action";
- public static final String EXTRA_ACTION_SHOW_TV_INPUT ="show_tv_input";
+ public static final String EXTRA_ACTION_SHOW_TV_INPUT = "show_tv_input";
public static final String EXTRA_KEY_FROM_LAUNCHER = "from_launcher";
public static final String EXTRA_KEY_RECORDED_PROGRAM_ID = "recorded_program_id";
public static final String EXTRA_KEY_RECORDED_PROGRAM_SEEK_TIME = "recorded_program_seek_time";
@@ -97,8 +86,7 @@ public class Utils {
private static final String PREF_KEY_LAST_WATCHED_CHANNEL_URI = "last_watched_channel_uri";
private static final String PREF_KEY_LAST_WATCHED_TUNER_INPUT_ID =
"last_watched_tuner_input_id";
- private static final String PREF_KEY_RECORDING_FAILED_REASONS =
- "recording_failed_reasons";
+ private static final String PREF_KEY_RECORDING_FAILED_REASONS = "recording_failed_reasons";
private static final String PREF_KEY_FAILED_SCHEDULED_RECORDING_INFO_SET =
"failed_scheduled_recording_info_set";
@@ -121,15 +109,6 @@ public class Utils {
private static final long HALF_MINUTE_MS = TimeUnit.SECONDS.toMillis(30);
private static final long ONE_DAY_MS = TimeUnit.DAYS.toMillis(1);
- // Hardcoded list for known bundled inputs not written by OEM/SOCs.
- // Bundled (system) inputs not in the list will get the high priority
- // so they and their channels come first in the UI.
- private static final Set<String> BUNDLED_PACKAGE_SET = new ArraySet<>();
-
- static {
- BUNDLED_PACKAGE_SET.add("com.android.tv");
- }
-
private enum AspectRatio {
ASPECT_RATIO_4_3(4, 3),
ASPECT_RATIO_16_9(16, 9),
@@ -150,13 +129,11 @@ public class Utils {
}
}
- private Utils() {
- }
+ private Utils() {}
public static String buildSelectionForIds(String idName, List<Long> ids) {
StringBuilder sb = new StringBuilder();
- sb.append(idName).append(" in (")
- .append(ids.get(0));
+ sb.append(idName).append(" in (").append(ids.get(0));
for (int i = 1; i < ids.size(); ++i) {
sb.append(",").append(ids.get(i));
}
@@ -171,8 +148,8 @@ public class Utils {
}
Uri channelUri = TvContract.buildChannelUri(channelId);
String[] projection = {TvContract.Channels.COLUMN_INPUT_ID};
- try (Cursor cursor = context.getContentResolver()
- .query(channelUri, projection, null, null, null)) {
+ try (Cursor cursor =
+ context.getContentResolver().query(channelUri, projection, null, null, null)) {
if (cursor != null && cursor.moveToNext()) {
return Utils.intern(cursor.getString(0));
}
@@ -185,60 +162,61 @@ public class Utils {
Log.e(TAG, "setLastWatchedChannel: channel cannot be null");
return;
}
- PreferenceManager.getDefaultSharedPreferences(context).edit()
- .putString(PREF_KEY_LAST_WATCHED_CHANNEL_URI, channel.getUri().toString()).apply();
+ PreferenceManager.getDefaultSharedPreferences(context)
+ .edit()
+ .putString(PREF_KEY_LAST_WATCHED_CHANNEL_URI, channel.getUri().toString())
+ .apply();
if (!channel.isPassthrough()) {
long channelId = channel.getId();
if (channel.getId() < 0) {
throw new IllegalArgumentException("channelId should be equal to or larger than 0");
}
- PreferenceManager.getDefaultSharedPreferences(context).edit()
+ PreferenceManager.getDefaultSharedPreferences(context)
+ .edit()
.putLong(PREF_KEY_LAST_WATCHED_CHANNEL_ID, channelId)
- .putLong(PREF_KEY_LAST_WATCHED_CHANNEL_ID_FOR_INPUT + channel.getInputId(),
+ .putLong(
+ PREF_KEY_LAST_WATCHED_CHANNEL_ID_FOR_INPUT + channel.getInputId(),
channelId)
.putString(PREF_KEY_LAST_WATCHED_TUNER_INPUT_ID, channel.getInputId())
.apply();
}
}
- /**
- * Sets recording failed reason.
- */
+ /** Sets recording failed reason. */
public static void setRecordingFailedReason(Context context, int reason) {
long reasons = getRecordingFailedReasons(context) | 0x1 << reason;
- PreferenceManager.getDefaultSharedPreferences(context).edit()
+ PreferenceManager.getDefaultSharedPreferences(context)
+ .edit()
.putLong(PREF_KEY_RECORDING_FAILED_REASONS, reasons)
.apply();
}
- /**
- * Adds the info of failed scheduled recording.
- */
- public static void addFailedScheduledRecordingInfo(Context context,
- String scheduledRecordingInfo) {
+ /** Adds the info of failed scheduled recording. */
+ public static void addFailedScheduledRecordingInfo(
+ Context context, String scheduledRecordingInfo) {
Set<String> failedScheduledRecordingInfoSet = getFailedScheduledRecordingInfoSet(context);
failedScheduledRecordingInfoSet.add(scheduledRecordingInfo);
- PreferenceManager.getDefaultSharedPreferences(context).edit()
- .putStringSet(PREF_KEY_FAILED_SCHEDULED_RECORDING_INFO_SET,
+ PreferenceManager.getDefaultSharedPreferences(context)
+ .edit()
+ .putStringSet(
+ PREF_KEY_FAILED_SCHEDULED_RECORDING_INFO_SET,
failedScheduledRecordingInfoSet)
.apply();
}
- /**
- * Clears the failed scheduled recording info set.
- */
+ /** Clears the failed scheduled recording info set. */
public static void clearFailedScheduledRecordingInfoSet(Context context) {
- PreferenceManager.getDefaultSharedPreferences(context).edit()
+ PreferenceManager.getDefaultSharedPreferences(context)
+ .edit()
.remove(PREF_KEY_FAILED_SCHEDULED_RECORDING_INFO_SET)
.apply();
}
- /**
- * Clears recording failed reason.
- */
+ /** Clears recording failed reason. */
public static void clearRecordingFailedReason(Context context, int reason) {
long reasons = getRecordingFailedReasons(context) & ~(0x1 << reason);
- PreferenceManager.getDefaultSharedPreferences(context).edit()
+ PreferenceManager.getDefaultSharedPreferences(context)
+ .edit()
.putLong(PREF_KEY_RECORDING_FAILED_REASONS, reasons)
.apply();
}
@@ -258,9 +236,7 @@ public class Utils {
.getString(PREF_KEY_LAST_WATCHED_CHANNEL_URI, null);
}
- /**
- * Returns the last watched tuner input id.
- */
+ /** Returns the last watched tuner input id. */
public static String getLastWatchedTunerInputId(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_LAST_WATCHED_TUNER_INPUT_ID, null);
@@ -268,32 +244,28 @@ public class Utils {
private static long getRecordingFailedReasons(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
- .getLong(PREF_KEY_RECORDING_FAILED_REASONS,
- RECORDING_FAILED_REASON_NONE);
+ .getLong(PREF_KEY_RECORDING_FAILED_REASONS, RECORDING_FAILED_REASON_NONE);
}
- /**
- * Returns the failed scheduled recordings info set.
- */
+ /** Returns the failed scheduled recordings info set. */
public static Set<String> getFailedScheduledRecordingInfoSet(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getStringSet(PREF_KEY_FAILED_SCHEDULED_RECORDING_INFO_SET, new HashSet<>());
}
- /**
- * Checks do recording failed reason exist.
- */
+ /** Checks do recording failed reason exist. */
public static boolean hasRecordingFailedReason(Context context, int reason) {
long reasons = getRecordingFailedReasons(context);
return (reasons & 0x1 << reason) != 0;
}
/**
- * Returns {@code true}, if {@code uri} specifies an input, which is usually generated
- * from {@link TvContract#buildChannelsUriForInput}.
+ * Returns {@code true}, if {@code uri} specifies an input, which is usually generated from
+ * {@link TvContract#buildChannelsUriForInput}.
*/
public static boolean isChannelUriForInput(Uri uri) {
- return isTvUri(uri) && PATH_CHANNEL.equals(uri.getPathSegments().get(0))
+ return isTvUri(uri)
+ && PATH_CHANNEL.equals(uri.getPathSegments().get(0))
&& !TextUtils.isEmpty(uri.getQueryParameter("input"));
}
@@ -314,7 +286,8 @@ public class Utils {
}
private static boolean isTvUri(Uri uri) {
- return uri != null && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())
+ return uri != null
+ && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())
&& TvContract.AUTHORITY.equals(uri.getAuthority());
}
@@ -323,23 +296,17 @@ public class Utils {
return pathSegments.size() == 2 && pathSegment.equals(pathSegments.get(0));
}
- /**
- * Returns {@code true}, if {@code uri} is a programs URI.
- */
+ /** Returns {@code true}, if {@code uri} is a programs URI. */
public static boolean isProgramsUri(Uri uri) {
return isTvUri(uri) && PATH_PROGRAM.equals(uri.getPathSegments().get(0));
}
- /**
- * Returns {@code true}, if {@code uri} is a programs URI.
- */
+ /** Returns {@code true}, if {@code uri} is a programs URI. */
public static boolean isRecordedProgramsUri(Uri uri) {
return isTvUri(uri) && PATH_RECORDED_PROGRAM.equals(uri.getPathSegments().get(0));
}
- /**
- * Gets the info of the program on particular time.
- */
+ /** Gets the info of the program on particular time. */
@WorkerThread
public static Program getProgramAt(Context context, long channelId, long timeMs) {
if (channelId == Channel.INVALID_ID) {
@@ -355,10 +322,11 @@ public class Utils {
Log.w(TAG, message);
}
}
- Uri uri = TvContract.buildProgramsUriForChannel(TvContract.buildChannelUri(channelId),
- timeMs, timeMs);
- try (Cursor cursor = context.getContentResolver().query(uri, Program.PROJECTION,
- null, null, null)) {
+ Uri uri =
+ TvContract.buildProgramsUriForChannel(
+ TvContract.buildChannelUri(channelId), timeMs, timeMs);
+ try (Cursor cursor =
+ context.getContentResolver().query(uri, Program.PROJECTION, null, null, null)) {
if (cursor != null && cursor.moveToNext()) {
return Program.fromCursor(cursor);
}
@@ -366,55 +334,98 @@ public class Utils {
return null;
}
- /**
- * Gets the info of the current program.
- */
+ /** Gets the info of the current program. */
@WorkerThread
public static Program getCurrentProgram(Context context, long channelId) {
return getProgramAt(context, channelId, System.currentTimeMillis());
}
- /**
- * Returns the round off minutes when convert milliseconds to minutes.
- */
+ /** Returns the round off minutes when convert milliseconds to minutes. */
public static int getRoundOffMinsFromMs(long millis) {
// Round off the result by adding half minute to the original ms.
return (int) TimeUnit.MILLISECONDS.toMinutes(millis + HALF_MINUTE_MS);
}
/**
- * Returns duration string according to the date & time format.
- * If {@code startUtcMillis} and {@code endUtcMills} are equal,
- * formatted time will be returned instead.
+ * Returns duration string according to the date & time format. If {@code startUtcMillis} and
+ * {@code endUtcMills} are equal, formatted time will be returned instead.
*
* @param startUtcMillis start of duration in millis. Should be less than {code endUtcMillis}.
* @param endUtcMillis end of duration in millis. Should be larger than {@code startUtcMillis}.
- * @param useShortFormat {@code true} if abbreviation is needed to save space.
- * In that case, date will be omitted if duration starts from today
- * and is less than a day. If it's necessary,
- * {@link DateUtils#FORMAT_NUMERIC_DATE} is used otherwise.
+ * @param useShortFormat {@code true} if abbreviation is needed to save space. In that case,
+ * date will be omitted if duration starts from today and is less than a day. If it's
+ * necessary, {@link DateUtils#FORMAT_NUMERIC_DATE} is used otherwise.
*/
public static String getDurationString(
Context context, long startUtcMillis, long endUtcMillis, boolean useShortFormat) {
- return getDurationString(context, System.currentTimeMillis(), startUtcMillis, endUtcMillis,
- useShortFormat, 0);
+ return getDurationString(
+ context,
+ System.currentTimeMillis(),
+ startUtcMillis,
+ endUtcMillis,
+ useShortFormat,
+ 0);
}
- @VisibleForTesting
- static String getDurationString(Context context, long baseMillis, long startUtcMillis,
- long endUtcMillis, boolean useShortFormat, int flag) {
- return getDurationString(context, startUtcMillis, endUtcMillis,
- useShortFormat, !isInGivenDay(baseMillis, startUtcMillis), true, flag);
+ /**
+ * Returns duration string according to the date & time format. If {@code startUtcMillis} and
+ * {@code endUtcMills} are equal, formatted time will be returned instead.
+ *
+ * @param clock the clock used to get the current time.
+ * @param startUtcMillis start of duration in millis. Should be less than {code endUtcMillis}.
+ * @param endUtcMillis end of duration in millis. Should be larger than {@code startUtcMillis}.
+ * @param useShortFormat {@code true} if abbreviation is needed to save space. In that case,
+ * date will be omitted if duration starts from today and is less than a day. If it's
+ * necessary, {@link DateUtils#FORMAT_NUMERIC_DATE} is used otherwise.
+ */
+ public static String getDurationString(
+ Context context,
+ Clock clock,
+ long startUtcMillis,
+ long endUtcMillis,
+ boolean useShortFormat) {
+ return getDurationString(
+ context,
+ clock.currentTimeMillis(),
+ startUtcMillis,
+ endUtcMillis,
+ useShortFormat,
+ 0);
}
- /**
- * Returns duration string according to the time format, may not contain date information.
- * Note: At least one of showDate and showTime should be true.
+ @VisibleForTesting
+ static String getDurationString(
+ Context context,
+ long baseMillis,
+ long startUtcMillis,
+ long endUtcMillis,
+ boolean useShortFormat,
+ int flag) {
+ return getDurationString(
+ context,
+ startUtcMillis,
+ endUtcMillis,
+ useShortFormat,
+ !isInGivenDay(baseMillis, startUtcMillis),
+ true,
+ flag);
+ }
+
+ /**
+ * Returns duration string according to the time format, may not contain date information. Note:
+ * At least one of showDate and showTime should be true.
*/
- public static String getDurationString(Context context, long startUtcMillis, long endUtcMillis,
- boolean useShortFormat, boolean showDate, boolean showTime, int flag) {
- flag |= DateUtils.FORMAT_ABBREV_MONTH
- | ((useShortFormat) ? DateUtils.FORMAT_NUMERIC_DATE : 0);
+ public static String getDurationString(
+ Context context,
+ long startUtcMillis,
+ long endUtcMillis,
+ boolean useShortFormat,
+ boolean showDate,
+ boolean showTime,
+ int flag) {
+ flag |=
+ DateUtils.FORMAT_ABBREV_MONTH
+ | ((useShortFormat) ? DateUtils.FORMAT_NUMERIC_DATE : 0);
SoftPreconditions.checkArgument(showTime || showDate);
if (showTime) {
flag |= DateUtils.FORMAT_SHOW_TIME;
@@ -431,20 +442,21 @@ public class Utils {
// Do not show date for short format.
// Subtracting one day is needed because {@link DateUtils@formatDateRange}
// automatically shows date if the duration covers multiple days.
- return DateUtils.formatDateRange(context,
- startUtcMillis, endUtcMillis - TimeUnit.DAYS.toMillis(1), flag);
+ return DateUtils.formatDateRange(
+ context, startUtcMillis, endUtcMillis - TimeUnit.DAYS.toMillis(1), flag);
}
}
// Workaround of b/28740989.
// Add 1 msec to endUtcMillis to avoid DateUtils' bug with a duration of 12:00AM~12:00AM.
String dateRange = DateUtils.formatDateRange(context, startUtcMillis, endUtcMillis, flag);
- return startUtcMillis == endUtcMillis || dateRange.contains("–") ? dateRange
+ return startUtcMillis == endUtcMillis || dateRange.contains("–")
+ ? dateRange
: DateUtils.formatDateRange(context, startUtcMillis, endUtcMillis + 1, flag);
}
/**
- * Checks if two given time (in milliseconds) are in the same day with regard to the
- * locale timezone.
+ * Checks if two given time (in milliseconds) are in the same day with regard to the locale
+ * timezone.
*/
public static boolean isInGivenDay(long dayToMatchInMillis, long subjectTimeInMillis) {
TimeZone timeZone = Calendar.getInstance().getTimeZone();
@@ -456,9 +468,7 @@ public class Utils {
== Utils.floorTime(subjectTimeInMillis + offset, ONE_DAY_MS);
}
- /**
- * Calculate how many days between two milliseconds.
- */
+ /** Calculate how many days between two milliseconds. */
public static int computeDateDifference(long startTimeMs, long endTimeMs) {
Calendar calFrom = Calendar.getInstance();
Calendar calTo = Calendar.getInstance();
@@ -476,17 +486,23 @@ public class Utils {
cal.set(Calendar.MILLISECOND, 0);
}
- /**
- * Returns the last millisecond of a day which the millis belongs to.
- */
+ /** Returns the last millisecond of a day which the millis belongs to. */
public static long getLastMillisecondOfDay(long millis) {
- Calendar calender = Calendar.getInstance();
- calender.setTime(new Date(millis));
- calender.set(Calendar.HOUR_OF_DAY, 23);
- calender.set(Calendar.MINUTE, 59);
- calender.set(Calendar.SECOND, 59);
- calender.set(Calendar.MILLISECOND, 999);
- return calender.getTimeInMillis();
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(new Date(millis));
+ calendar.set(Calendar.HOUR_OF_DAY, 23);
+ calendar.set(Calendar.MINUTE, 59);
+ calendar.set(Calendar.SECOND, 59);
+ calendar.set(Calendar.MILLISECOND, 999);
+ return calendar.getTimeInMillis();
+ }
+
+ /** Returns the last millisecond of a day which the millis belongs to. */
+ public static long getFirstMillisecondOfDay(long millis) {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(new Date(millis));
+ resetCalendar(calendar);
+ return calendar.getTimeInMillis();
}
public static String getAspectRatioString(int width, int height) {
@@ -494,7 +510,7 @@ public class Utils {
return "";
}
- for (AspectRatio ratio: AspectRatio.values()) {
+ for (AspectRatio ratio : AspectRatio.values()) {
if (Math.abs((float) ratio.height / ratio.width - (float) height / width) < 0.05f) {
return ratio.toString();
}
@@ -531,11 +547,9 @@ public class Utils {
public static String getVideoDefinitionLevelString(Context context, int videoFormat) {
switch (videoFormat) {
case StreamInfo.VIDEO_DEFINITION_LEVEL_ULTRA_HD:
- return context.getResources().getString(
- R.string.video_definition_level_ultra_hd);
+ return context.getResources().getString(R.string.video_definition_level_ultra_hd);
case StreamInfo.VIDEO_DEFINITION_LEVEL_FULL_HD:
- return context.getResources().getString(
- R.string.video_definition_level_full_hd);
+ return context.getResources().getString(R.string.video_definition_level_full_hd);
case StreamInfo.VIDEO_DEFINITION_LEVEL_HD:
return context.getResources().getString(R.string.video_definition_level_hd);
case StreamInfo.VIDEO_DEFINITION_LEVEL_SD:
@@ -570,8 +584,8 @@ public class Utils {
return false;
}
- public static String getMultiAudioString(Context context, TvTrackInfo track,
- boolean showSampleRate) {
+ public static String getMultiAudioString(
+ Context context, TvTrackInfo track, boolean showSampleRate) {
if (track.getType() != TvTrackInfo.TYPE_AUDIO) {
throw new IllegalArgumentException("Not an audio track: " + track);
}
@@ -600,11 +614,17 @@ public class Utils {
break;
default:
if (track.getAudioChannelCount() > 0) {
- metadata.append(context.getString(R.string.multi_audio_channel_suffix,
- track.getAudioChannelCount()));
+ metadata.append(
+ context.getString(
+ R.string.multi_audio_channel_suffix,
+ track.getAudioChannelCount()));
} else {
- Log.d(TAG, "Invalid audio channel count (" + track.getAudioChannelCount()
- + ") found for the audio track: " + track);
+ Log.d(
+ TAG,
+ "Invalid audio channel count ("
+ + track.getAudioChannelCount()
+ + ") found for the audio track: "
+ + track);
}
break;
}
@@ -628,8 +648,8 @@ public class Utils {
if (metadata.length() == 0) {
return language;
}
- return context.getString(R.string.multi_audio_display_string_with_channel, language,
- metadata.toString());
+ return context.getString(
+ R.string.multi_audio_display_string_with_channel, language, metadata.toString());
}
public static boolean isEqualLanguage(String lang1, String lang2) {
@@ -647,19 +667,19 @@ public class Utils {
}
public static boolean isIntentAvailable(Context context, Intent intent) {
- return context.getPackageManager().queryIntentActivities(
- intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
+ return context.getPackageManager()
+ .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
+ .size()
+ > 0;
}
- /**
- * Returns the label for a given input. Returns the custom label, if any.
- */
+ /** Returns the label for a given input. Returns the custom label, if any. */
public static String loadLabel(Context context, TvInputInfo input) {
if (input == null) {
return null;
}
TvInputManagerHelper inputManager =
- TvApplication.getSingletons(context).getTvInputManagerHelper();
+ TvSingletons.getSingletons(context).getTvInputManagerHelper();
CharSequence customLabel = inputManager.loadCustomLabel(input);
String label = (customLabel == null) ? null : customLabel.toString();
if (TextUtils.isEmpty(label)) {
@@ -668,9 +688,7 @@ public class Utils {
return label;
}
- /**
- * Enable all channels synchronously.
- */
+ /** Enable all channels synchronously. */
@WorkerThread
public static void enableAllChannels(Context context) {
ContentValues values = new ContentValues();
@@ -681,46 +699,48 @@ public class Utils {
/**
* Converts time in milliseconds to a String.
*
- * @param fullFormat {@code true} for returning date string with a full format
- * (e.g., Mon Aug 15 20:08:35 GMT 2016). {@code false} for a short format,
- * {e.g., [8/15/16] 8:08 AM}, in which date information would only appears
- * when the target time is not today.
+ * @param fullFormat {@code true} for returning date string with a full format (e.g., Mon Aug 15
+ * 20:08:35 GMT 2016). {@code false} for a short format, {e.g., 8/15/16 or 8:08 AM}, in
+ * which only the time is shown if the time is on the same day as now, and only the date is
+ * shown if it's a different day.
*/
public static String toTimeString(long timeMillis, boolean fullFormat) {
if (fullFormat) {
return new Date(timeMillis).toString();
} else {
long currentTime = System.currentTimeMillis();
- return (String) DateUtils.formatSameDayTime(timeMillis, System.currentTimeMillis(),
- SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
+ return (String)
+ DateUtils.formatSameDayTime(
+ timeMillis,
+ System.currentTimeMillis(),
+ SimpleDateFormat.SHORT,
+ SimpleDateFormat.SHORT);
}
}
- /**
- * Converts time in milliseconds to a String.
- */
+ /** Converts time in milliseconds to a String. */
public static String toTimeString(long timeMillis) {
return toTimeString(timeMillis, true);
}
/**
- * Converts time in milliseconds to a ISO 8061 string.
- */
- public static String toIsoDateTimeString(long timeMillis) {
- return ISO_8601.format(new Date(timeMillis));
- }
-
- /**
* Returns a {@link String} object which contains the layout information of the {@code view}.
*/
public static String toRectString(View view) {
return "{"
- + "l=" + view.getLeft()
- + ",r=" + view.getRight()
- + ",t=" + view.getTop()
- + ",b=" + view.getBottom()
- + ",w=" + view.getWidth()
- + ",h=" + view.getHeight() + "}";
+ + "l="
+ + view.getLeft()
+ + ",r="
+ + view.getRight()
+ + ",t="
+ + view.getTop()
+ + ",b="
+ + view.getBottom()
+ + ",w="
+ + view.getWidth()
+ + ",h="
+ + view.getHeight()
+ + "}";
}
/**
@@ -732,16 +752,14 @@ public class Utils {
}
/**
- * Ceils time to the given {@code timeUnit}. For example, if time is 5:32:11 and timeUnit is
- * one hour (60 * 60 * 1000), then the output will be 6:00:00.
+ * Ceils time to the given {@code timeUnit}. For example, if time is 5:32:11 and timeUnit is one
+ * hour (60 * 60 * 1000), then the output will be 6:00:00.
*/
public static long ceilTime(long timeMs, long timeUnit) {
return timeMs + timeUnit - (timeMs % timeUnit);
}
- /**
- * Returns an {@link String#intern() interned} string or null if the input is null.
- */
+ /** Returns an {@link String#intern() interned} string or null if the input is null. */
@Nullable
public static String intern(@Nullable String string) {
return string == null ? null : string.intern();
@@ -749,6 +767,7 @@ public class Utils {
/**
* Check if the index is valid for the collection,
+ *
* @param collection the collection
* @param index the index position to test
* @return index >= 0 && index < collection.size().
@@ -757,9 +776,7 @@ public class Utils {
return collection != null && (index >= 0 && index < collection.size());
}
- /**
- * Returns a localized version of the text resource specified by resourceId.
- */
+ /** Returns a localized version of the text resource specified by resourceId. */
public static CharSequence getTextForLocale(Context context, Locale locale, int resourceId) {
if (locale.equals(context.getResources().getConfiguration().locale)) {
return context.getText(resourceId);
@@ -769,12 +786,12 @@ public class Utils {
return context.createConfigurationContext(config).getText(resourceId);
}
- /**
- * Checks where there is any internal TV input.
- */
+ /** Checks where there is any internal TV input. */
public static boolean hasInternalTvInputs(Context context, boolean tunerInputOnly) {
- for (TvInputInfo input : TvApplication.getSingletons(context).getTvInputManagerHelper()
- .getTvInputInfos(true, tunerInputOnly)) {
+ for (TvInputInfo input :
+ TvSingletons.getSingletons(context)
+ .getTvInputManagerHelper()
+ .getTvInputInfos(true, tunerInputOnly)) {
if (isInternalTvInput(context, input.getId())) {
return true;
}
@@ -782,13 +799,13 @@ public class Utils {
return false;
}
- /**
- * Returns the internal TV inputs.
- */
+ /** Returns the internal TV inputs. */
public static List<TvInputInfo> getInternalTvInputs(Context context, boolean tunerInputOnly) {
List<TvInputInfo> inputs = new ArrayList<>();
- for (TvInputInfo input : TvApplication.getSingletons(context).getTvInputManagerHelper()
- .getTvInputInfos(true, tunerInputOnly)) {
+ for (TvInputInfo input :
+ TvSingletons.getSingletons(context)
+ .getTvInputManagerHelper()
+ .getTvInputInfos(true, tunerInputOnly)) {
if (isInternalTvInput(context, input.getId())) {
inputs.add(input);
}
@@ -796,81 +813,41 @@ public class Utils {
return inputs;
}
- /**
- * Checks whether the input is internal or not.
- */
+ /** Checks whether the input is internal or not. */
public static boolean isInternalTvInput(Context context, String inputId) {
- return context.getPackageName().equals(ComponentName.unflattenFromString(inputId)
- .getPackageName());
+ return context.getPackageName()
+ .equals(ComponentName.unflattenFromString(inputId).getPackageName());
}
- /**
- * Returns the TV input for the given {@code program}.
- */
+ /** Returns the TV input for the given {@code program}. */
@Nullable
public static TvInputInfo getTvInputInfoForProgram(Context context, Program program) {
- if (!Program.isValid(program)) {
+ if (!Program.isProgramValid(program)) {
return null;
}
return getTvInputInfoForChannelId(context, program.getChannelId());
}
- /**
- * Returns the TV input for the given channel ID.
- */
+ /** Returns the TV input for the given channel ID. */
@Nullable
public static TvInputInfo getTvInputInfoForChannelId(Context context, long channelId) {
- ApplicationSingletons appSingletons = TvApplication.getSingletons(context);
- Channel channel = appSingletons.getChannelDataManager().getChannel(channelId);
+ TvSingletons tvSingletons = TvSingletons.getSingletons(context);
+ Channel channel = tvSingletons.getChannelDataManager().getChannel(channelId);
if (channel == null) {
return null;
}
- return appSingletons.getTvInputManagerHelper().getTvInputInfo(channel.getInputId());
+ return tvSingletons.getTvInputManagerHelper().getTvInputInfo(channel.getInputId());
}
- /**
- * Returns the {@link TvInputInfo} for the given input ID.
- */
+ /** Returns the {@link TvInputInfo} for the given input ID. */
@Nullable
public static TvInputInfo getTvInputInfoForInputId(Context context, String inputId) {
- return TvApplication.getSingletons(context).getTvInputManagerHelper()
+ return TvSingletons.getSingletons(context)
+ .getTvInputManagerHelper()
.getTvInputInfo(inputId);
}
- /**
- * Deletes a file or a directory.
- */
- public static void deleteDirOrFile(File fileOrDirectory) {
- if (fileOrDirectory.isDirectory()) {
- for (File child : fileOrDirectory.listFiles()) {
- deleteDirOrFile(child);
- }
- }
- fileOrDirectory.delete();
- }
-
- /**
- * Checks whether a given package is in our bundled package set.
- */
- public static boolean isInBundledPackageSet(String packageName) {
- return BUNDLED_PACKAGE_SET.contains(packageName);
- }
-
- /**
- * Checks whether a given input is a bundled input.
- */
- public static boolean isBundledInput(String inputId) {
- for (String prefix : BUNDLED_PACKAGE_SET) {
- if (inputId.startsWith(prefix + "/")) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns the canonical genre ID's from the {@code genres}.
- */
+ /** Returns the canonical genre ID's from the {@code genres}. */
public static int[] getCanonicalGenreIds(String genres) {
if (TextUtils.isEmpty(genres)) {
return null;
@@ -878,9 +855,7 @@ public class Utils {
return getCanonicalGenreIds(Genres.decode(genres));
}
- /**
- * Returns the canonical genre ID's from the {@code genres}.
- */
+ /** Returns the canonical genre ID's from the {@code genres}. */
public static int[] getCanonicalGenreIds(String[] canonicalGenres) {
if (canonicalGenres != null && canonicalGenres.length > 0) {
int[] results = new int[canonicalGenres.length];
@@ -901,9 +876,7 @@ public class Utils {
return null;
}
- /**
- * Returns the canonical genres for database.
- */
+ /** Returns the canonical genres for database. */
public static String getCanonicalGenre(int[] canonicalGenreIds) {
if (canonicalGenreIds == null || canonicalGenreIds.length == 0) {
return null;
@@ -916,15 +889,8 @@ public class Utils {
}
/**
- * Returns true if the current user is a developer.
- */
- public static boolean isDeveloper() {
- return BuildConfig.ENG || Experiments.ENABLE_DEVELOPER_FEATURES.get();
- }
-
- /**
- * Runs the method in main thread. If the current thread is not main thread, block it util
- * the method is finished.
+ * Runs the method in main thread. If the current thread is not main thread, block it util the
+ * method is finished.
*/
public static void runInMainThreadAndWait(Runnable runnable) {
if (Looper.myLooper() == Looper.getMainLooper()) {