Skip to content

Instantly share code, notes, and snippets.

@Krishan14sharma
Created December 5, 2014 04:15
Show Gist options
  • Save Krishan14sharma/bbdfa1136ca255f7a4e8 to your computer and use it in GitHub Desktop.
Save Krishan14sharma/bbdfa1136ca255f7a4e8 to your computer and use it in GitHub Desktop.
Utils
package com.dnn.zapbuild.commons.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Build;
import android.util.Log;
public class AndroidUtils {
private AndroidUtils() {
}
public static String getAppName(Context context) {
return getAppName(context, null);
}
public static String getAppName(Context context, String packageName) {
String applicationName;
if (packageName == null) {
packageName = context.getPackageName();
}
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
applicationName = context.getString(packageInfo.applicationInfo.labelRes);
}
catch (Exception e) {
Log.w("Failed to get version number.", e);
applicationName = "";
}
return applicationName;
}
public static String getAppVersionNumber(Context context) {
return getAppVersionNumber(context, null);
}
public static String getAppVersionNumber(Context context, String packageName) {
String versionName;
if (packageName == null) {
packageName = context.getPackageName();
}
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
versionName = packageInfo.versionName;
}
catch (Exception e) {
Log.w("Failed to get version number.", e);
versionName = "";
}
return versionName;
}
public static String getAppVersionCode(Context context) {
return getAppVersionCode(context, null);
}
public static String getAppVersionCode(Context context, String packageName) {
String versionCode;
if (packageName == null) {
packageName = context.getPackageName();
}
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
versionCode = Integer.toString(packageInfo.versionCode);
}
catch (Exception e) {
Log.w("Failed to get version code.", e);
versionCode = "";
}
return versionCode;
}
public static int getSdkVersion() {
try {
return Build.VERSION.class.getField("SDK_INT").getInt(null);
}
catch (Exception e) {
return 3;
}
}
public static boolean isEmulator() {
return Build.MODEL.equals("sdk") || Build.MODEL.equals("google_sdk");
}
}
package com.dnn.zapbuild.commons.util;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.dnn.zapbuild.commons.BaseApp;
/**
* Created by zapbuild on 17/11/14.
*/
public class CommonUtil {
/**
*
* @param message message to be displayed in Toast.
*/
public static void showToast(String message)
{
Toast.makeText(BaseApp.getContext(), message, Toast.LENGTH_SHORT).show();
}
public static void showIME(Context context) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_NOT_ALWAYS);
}
public static void hideIME(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
package com.dnn.zapbuild.commons.util;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.res.Resources;
import android.net.wifi.WifiManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.WindowManager;
import com.dnn.zapbuild.commons.BaseApp;
//hardware related functions
public class DeviceUtil {
public static final String TAG = "DeviceUtil";
public static String getInfo() {
String model = android.os.Build.MODEL;
String device = android.os.Build.DEVICE;
String brand = android.os.Build.BRAND;
String product = android.os.Build.PRODUCT;
String display = android.os.Build.DISPLAY;
String manufacture = android.os.Build.MANUFACTURER;
Context context = BaseApp.getContext();
Resources resources = context.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
float density = dm.density;
StringBuilder sb = new StringBuilder();
String finalInfo = sb.append("MODEL " + model)
.append("\nDEVICE " + device).append("\nBRAND " + brand)
.append("\nPRODUCT " + product).append("\nDISPLAY " + display)
.append("\nMANUFACTURE " + manufacture)
.append("\nSCREEN_WIDTH " + screenWidth)
.append("\nSCREEN_HEIGHT " + screenHeight)
.append("\nDENSITY " + density).toString();
return finalInfo;
}
public static final String getBluetoothMac() {
BluetoothAdapter adapter = null;
String bluetoothMac = null;
try {
adapter = BluetoothAdapter.getDefaultAdapter();
bluetoothMac = adapter.getAddress();
} catch (Exception e) {
}
return bluetoothMac;
}
public static final String getWlanMac() {
Context context = BaseApp.getContext();
String wlanMac = null;
try {
WifiManager wm = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
wlanMac = wm.getConnectionInfo().getMacAddress();
} catch (Exception e) {
}
return wlanMac;
}
public static final String getAndroidId() {
Context context = BaseApp.getContext();
String androidID = null;
try {
androidID = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
} catch (Exception e) {
}
return androidID;
}
public static final String getIMEI() {
Context context = BaseApp.getContext();
String deviceIMEI = null;
try {
TelephonyManager teleManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
deviceIMEI = teleManager.getDeviceId();
} catch (Exception e) {
}
return deviceIMEI;
}
public static float getScreenInches() {
Context context = BaseApp.getContext();
float screenInches = -1;
try {
Resources resources = context.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
double width = Math.pow(dm.widthPixels / dm.xdpi, 2);
double height = Math.pow(dm.heightPixels / dm.ydpi, 2);
screenInches = (float) (Math.sqrt(width + height));
} catch (Exception e) {
}
return screenInches;
}
public static int dp2px(int dip) {
Context context = BaseApp.getContext();
Resources resources = context.getResources();
int px = Math
.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dip, resources.getDisplayMetrics()));
return px;
}
public static int px2dp(int px) {
Context context = BaseApp.getContext();
DisplayMetrics displayMetrics = context.getResources()
.getDisplayMetrics();
int dp = Math.round(px
/ (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return dp;
}
public static int sp2px(float sp) {
Context context = BaseApp.getContext();
final float scale = context.getResources().getDisplayMetrics().scaledDensity;
int px = Math.round(sp * scale);
return px;
}
public static int getDensity() {
Context context = BaseApp.getContext();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
int density = metrics.densityDpi;
return density;
}
}
package com.dnn.zapbuild.commons.util;
import java.util.ArrayList;
/**
* Created by zapbuild on 18/11/14.
*/
public class DummyUtil {
public static ArrayList<String> getDummyList()
{
ArrayList<String> list=new ArrayList<String>();
list.add("Tiger");
list.add("Lion");
list.add("Dog");
list.add("Cat");
list.add("Owl");
list.add("Pig");
list.add("Sparrow");
list.add("Lemur");
list.add("Pumba");
list.add("Timon");
list.add("Monitor");
list.add("Panda");
list.add("Snake");
list.add("Shoaib Akhtar");
list.add("Cow");
list.add("Doggie");
list.add("Red Panda");
list.add("Grasshopper");
list.add("Cricket");
list.add("Charmeleon");
return list;
}
}
package com.dnn.zapbuild.commons.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
public class FileUtil {
public static final String TAG = "FileUtil";
private static final int IO_BUFFER_SIZE = 16384;
public static boolean create(String absPath) {
return create(absPath, false);
}
public static boolean create(String absPath, boolean force) {
if (TextUtils.isEmpty(absPath)) {
return false;
}
if (exists(absPath)) {
return true;
}
String parentPath = getParent(absPath);
mkdirs(parentPath, force);
try {
File file = new File(absPath);
return file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean mkdirs(String absPath) {
return mkdirs(absPath, false);
}
public static boolean mkdirs(String absPath, boolean force) {
File file = new File(absPath);
if (exists(absPath) && !isFolder(absPath)) {
if (!force) {
return false;
} else {
delete(file);
}
}
try {
file.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
return exists(file);
}
public static boolean move(String srcPath, String dstPath) {
return move(srcPath, dstPath, false);
}
public static boolean move(String srcPath, String dstPath, boolean force) {
if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) {
return false;
}
if (!exists(srcPath)) {
return false;
}
if (exists(dstPath)) {
if (!force) {
return false;
} else {
delete(dstPath);
}
}
try {
File srcFile = new File(srcPath);
File dstFile = new File(dstPath);
return srcFile.renameTo(dstFile);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean delete(String absPath) {
if (TextUtils.isEmpty(absPath)) {
return false;
}
File file = new File(absPath);
return delete(file);
}
public static boolean delete(File file) {
if (!exists(file)) {
return true;
}
if (file.isFile()) {
return file.delete();
}
boolean result = true;
File files[] = file.listFiles();
for (int index = 0; index < files.length; index++) {
result |= delete(files[index]);
}
result |= file.delete();
return result;
}
public static boolean exists(String absPath) {
if (TextUtils.isEmpty(absPath)) {
return false;
}
File file = new File(absPath);
return exists(file);
}
public static boolean exists(File file) {
if (file == null) {
return false;
}
return file.exists();
}
public static boolean childOf(String childPath, String parentPath) {
if (TextUtils.isEmpty(childPath) || TextUtils.isEmpty(parentPath)) {
return false;
}
childPath = cleanPath(childPath);
parentPath = cleanPath(parentPath);
if (childPath.startsWith(parentPath + File.separator)) {
return true;
}
return false;
}
public static int childCount(String absPath) {
if (!exists(absPath)) {
return 0;
}
File file = new File(absPath);
File[] children = file.listFiles();
if (children == null || children.length == 0) {
return 0;
}
return children.length;
}
public static String cleanPath(String absPath) {
if (TextUtils.isEmpty(absPath)) {
return absPath;
}
try {
File file = new File(absPath);
absPath = file.getCanonicalPath();
} catch (Exception e) {
}
return absPath;
}
public static long size(String absPath) {
if (absPath == null) {
return 0;
}
File file = new File(absPath);
return size(file);
}
public static long size(File file) {
if (!exists(file)) {
return 0;
}
long length = 0;
if (isFile(file)) {
length = file.length();
return length;
}
File files[] = file.listFiles();
if (files == null || files.length == 0) {
return length;
}
int size = files.length;
for (int index = 0; index < size; index++) {
File child = files[index];
length += size(child);
}
return length;
}
public static boolean copy(String srcPath, String dstPath) {
return copy(srcPath, dstPath, false);
}
public static boolean copy(String srcPath, String dstPath, boolean force) {
if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) {
return false;
}
// check if copy source equals destination
if (srcPath.equals(dstPath)) {
return true;
}
// check if source file exists or is a directory
if (!exists(srcPath) || !isFile(srcPath)) {
return false;
}
// delete old content
if (exists(dstPath)) {
if (!force) {
return false;
} else {
delete(dstPath);
}
}
if (!create(dstPath)) {
return false;
}
FileInputStream in = null;
FileOutputStream out = null;
// get streams
try {
in = new FileInputStream(srcPath);
out = new FileOutputStream(dstPath);
} catch (Exception e) {
e.printStackTrace();
return false;
}
try {
byte[] buffer = new byte[IO_BUFFER_SIZE];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
public final static boolean isFile(String absPath) {
boolean exists = exists(absPath);
if (!exists) {
return false;
}
File file = new File(absPath);
return isFile(file);
}
public final static boolean isFile(File file) {
if (file == null) {
return false;
}
return file.isFile();
}
public final static boolean isFolder(String absPath) {
boolean exists = exists(absPath);
if (!exists) {
return false;
}
File file = new File(absPath);
return file.isDirectory();
}
public final static String getName(File file) {
if (file == null) {
return null;
} else {
return getName(file.getAbsolutePath());
}
}
public final static String getName(String absPath) {
if (TextUtils.isEmpty(absPath)) {
return absPath;
}
String fileName = null;
int index = absPath.lastIndexOf("/");
if (index > 0 && index < (absPath.length() - 1)) {
fileName = absPath.substring(index + 1, absPath.length());
}
return fileName;
}
public final static String getParent(File file) {
if (file == null) {
return null;
} else {
return file.getParent();
}
}
public final static String getParent(String absPath) {
if (TextUtils.isEmpty(absPath)) {
return null;
}
absPath = cleanPath(absPath);
File file = new File(absPath);
return getParent(file);
}
public static String getStem(File file) {
if (file == null) {
return null;
}
return getStem(file.getName());
}
public final static String getStem(String fileName) {
if (TextUtils.isEmpty(fileName)) {
return null;
}
int index = fileName.lastIndexOf(".");
if (index > 0) {
return fileName.substring(0, index);
} else {
return "";
}
}
public static String getExtension(File file) {
if (file == null) {
return null;
}
return getExtension(file.getName());
}
public static String getExtension(String fileName) {
if (TextUtils.isEmpty(fileName)) {
return "";
}
int index = fileName.lastIndexOf('.');
if (index < 0 || index >= (fileName.length() - 1)) {
return "";
}
return fileName.substring(index + 1);
}
public static String getMimeType(File file) {
if (file == null) {
return "*/*";
}
String fileName = file.getName();
return getMimeType(fileName);
}
public static String getMimeType(String fileName) {
if (TextUtils.isEmpty(fileName)) {
return "*/*";
}
String extension = getExtension(fileName);
MimeTypeMap map = MimeTypeMap.getSingleton();
String type = map.getMimeTypeFromExtension(extension);
if (TextUtils.isEmpty(type)) {
return "*/*";
} else {
return type;
}
}
public static String fileSHA1(String absPath) {
if (TextUtils.isEmpty(absPath)) {
return null;
}
File file = new File(absPath);
if (!file.exists() || file.isDirectory()) {
return null;
}
String fileSHA1 = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return null;
}
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("SHA-1");
byte[] buffer = new byte[IO_BUFFER_SIZE];
int length = 0;
while ((length = fis.read(buffer)) > 0) {
messageDigest.update(buffer, 0, length);
}
fis.close();
fileSHA1 = SecurityUtil.bytes2Hex(messageDigest.digest());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!TextUtils.isEmpty(fileSHA1)) {
fileSHA1 = fileSHA1.trim();
}
return fileSHA1;
}
public static String fileMD5(String absPath) {
if (TextUtils.isEmpty(absPath)) {
return null;
}
File file = new File(absPath);
if (!file.exists() || file.isDirectory()) {
return null;
}
String fileMD5 = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return null;
}
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[IO_BUFFER_SIZE];
int length = 0;
while ((length = fis.read(buffer)) > 0) {
messageDigest.update(buffer, 0, length);
}
fis.close();
fileMD5 = SecurityUtil.bytes2Hex(messageDigest.digest());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!TextUtils.isEmpty(fileMD5)) {
fileMD5 = fileMD5.trim();
}
return fileMD5;
}
}
package com.dnn.zapbuild.commons.util;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.dnn.zapbuild.commons.BaseApp;
public class IntentUtils {
/**
* This will fire an intent for opening the url.
* @param context
* @param url
*/
public static void startWebActivity(Context context,String url) {
try {
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
context.startActivity(intent);
}catch (ActivityNotFoundException exception)
{
CommonUtil.showToast("No browser app found");
}
}
public static void startEmailActivity(Context context, int toResId, int subjectResId, int bodyResId) {
startEmailActivity(context, context.getString(toResId), context.getString(subjectResId),
context.getString(bodyResId));
}
public static void startEmailActivity(Context context, String to, String subject, String body) {
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
if (!TextUtils.isEmpty(to)) {
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
}
if (!TextUtils.isEmpty(subject)) {
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
}
if (!TextUtils.isEmpty(body)) {
intent.putExtra(Intent.EXTRA_TEXT, body);
}
final PackageManager pm = (PackageManager) context.getPackageManager();
try {
if (pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() == 0) {
intent.setType("text/plain");
}
}
catch (Exception e) {
Log.w("Exception encountered while looking for email intent receiver.", e);
}
context.startActivity(intent);
}
}
package com.dnn.zapbuild.commons.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
package com.dnn.zapbuild.commons.util;
import android.os.StrictMode;
import com.dnn.zapbuild.commons.BuildConfig;
/**
* Created by zapbuild on 28/11/14.
* This class contains methods that are useful for performance analysis.
* Other ways-
* 1.Strict mode enable in developer options
* 2.Don't keep activities enabled
* 3.Gpu Overdraw setting
* 4.Hierarchy viewer in Device monitor
*
* Tips
* 1.Use apply instead of commit in Shared preferences if you are not using the result.
*/
public class PerformanceUtil {
private static final boolean DEVELOPER_MODE=true;
/**
* Alternatively enable Strict mode enable on device Developer settings
*/
public static void enableStrictMode()
{
if(BuildConfig.DEBUG && DEVELOPER_MODE) {
// Activate StrictMode
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyDeath()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
// alternatively .detectAll() for all detectable problems
.penaltyLog()
.penaltyDeath()
.build());
}
}
}
package com.dnn.zapbuild.commons.util;
import java.security.MessageDigest;
import java.util.Locale;
import android.text.TextUtils;
public class SecurityUtil {
public static final String TAG = "SecurityUtil";
public static String getMD5(String text) {
String md5 = null;
if (TextUtils.isEmpty(text)) {
return md5;
}
MessageDigest md5Digest = null;
try {
md5Digest = MessageDigest.getInstance("MD5");
} catch (Exception e) {
e.printStackTrace();
return md5;
}
char[] charArray = text.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int index = 0; index < charArray.length; index++) {
byteArray[index] = (byte) charArray[index];
}
byte[] md5Bytes = md5Digest.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int index = 0; index < md5Bytes.length; index++) {
int val = ((int) md5Bytes[index]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
md5 = hexValue.toString();
return md5;
}
public static String bytes2Hex(byte[] bytes) {
String hs = "";
String stmp = "";
for (int n = 0; n < bytes.length; n++) {
stmp = (Integer.toHexString(bytes[n] & 0XFF));
if (stmp.length() == 1) {
hs += "0" + stmp;
} else {
hs += stmp;
}
}
return hs.toLowerCase(Locale.ENGLISH);
}
public static String getSHA1(String text) {
String sha1 = null;
if (TextUtils.isEmpty(text)) {
return sha1;
}
MessageDigest sha1Digest = null;
try {
sha1Digest = MessageDigest.getInstance("SHA-1");
} catch (Exception e) {
return sha1;
}
byte[] textBytes = text.getBytes();
sha1Digest.update(textBytes, 0, text.length());
byte[] sha1hash = sha1Digest.digest();
return bytes2Hex(sha1hash);
}
}
package com.dnn.zapbuild.commons.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import android.util.Log;
public class ZipUtil {
public static final String TAG = "ZipUtil";
private final static int BUFFER_SIZE = 8192;
public static boolean zip(String filePath, String zipPath) {
try {
File file = new File(filePath);
BufferedInputStream bis = null;
FileOutputStream fos = new FileOutputStream(zipPath);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(
fos));
if (file.isDirectory()) {
int baseLength = file.getParent().length() + 1;
zipFolder(zos, file, baseLength);
} else {
byte data[] = new byte[BUFFER_SIZE];
FileInputStream fis = new FileInputStream(filePath);
bis = new BufferedInputStream(fis, BUFFER_SIZE);
String entryName = file.getName();
Log.i(TAG, "zip entry " + entryName);
ZipEntry entry = new ZipEntry(entryName);
zos.putNextEntry(entry);
int count;
while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {
zos.write(data, 0, count);
}
}
zos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private static void zipFolder(ZipOutputStream zos, File folder,
int baseLength) throws IOException {
if (zos == null || folder == null) {
return;
}
File[] fileList = folder.listFiles();
if (fileList == null || fileList.length == 0) {
return;
}
for (File file : fileList) {
if (file.isDirectory()) {
zipFolder(zos, file, baseLength);
} else {
byte data[] = new byte[BUFFER_SIZE];
String unmodifiedFilePath = file.getPath();
String realPath = unmodifiedFilePath.substring(baseLength);
Log.i(TAG, "zip entry " + realPath);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
BufferedInputStream bis = new BufferedInputStream(fi,
BUFFER_SIZE);
ZipEntry entry = new ZipEntry(realPath);
zos.putNextEntry(entry);
int count;
while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {
zos.write(data, 0, count);
}
bis.close();
}
}
}
public static boolean unzip(String zipPath, String unzipFolder) {
if (!FileUtil.exists(zipPath)) {
return false;
}
if (!FileUtil.mkdirs(unzipFolder, true)) {
return false;
}
try {
FileInputStream fin = new FileInputStream(zipPath);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String entryName = ze.getName();
String entryPath = unzipFolder + "/" + entryName;
if (ze.isDirectory()) {
FileUtil.mkdirs(entryPath);
} else {
if (!FileUtil.create(entryPath, true)) {
continue;
}
FileOutputStream fout = new FileOutputStream(entryPath);
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = zin.read(buffer)) != -1) {
fout.write(buffer, 0, len);
}
fout.close();
zin.closeEntry();
}
}
zin.close();
} catch (Exception e) {
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment