InputStream
as a byte[]
.
*
* This method buffers the input internally, so there is no need to use a
* BufferedInputStream
.
*
* @param input the InputStream
to read from
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws java.io.IOException if an I/O error occurs
*/
public static byte[] toByteArray(InputStream input) throws IOException
{
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
public static long copy(InputStream input, OutputStream output) throws IOException
{
byte[] buffer = new byte[1024 * 4];
long count = 0;
int n;
while (-1 != (n = input.read(buffer)))
{
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static void atomicCopy(File from, File to) throws IOException
{
File tmp = new File(String.format("%s.tmp", to.getPath()));
FileInputStream in = new FileInputStream(from);
FileOutputStream out = new FileOutputStream(tmp);
try
{
in.getChannel().transferTo(0, from.length(), out.getChannel());
out.close();
if (!tmp.renameTo(to))
{
throw new IOException(String.format("Failed to rename %s to %s", tmp, to));
}
Timber.i("Copied %s to %s", from, to);
}
catch (IOException x)
{
close(out);
delete(to);
throw x;
}
finally
{
close(in);
close(out);
delete(tmp);
}
}
public static void renameFile(File from, File to) throws IOException
{
if (from.renameTo(to))
{
Timber.i("Renamed %s to %s", from, to);
}
else
{
atomicCopy(from, to);
}
}
public static void close(Closeable closeable)
{
try
{
if (closeable != null)
{
closeable.close();
}
}
catch (Throwable x)
{
// Ignored
}
}
public static boolean delete(File file)
{
if (file != null && file.exists())
{
if (!file.delete())
{
Timber.w("Failed to delete file %s", file);
return false;
}
Timber.i("Deleted file %s", file);
}
return true;
}
public static void toast(Context context, int messageId)
{
toast(context, messageId, true);
}
public static void toast(Context context, int messageId, boolean shortDuration)
{
toast(context, context.getString(messageId), shortDuration);
}
public static void toast(Context context, CharSequence message)
{
toast(context, message, true);
}
public static void toast(Context context, CharSequence message, boolean shortDuration)
{
if (toast == null)
{
toast = Toast.makeText(context, message, shortDuration ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
}
else
{
toast.setText(message);
toast.setDuration(shortDuration ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG);
}
toast.show();
}
/**
* Converts a byte-count to a formatted string suitable for display to the user.
* For instance:
* format(918)
returns "918 B".format(98765)
returns "96 KB".format(1238476)
returns "1.2 MB".format(918)
returns "918 B".format(98765)
returns "96 KB".format(1238476)
returns "1.2 MB".Broadcasts the given song info as the new song being played.
*/ public static void broadcastNewTrackInfo(Context context, Entry song) { Intent intent = new Intent(EVENT_META_CHANGED); if (song != null) { intent.putExtra("title", song.getTitle()); intent.putExtra("artist", song.getArtist()); intent.putExtra("album", song.getAlbum()); File albumArtFile = FileUtil.getAlbumArtFile(context, song); intent.putExtra("coverart", albumArtFile.getAbsolutePath()); } else { intent.putExtra("title", ""); intent.putExtra("artist", ""); intent.putExtra("album", ""); intent.putExtra("coverart", ""); } context.sendBroadcast(intent); } public static void broadcastA2dpMetaDataChange(Context context, int playerPosition, DownloadFile currentPlaying, int listSize, int id) { if (!Util.getShouldSendBluetoothNotifications(context)) { return; } Entry song = null; Intent avrcpIntent = new Intent(CM_AVRCP_METADATA_CHANGED); if (currentPlaying != null) song = currentPlaying.getSong(); if (song == null) { avrcpIntent.putExtra("track", ""); avrcpIntent.putExtra("track_name", ""); avrcpIntent.putExtra("artist", ""); avrcpIntent.putExtra("artist_name", ""); avrcpIntent.putExtra("album", ""); avrcpIntent.putExtra("album_name", ""); avrcpIntent.putExtra("album_artist", ""); avrcpIntent.putExtra("album_artist_name", ""); if (Util.getShouldSendBluetoothAlbumArt(context)) { avrcpIntent.putExtra("coverart", (Parcelable) null); avrcpIntent.putExtra("cover", (Parcelable) null); } avrcpIntent.putExtra("ListSize", (long) 0); avrcpIntent.putExtra("id", (long) 0); avrcpIntent.putExtra("duration", (long) 0); avrcpIntent.putExtra("position", (long) 0); } else { if (song != currentSong) { currentSong = song; } String title = song.getTitle(); String artist = song.getArtist(); String album = song.getAlbum(); Integer duration = song.getDuration(); avrcpIntent.putExtra("track", title); avrcpIntent.putExtra("track_name", title); avrcpIntent.putExtra("artist", artist); avrcpIntent.putExtra("artist_name", artist); avrcpIntent.putExtra("album", album); avrcpIntent.putExtra("album_name", album); avrcpIntent.putExtra("album_artist", artist); avrcpIntent.putExtra("album_artist_name", artist); if (Util.getShouldSendBluetoothAlbumArt(context)) { File albumArtFile = FileUtil.getAlbumArtFile(context, song); avrcpIntent.putExtra("coverart", albumArtFile.getAbsolutePath()); avrcpIntent.putExtra("cover", albumArtFile.getAbsolutePath()); } avrcpIntent.putExtra("position", (long) playerPosition); avrcpIntent.putExtra("id", (long) id); avrcpIntent.putExtra("ListSize", (long) listSize); if (duration != null) { avrcpIntent.putExtra("duration", (long) duration); } } context.sendBroadcast(avrcpIntent); } public static void broadcastA2dpPlayStatusChange(Context context, PlayerState state, Entry currentSong, Integer listSize, Integer id, Integer playerPosition) { if (!Util.getShouldSendBluetoothNotifications(context)) { return; } if (currentSong != null) { Intent avrcpIntent = new Intent(CM_AVRCP_PLAYSTATE_CHANGED); if (currentSong == null) { return; } if (currentSong != currentSong) { Util.currentSong = currentSong; } String title = currentSong.getTitle(); String artist = currentSong.getArtist(); String album = currentSong.getAlbum(); Integer duration = currentSong.getDuration(); avrcpIntent.putExtra("track", title); avrcpIntent.putExtra("track_name", title); avrcpIntent.putExtra("artist", artist); avrcpIntent.putExtra("artist_name", artist); avrcpIntent.putExtra("album", album); avrcpIntent.putExtra("album_name", album); avrcpIntent.putExtra("album_artist", artist); avrcpIntent.putExtra("album_artist_name", artist); if (Util.getShouldSendBluetoothAlbumArt(context)) { File albumArtFile = FileUtil.getAlbumArtFile(context, currentSong); avrcpIntent.putExtra("coverart", albumArtFile.getAbsolutePath()); avrcpIntent.putExtra("cover", albumArtFile.getAbsolutePath()); } avrcpIntent.putExtra("position", (long) playerPosition); avrcpIntent.putExtra("id", (long) id); avrcpIntent.putExtra("ListSize", (long) listSize); if (duration != null) { avrcpIntent.putExtra("duration", (long) duration); } switch (state) { case STARTED: avrcpIntent.putExtra("playing", true); break; case STOPPED: avrcpIntent.putExtra("playing", false); break; case PAUSED: avrcpIntent.putExtra("playing", false); break; case COMPLETED: avrcpIntent.putExtra("playing", false); break; default: return; // No need to broadcast. } context.sendBroadcast(avrcpIntent); } } /** *Broadcasts the given player state as the one being set.
*/ public static void broadcastPlaybackStatusChange(Context context, PlayerState state) { Intent intent = new Intent(EVENT_PLAYSTATE_CHANGED); switch (state) { case STARTED: intent.putExtra("state", "play"); break; case STOPPED: intent.putExtra("state", "stop"); break; case PAUSED: intent.putExtra("state", "pause"); break; case COMPLETED: intent.putExtra("state", "complete"); break; default: return; // No need to broadcast. } context.sendBroadcast(intent); } public static int getNotificationImageSize(Context context) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int imageSizeLarge = Math.round(Math.min(metrics.widthPixels, metrics.heightPixels)); int size; if (imageSizeLarge <= 480) { size = 64; } else size = imageSizeLarge <= 768 ? 128 : 256; return size; } public static int getAlbumImageSize(Context context) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int imageSizeLarge = Math.round(Math.min(metrics.widthPixels, metrics.heightPixels)); int size; if (imageSizeLarge <= 480) { size = 128; } else size = imageSizeLarge <= 768 ? 256 : 512; return size; } public static int getMinDisplayMetric(Context context) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return Math.min(metrics.widthPixels, metrics.heightPixels); } public static int getMaxDisplayMetric(Context context) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return Math.max(metrics.widthPixels, metrics.heightPixels); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } public static void linkButtons(Context context, RemoteViews views, boolean playerActive) { Intent intent = new Intent(context, playerActive ? DownloadActivity.class : MainActivity.class); intent.setAction("android.intent.action.MAIN"); intent.addCategory("android.intent.category.LAUNCHER"); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.appwidget_coverart, pendingIntent); views.setOnClickPendingIntent(R.id.appwidget_top, pendingIntent); // Emulate media button clicks. intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)); pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0); views.setOnClickPendingIntent(R.id.control_play, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT)); pendingIntent = PendingIntent.getBroadcast(context, 2, intent, 0); views.setOnClickPendingIntent(R.id.control_next, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS)); pendingIntent = PendingIntent.getBroadcast(context, 3, intent, 0); views.setOnClickPendingIntent(R.id.control_previous, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP)); pendingIntent = PendingIntent.getBroadcast(context, 4, intent, 0); views.setOnClickPendingIntent(R.id.control_stop, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1)); pendingIntent = PendingIntent.getBroadcast(context, 5, intent, 0); views.setOnClickPendingIntent(R.id.notification_five_star_1, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_2)); pendingIntent = PendingIntent.getBroadcast(context, 6, intent, 0); views.setOnClickPendingIntent(R.id.notification_five_star_2, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_3)); pendingIntent = PendingIntent.getBroadcast(context, 7, intent, 0); views.setOnClickPendingIntent(R.id.notification_five_star_3, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_4)); pendingIntent = PendingIntent.getBroadcast(context, 8, intent, 0); views.setOnClickPendingIntent(R.id.notification_five_star_4, pendingIntent); intent = new Intent(Constants.CMD_PROCESS_KEYCODE); intent.setPackage(context.getPackageName()); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_5)); pendingIntent = PendingIntent.getBroadcast(context, 9, intent, 0); views.setOnClickPendingIntent(R.id.notification_five_star_5, pendingIntent); } public static int getNetworkTimeout(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000")); } public static int getDefaultAlbums(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_DEFAULT_ALBUMS, "5")); } public static int getMaxAlbums(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_MAX_ALBUMS, "20")); } public static int getDefaultSongs(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_DEFAULT_SONGS, "10")); } public static int getMaxSongs(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_MAX_SONGS, "25")); } public static int getMaxArtists(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_MAX_ARTISTS, "10")); } public static int getDefaultArtists(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_DEFAULT_ARTISTS, "3")); } public static int getBufferLength(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_BUFFER_LENGTH, "5")); } public static int getIncrementTime(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_INCREMENT_TIME, "5")); } public static boolean getMediaButtonsPreference(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_MEDIA_BUTTONS, true); } public static boolean getShowNowPlayingPreference(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_SHOW_NOW_PLAYING, true); } public static boolean getGaplessPlaybackPreference(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_GAPLESS_PLAYBACK, false); } public static boolean getShouldTransitionOnPlaybackPreference(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_DOWNLOAD_TRANSITION, true); } public static boolean getShouldUseId3Tags(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_ID3_TAGS, false); } public static int getChatRefreshInterval(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_CHAT_REFRESH_INTERVAL, "5000")); } public static int getDirectoryCacheTime(Context context) { SharedPreferences preferences = getPreferences(context); return Integer.parseInt(preferences.getString(Constants.PREFERENCES_KEY_DIRECTORY_CACHE_TIME, "300")); } public static boolean isNullOrWhiteSpace(String string) { return string == null || string.isEmpty() || string.trim().isEmpty(); } public static String formatTotalDuration(long totalDuration) { return formatTotalDuration(totalDuration, false); } public static boolean getShouldClearPlaylist(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_CLEAR_PLAYLIST, false); } public static boolean getShouldSortByDisc(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_DISC_SORT, false); } public static boolean getShouldClearBookmark(Context context) { SharedPreferences preferences = getPreferences(context); return preferences.getBoolean(Constants.PREFERENCES_KEY_CLEAR_BOOKMARK, false); } public static String formatTotalDuration(long totalDuration, boolean inMilliseconds) { long millis = totalDuration; if (!inMilliseconds) { millis = totalDuration * 1000; } long hours = TimeUnit.MILLISECONDS.toHours(millis); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(hours); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(hours * 60 + minutes); if (hours >= 10) { return String.format("%02d:%02d:%02d", hours, minutes, seconds); } else if (hours > 0) { return String.format("%d:%02d:%02d", hours, minutes, seconds); } else if (minutes >= 10) { return String.format("%02d:%02d", minutes, seconds); } else return minutes > 0 ? String.format("%d:%02d", minutes, seconds) : String.format("0:%02d", seconds); } public static VideoPlayerType getVideoPlayerType(Context context) { SharedPreferences preferences = getPreferences(context); return VideoPlayerType.forKey(preferences.getString(Constants.PREFERENCES_KEY_VIDEO_PLAYER, VideoPlayerType.MX.getKey())); } public static boolean isPackageInstalled(Context context, String packageName) { PackageManager pm = context.getPackageManager(); List