Skip to content

Instantly share code, notes, and snippets.

@KazaKago
Last active September 11, 2015 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KazaKago/081664c673b3d817b046 to your computer and use it in GitHub Desktop.
Save KazaKago/081664c673b3d817b046 to your computer and use it in GitHub Desktop.
汎用ユーティリティクラス
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresPermission;
import android.telephony.TelephonyManager;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
/**
* 共通Utilクラス
*
* @author PTAMURA
*/
public class CommonUtil {
/**
* int→boolean変換
*
* @param num
* @return
*/
public static boolean intToBoolean(int num) {
return (num != 0);
}
/**
* boolean→int変換
*
* @param bool
* @return
*/
public static int booleanToInt(boolean bool) {
return (bool) ? 1 : 0;
}
/**
* コピー元のパス[srcPath]から、コピー先のパス[destPath]へ ファイルのコピーを行う。 <br>
* コピー処理にはFileChannel#transferToメソッドを利用します。<br>
* 尚、コピー処理終了後、入力・出力のチャネルをクローズします。
*
* @param srcPath コピー元のパス
* @param destPath コピー先のパス
* @throws IOException 何らかの入出力処理例外が発生した場合
*/
public static void copyTransfer(String srcPath, String destPath) throws IOException {
FileInputStream is = new FileInputStream(srcPath);
FileChannel srcChannel = is.getChannel();
FileOutputStream os = new FileOutputStream(destPath);
FileChannel destChannel = os.getChannel();
srcChannel.transferTo(0, srcChannel.size(), destChannel);
is.close();
srcChannel.close();
os.close();
destChannel.close();
}
/**
* .nomediaファイルを指定フォルダに作成
*
* @param file
* @return
* @throws IOException
*/
public static boolean createNomedia(File file) throws IOException {
File nomediaFile = new File(file.getPath(), ".nomedia");
return nomediaFile.createNewFile();
}
/**
* 自身のバージョン名を取得する
*
* @param context
* @return
* @throws NameNotFoundException
*/
public static String getVersionName(Context context) throws NameNotFoundException {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionName;
}
/**
* 自身のバージョンコードを取得する
*
* @param context
* @return
* @throws NameNotFoundException
*/
public static int getVersionCode(Context context) throws NameNotFoundException {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
}
/**
* 互換性を考慮した背景画像を設定メソッド
*
* @param view
* @param drawable
* @return
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static View setBackground(View view, Drawable drawable) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
return view;
}
/**
* 互換性を考慮したAsyncTask実行メソッド
*
* @param task
* @param params
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> task, T... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}
}
/**
* \nがそのまま表示されてしまう文字列を適切な改行コードに変換する<br>
* DBから文字を取得した時などは本処理を行わないと\nがそのまま表示されてしまうので注意
*
* @param originalStr
* @return
* @throws UnsupportedEncodingException
*/
public static String convertNewLine(String originalStr) throws UnsupportedEncodingException {
byte[] bytes = "\\\\n".getBytes("ISO-8859-1");
String new_line = new String(bytes, "UTF-8");
return originalStr.replaceAll(new_line, System.getProperty("line.separator"));
}
/**
* 自身のPlayストアリンクを取得する(Playストアアプリへの直接遷移)
*
* @param context
* @return
* @throws NameNotFoundException
*/
public static String getStoreDirectLink(Context context) throws NameNotFoundException {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return "market://details?id=" + packageInfo.packageName;
}
/**
* 自身のPlayストアリンクを取得する(ブラウザでも開けるバージョン)
*
* @param context
* @return
* @throws NameNotFoundException
*/
public static String getStoreGeneralLink(Context context) throws NameNotFoundException {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return "http://play.google.com/store/apps/details?id=" + packageInfo.packageName;
}
/**
* dpをpxに変換する
*
* @param context
* @param dip
* @return
*/
public static int dipToPixel(Context context, int dip) {
// density (比率)を取得する
float density = context.getResources().getDisplayMetrics().density;
//pixelに変換する(dp × density + 0.5f(四捨五入))
return (int) (dip * density + 0.5f);
}
/**
* pxをdpに変換する
*
* @param context
* @param pixel
* @return
*/
public static int pixelToDip(Context context, int pixel) {
// density (比率)を取得する
float density = context.getResources().getDisplayMetrics().density;
//dpに変換する(pixel ÷ density + 0.5f(四捨五入))
return (int) (pixel / density + 0.5f);
}
/**
* ordinal から指定した Enum の要素に変換する汎用関数
*
* @param enumClass
* @param ordinal
* @return
*/
public static <E extends Enum<E>> E fromOrdinal(Class<E> enumClass, int ordinal) {
E[] enumArray = enumClass.getEnumConstants();
return enumArray[ordinal];
}
/**
* UriからPathへの変換処理 Uriのscheme()から context:// file:// を判断して、処理する内容を変える。
*
* @param context
* @param uri
* @return String
* @throws NullPointerException
*/
public static String getPathFromUri(Context context, Uri uri) throws NullPointerException {
String filePath;
if (uri.getScheme().equals("content")) {
Cursor cursor = context.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
filePath = uri.getPath();
}
return filePath;
}
/**
* 端末IDを取得する。
*
* @param context
* @return
*/
@RequiresPermission(Manifest.permission.ACCESS_WIFI_STATE)
public static String getTerminalID(Context context) {
String terminalID = null;
String imei = getIMEI(context);
String serialNo = getSerialNo(context);
String macAddress = getMacAddress(context);
if (imei != null && imei.length() > 0) {
terminalID = "i" + imei;
} else if (serialNo != null && serialNo.length() > 0) {
terminalID = "s" + serialNo;
} else if (macAddress != null && macAddress.length() > 0) {
terminalID = "m" + macAddress;
}
return terminalID;
}
/**
* 端末のIMEIを取得する
*
* @param context
* @return
*/
private static String getIMEI(Context context) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getDeviceId();
}
/**
* 端末のSIMのシリアルナンバーを取得する
*
* @param context
* @return
*/
private static String getSerialNo(Context context) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getSimSerialNumber();
}
/**
* 端末のMACアドレスを取得する
*
* @param context
* @return
*/
@RequiresPermission(Manifest.permission.ACCESS_WIFI_STATE)
private static String getMacAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getMacAddress();
}
/**
* APIレベル18以下のWebViewでパスワード保存ダイアログを表示させないようにさせるための制御<br>
* APIレベル19以降はそもそもWebViewでのパスワード保存がサポートされない
*
* @param webSettings
*/
@SuppressWarnings("deprecation")
public static void setDisableSavePassword(WebSettings webSettings) {
if (Build.VERSION.SDK_INT <= 18) webSettings.setSavePassword(false);
}
/**
* 互換性を考慮したクッキー削除メソッド
*
* @param cookieManager
*/
@SuppressWarnings("deprecation")
public static void removeAllCookies(CookieManager cookieManager) {
if (Build.VERSION.SDK_INT <= 21) cookieManager.removeAllCookie();
else cookieManager.removeAllCookies(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment