1 /* 2 * Copyright (C) 2014 Google Inc. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.musicservicedemo; 18 19 import android.graphics.Bitmap; 20 import android.graphics.BitmapFactory; 21 import android.util.Log; 22 23 import java.io.IOException; 24 import java.io.InputStream; 25 import java.net.HttpURLConnection; 26 import java.net.URL; 27 28 public class Utils { 29 30 private static final String TAG = "Utils"; 31 32 /** 33 * Utility method to check that parameters are not null 34 * 35 * @param object 36 */ checkNotNull(Object object)37 public static final void checkNotNull(Object object) { 38 if (object == null) { 39 throw new NullPointerException(); 40 } 41 } 42 43 /** 44 * Utility to download a bitmap 45 * 46 * @param source 47 * @return 48 */ getBitmapFromURL(String source)49 public static Bitmap getBitmapFromURL(String source) { 50 try { 51 URL url = new URL(source); 52 HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); 53 httpConnection.setDoInput(true); 54 httpConnection.connect(); 55 InputStream inputStream = httpConnection.getInputStream(); 56 return BitmapFactory.decodeStream(inputStream); 57 } catch (IOException e) { 58 Log.e(TAG, "getBitmapFromUrl: " + source, e); 59 } 60 return null; 61 } 62 63 /** 64 * Utility method to wrap an index 65 * 66 * @param i 67 * @param size 68 * @return 69 */ wrapIndex(int i, int size)70 public static int wrapIndex(int i, int size) { 71 int m = i % size; 72 if (m < 0) { // java modulus can be negative 73 m += size; 74 } 75 return m; 76 } 77 } 78