package com.finddreams.baselib.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.Date; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; import com.lidroid.xutils.BitmapUtils; import com.lidroid.xutils.bitmap.BitmapDisplayConfig; import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack; import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom; /** * @Description: 通用的类 * @author http://blog.csdn.net/finddreams */ public class CommonUtils { private static final String TAG = "CommonUtils"; /** * 根据应用名字去应用市场查询该应用 * @param context * @param appName market://search?q=pub:听听中心 */ public static void searchTingting(Context context,String appName) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("market://search?q=pub:"+ appName +"")); context.startActivity(intent); } /** * 根据应用的包名,去应用市场搜索该应用 * com.google.android.voicesearch google语音 * com.snda.tts.service 听听中心 * @param context * @param appPckName */ public static void searchAppByPkgName(Context context,String appPckName) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("market://details?id=" + appPckName)); context.startActivity(intent); } public static void call(Context context,String phoneNumber) { Intent myIntentDial = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phoneNumber)); context.startActivity(myIntentDial); } public static void shareImage(final Context context,File file) { if (file != null) { Intent intent=new Intent(Intent.ACTION_SEND); intent.setType("image/*"); Uri u = Uri.fromFile(file); intent.putExtra(Intent.EXTRA_STREAM, u); context.startActivity(Intent.createChooser(intent, "分享")); } } /** *打开设置网页界面 */ public static void openSettingNet(Context context) { Intent intent=null; //判断手机系统的版本 即API大于10 就是3.0或以上版本 if(android.os.Build.VERSION.SDK_INT>10){ intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); LogManager.d(TAG, "api level 10"); }else{ intent = new Intent(); ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings"); intent.setComponent(component); intent.setAction("android.intent.action.VIEW"); LogManager.d(TAG, "api level less 10"); } context.startActivity(intent); } public static void openBroswer(Context context,String url) { Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // it.setClassName("com.android.browser", "com.android.browser.BrowserActivity"); context.startActivity(it); } public static void openImage(Context context,String path) { if (path != null && path.length() > 0 && context != null) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(path)), "image/*"); context.startActivity(intent); } } public static void showInfoDialog(Context context, String message) { showInfoDialog(context, message, "提示", "确定", null); } public static void showInfoDialog(Context context, String message, String titleStr, String positiveStr, DialogInterface.OnClickListener onClickListener) { AlertDialog.Builder localBuilder = new AlertDialog.Builder(context); localBuilder.setTitle(titleStr); localBuilder.setMessage(message); if (onClickListener == null) onClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }; localBuilder.setPositiveButton(positiveStr, onClickListener); localBuilder.show(); } /** * 将指定byte数组转换成16进制字符串 * * @param b * @return */ public static String byteToHexString(byte[] b) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } hexString.append(hex.toUpperCase()); } return hexString.toString(); } /** * 判断当前是否有可用的网络以及网络类型 0:无网络 1:WIFI 2:CMWAP 3:CMNET * * @param context * @return */ public static int isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { return 0; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { NetworkInfo netWorkInfo = info[i]; if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) { return 1; } else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { String extraInfo = netWorkInfo.getExtraInfo(); if ("cmwap".equalsIgnoreCase(extraInfo) || "cmwap:gsm".equalsIgnoreCase(extraInfo)) { return 2; } return 3; } } } } } return 0; } /** * * @param context * @param button * @param nornalImageFileName * @param pressedImageFileName * @throws Exception */ public static void bindViewSelector(Context context, final View view, String nornalImageurl, final String pressedImageUrl) { final StateListDrawable stateListDrawable = new StateListDrawable(); final BitmapUtils utils = new BitmapUtils(context); utils.display(view, nornalImageurl, new BitmapLoadCallBack<View>() { @Override public void onLoadCompleted(View container, String uri, Bitmap bitmap, BitmapDisplayConfig config, BitmapLoadFrom from) { Drawable normalDrawable = new BitmapDrawable(bitmap); stateListDrawable.addState( new int[] { android.R.attr.state_active }, normalDrawable); stateListDrawable.addState(new int[] { android.R.attr.state_focused, android.R.attr.state_enabled }, normalDrawable); stateListDrawable.addState( new int[] { android.R.attr.state_enabled }, normalDrawable); utils.display(container, pressedImageUrl, new BitmapLoadCallBack<View>() { @Override public void onLoadCompleted(View container, String uri, Bitmap bitmap, BitmapDisplayConfig config, BitmapLoadFrom from) { stateListDrawable.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, new BitmapDrawable(bitmap)); view.setBackgroundDrawable(stateListDrawable); } @Override public void onLoadFailed(View container, String uri, Drawable drawable) { // TODO Auto-generated method stub } }); } @Override public void onLoadFailed(View container, String uri, Drawable drawable) { } }); } private static Drawable createDrawable(Drawable d, Paint p) { BitmapDrawable bd = (BitmapDrawable) d; Bitmap b = bd.getBitmap(); Bitmap bitmap = Bitmap.createBitmap(bd.getIntrinsicWidth(), bd.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.drawBitmap(b, 0, 0, p); // 关键代码,使用新的Paint画原图, return new BitmapDrawable(bitmap); } /** 设置Selector。 本次只增加点击变暗的效果,注释的代码为更多的效果 */ public static StateListDrawable createSLD(Context context, Drawable drawable) { StateListDrawable bg = new StateListDrawable(); int brightness = 50 - 127; ColorMatrix cMatrix = new ColorMatrix(); cMatrix.set(new float[] { 1, 0, 0, 0, brightness, 0, 1, 0, 0, brightness,// 改变亮度 0, 0, 1, 0, brightness, 0, 0, 0, 1, 0 }); Paint paint = new Paint(); paint.setColorFilter(new ColorMatrixColorFilter(cMatrix)); Drawable normal = drawable; Drawable pressed = createDrawable(drawable, paint); bg.addState(new int[] { android.R.attr.state_pressed, }, pressed); bg.addState(new int[] { android.R.attr.state_focused, }, pressed); bg.addState(new int[] { android.R.attr.state_selected }, pressed); bg.addState(new int[] {}, normal); return bg; } public static Bitmap getImageFromAssetsFile(Context ct, String fileName) { Bitmap image = null; AssetManager am = ct.getAssets(); try { InputStream is = am.open(fileName); image = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return image; } /** * 更新刷新时间 * @param created * @return */ public static String getUploadtime(long created) { StringBuffer when = new StringBuffer(); int difference_seconds; int difference_minutes; int difference_hours; int difference_days; int difference_months; long curTime = System.currentTimeMillis(); difference_months = (int) (((curTime / 2592000) % 12) - ((created / 2592000) % 12)); if (difference_months > 0) { when.append(difference_months + "月"); } difference_days = (int) (((curTime / 86400) % 30) - ((created / 86400) % 30)); if (difference_days > 0) { when.append(difference_days + "天"); } difference_hours = (int) (((curTime / 3600) % 24) - ((created / 3600) % 24)); if (difference_hours > 0) { when.append(difference_hours + "小时"); } difference_minutes = (int) (((curTime / 60) % 60) - ((created / 60) % 60)); if (difference_minutes > 0) { when.append(difference_minutes + "分钟"); } difference_seconds = (int) ((curTime % 60) - (created % 60)); if (difference_seconds > 0) { when.append(difference_seconds + "秒"); } return when.append("前").toString(); } public static boolean hasToken(Context ct) { String token = SharePrefUtil.getString(ct, "token", ""); if (TextUtils.isEmpty(token)) { return false; } else { return true; } } public static void setListViewHeightBasedOnChildren(ListView listView) { // 获取ListView对应的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目 View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); // 计算子项View 的宽高 totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度 } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); // listView.getDividerHeight()获取子项间分隔符占用的高度 // params.height最后得到整个ListView完整显示需要的高度 listView.setLayoutParams(params); } }