android 經常使用方法總結
- public class Toolkit {
-
-
-
-
-
-
-
-
-
-
-
- public static String getProvidersName(Context context) {
- String ProvidersName = "nosim";
- try {
-
- TelephonyManager telephonyManager = (TelephonyManager) context
- .getSystemService(Context.TELEPHONY_SERVICE);
- String IMSI = telephonyManager.getSubscriberId();
-
- if (IMSI.startsWith("46000") || IMSI.startsWith("46002"))
- ProvidersName = "中國移動";
- else if (IMSI.startsWith("46001"))
- ProvidersName = "中國聯通";
- else if (IMSI.startsWith("46003"))
- ProvidersName = "中國電信";
- } catch (Exception e) {
-
- e.printStackTrace();
- return ProvidersName;
- }
- return ProvidersName;
- }
-
-
-
-
-
-
-
- public static String getPhone(Context context) {
- TelephonyManager phoneMgr = (TelephonyManager) context
- .getSystemService(Context.TELEPHONY_SERVICE);
- return phoneMgr.getLine1Number();
- }
-
-
-
-
-
-
- public static String getPhoneType() {
- return Build.MODEL;
- }
-
-
-
-
-
-
- public static String getSDKVersion() {
- return Build.VERSION.SDK;
- }
-
-
-
-
-
-
- public static String getVersion() {
- return Build.VERSION.RELEASE;
- }
-
- public static class TelephonyManagerInfo {
-
-
-
-
-
-
-
- public static int CallState;
-
-
-
-
- public static String CellLocation;
-
-
-
-
-
-
-
-
-
- public static String DeviceId;
-
-
-
-
-
-
-
-
-
- public static String DeviceSoftwareVersion;
-
-
-
-
-
-
-
-
-
- public static String Line1Number;
-
-
-
-
-
-
-
-
-
- public static List<NeighboringCellInfo> NeighboringCellInfo;
-
-
-
-
-
-
-
-
-
- public static String NetworkCountryIso;
-
-
-
-
-
-
-
-
-
- public static String NetworkOperator;
-
-
-
-
-
-
-
-
-
-
- public static String NetworkOperatorName;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static int NetworkType;
-
-
-
-
-
-
-
-
-
-
-
-
- public static int PhoneType;
-
-
-
-
-
-
-
-
- public static String SimCountryIso;
-
-
-
-
-
-
-
-
-
-
- public static String SimOperator;
-
-
-
-
-
-
-
-
-
- public static String SimOperatorName;
-
-
-
-
-
-
-
- public static String SimSerialNumber;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static int SimState;
-
-
-
-
-
-
-
-
-
- public static String SubscriberId;
-
-
-
-
-
-
-
- public static String VoiceMailAlphaTag;
-
-
-
-
-
-
-
- public static String VoiceMailNumber;
-
-
-
-
-
- public static boolean hasIccCard;
-
-
-
-
-
-
-
- public static boolean isNetworkRoaming;
- }
-
-
-
-
-
-
-
- public static String getPhoneUniqueId(Context context) {
- TelephonyManager tm = (TelephonyManager) context
- .getSystemService(context.TELEPHONY_SERVICE);
- return tm.getDeviceId();
- }
-
-
-
-
-
-
-
- public static TelephonyManagerInfo getTelephonyInfo(Context context) {
- TelephonyManagerInfo info = new TelephonyManagerInfo();
- TelephonyManager tm = (TelephonyManager) context
- .getSystemService(context.TELEPHONY_SERVICE);
- info.CallState = tm.getCallState();
- info.CellLocation = tm.getCellLocation().toString();
- info.DeviceId = tm.getDeviceId();
- info.DeviceSoftwareVersion = tm.getDeviceSoftwareVersion();
- info.hasIccCard = tm.hasIccCard();
- info.isNetworkRoaming = tm.isNetworkRoaming();
- info.Line1Number = tm.getLine1Number();
- info.NeighboringCellInfo = tm.getNeighboringCellInfo();
- info.NetworkCountryIso = tm.getNetworkCountryIso();
- info.NetworkOperator = tm.getNetworkOperator();
- info.NetworkOperatorName = tm.getNetworkOperatorName();
- info.NetworkType = tm.getNetworkType();
- info.PhoneType = tm.getPhoneType();
- info.SimCountryIso = tm.getSimCountryIso();
- info.SimOperator = tm.getSimOperator();
- info.SimOperatorName = tm.getSimOperatorName();
- info.SimSerialNumber = tm.getSimSerialNumber();
- info.SimState = tm.getSimState();
- info.SubscriberId = tm.getSubscriberId();
- info.VoiceMailAlphaTag = tm.getVoiceMailAlphaTag();
- info.VoiceMailNumber = tm.getVoiceMailNumber();
- return info;
- }
-
-
-
-
-
-
-
-
- public static int[] getDisplayPixes(Activity context) {
- DisplayMetrics dm = new DisplayMetrics();
- context.getWindowManager().getDefaultDisplay().getMetrics(dm);
- return new int[] { dm.widthPixels, dm.heightPixels };
- }
-
-
-
-
-
-
-
-
- public static int[] getDisplayWidthHeight(Activity context) {
- Display dis = context.getWindowManager().getDefaultDisplay();
- return new int[] { dis.getWidth(), dis.getHeight() };
- }
-
-
-
-
-
-
-
-
- public static boolean isAvaliable(Context context) {
- if (isWiFiActive(context) || isNetworkAvailable(context))
-
- return true;
- else
-
- return false;
- }
-
-
- public static long getNetworkSpeed() {
-
- ProcessBuilder cmd;
- long readBytes = 0;
- BufferedReader rd = null;
- try {
- String[] args = { "/system/bin/cat", "/proc/net/dev" };
- cmd = new ProcessBuilder(args);
- Process process = cmd.start();
- rd = new BufferedReader(new InputStreamReader(
- process.getInputStream()));
- String line;
- int linecount = 0;
- while ((line = rd.readLine()) != null) {
- linecount++;
- if (line.contains("wlan0") || line.contains("eth0")) {
-
- String[] delim = line.split(":");
- if (delim.length >= 2) {
- String[] numbers = delim[1].trim().split(" ");
- readBytes = Long.parseLong(numbers[0].trim());
- break;
- }
- }
- }
- rd.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- } finally {
- if (rd != null) {
- try {
- rd.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- }
- return readBytes;
- }
-
-
-
-
-
-
-
- public static boolean isWiFiActive(Context inContext) {
- WifiManager mWifiManager = (WifiManager) inContext
- .getSystemService(Context.WIFI_SERVICE);
- WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
- int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
- if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
- System.out.println("**** WIFI is on");
- return true;
- } else {
- System.out.println("**** WIFI is off");
- return false;
- }
- }
-
-
-
-
-
-
-
- public static boolean isNetworkAvailable(Context context) {
- ConnectivityManager connectivity = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivity == null) {
- return false;
- } else {
- NetworkInfo info = connectivity.getActiveNetworkInfo();
- if (info == null) {
- return false;
- } else {
- if (info.isAvailable()) {
- return true;
- }
- }
- }
- return false;
- }
-
-
-
-
-
-
- public static boolean isWifiConnected(Context context) {
- int ipAddress = getWifiIpInfo(context);
- if (ipAddress > 0)
- return true;
- else
- return false;
- }
-
- private static int getWifiIpInfo(Context context) {
-
- WifiManager wifiManager = (WifiManager) context
- .getSystemService(Context.WIFI_SERVICE);
-
- if (!wifiManager.isWifiEnabled()) {
- wifiManager.setWifiEnabled(true);
- }
- WifiInfo wifiInfo = wifiManager.getConnectionInfo();
-
- int ipAddress = wifiInfo.getIpAddress();
- return ipAddress;
- }
-
-
-
-
-
-
- public static String getWifiAddress(Context context) {
- int ipAddress = getWifiIpInfo(context);
- return intToIp(ipAddress);
- }
-
- private static String intToIp(int i) {
- return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
- + "." + (i >> 24 & 0xFF);
- }
-
-
-
-
-
- public static String getMacAddress(Context context) {
-
- String macAddress = "000000000000";
- try {
- WifiManager wifiMgr = (WifiManager) context
- .getSystemService(Context.WIFI_SERVICE);
- WifiInfo info = (null == wifiMgr ? null : wifiMgr
- .getConnectionInfo());
- if (null != info) {
- if (!TextUtils.isEmpty(info.getMacAddress()))
- macAddress = info.getMacAddress().replace(":", "");
- else
- return macAddress;
- }
- } catch (Exception e) {
-
- e.printStackTrace();
- return macAddress;
- }
- return macAddress;
- }
-
-
-
-
-
-
-
-
- public static String getLocalIpAddress() throws SocketException {
- for (Enumeration<NetworkInterface> en = NetworkInterface
- .getNetworkInterfaces(); en.hasMoreElements();) {
- NetworkInterface intf = en.nextElement();
- for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
- .hasMoreElements();) {
- InetAddress inetAddress = enumIpAddr.nextElement();
- if (!inetAddress.isLoopbackAddress()) {
- return inetAddress.getHostAddress().toString();
- }
- }
- }
- return null;
- }
-
-
-
-
-
-
-
- public static String getHostAddress() throws UnknownHostException {
- InetAddress address = null;
- address = InetAddress.getLocalHost();
- return address.getHostAddress();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String readFromFileByChar(String file, Context context,
- String encode) throws IOException {
- FileInputStream fis = context.openFileInput(file);
- BufferedReader br = new BufferedReader(new InputStreamReader(fis,
- encode));
-
- int index = 0;
- char[] buffer = new char[1024];
- StringBuffer sb = new StringBuffer();
- while ((index = br.read(buffer)) != -1) {
-
- if ((index == buffer.length) && (buffer[buffer.length - 1] != 'r')) {
- sb.append(buffer);
- } else {
- for (int i = 0; i < index; i++) {
- if (buffer[i] == 'r') {
- continue;
- } else {
- sb.append(buffer[i]);
- }
- }
- }
- }
- br.close();
- fis.close();
- return sb.toString();
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String readFromFileByLine(String file, Context context,
- String encode) throws IOException {
- FileInputStream fis = context.openFileInput(file);
- BufferedReader br = new BufferedReader(new InputStreamReader(fis,
- encode));
-
- StringBuffer sb = new StringBuffer();
- String temp;
- while ((temp = br.readLine()) != null) {
- sb.append(temp);
- }
- br.close();
- fis.close();
- return sb.toString();
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public static void writeToFile(Context context, String file, String content)
- throws IOException {
- FileOutputStream fos = context.openFileOutput(file,
- context.MODE_PRIVATE);
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
- bw.write(content);
- bw.flush();
- bw.close();
- fos.close();
- }
-
-
-
-
-
-
-
-
-
- public static boolean writeFileByObject(String fileName, Object object) {
- try {
- FileOutputStream fos = new FileOutputStream(fileName);
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(object);
- oos.flush();
- oos.close();
- fos.close();
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
-
-
-
-
-
-
-
- public static Object readFileByObject(String fileName) {
- try {
- FileInputStream fis = new FileInputStream(fileName);
- ObjectInputStream ois = new ObjectInputStream(fis);
- Object o = ois.readObject();
- ois.close();
- fis.close();
- return o;
- } catch (Exception e) {
- return null;
- }
- }
-
-
-
-
-
-
-
-
-
- public static Bitmap compressBitmap(Bitmap bm, int w, int h) {
- return ThumbnailUtils.extractThumbnail(bm, w, h);
- }
-
-
-
-
-
-
-
-
-
-
- public static Bitmap compressBitmapByscale(InputStream is, int scalePix) {
- BitmapFactory.Options opt = new Options();
- opt.inSampleSize = scalePix;
- return BitmapFactory.decodeStream(is, null, opt);
- }
-
-
-
-
-
-
-
-
-
-
-
- public static Bitmap compressBitmap(byte[] data, int ratio) {
- BitmapFactory.Options opts = new Options();
- opts.inJustDecodeBounds = false;
- opts.inSampleSize = ratio;
-
- return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
-
- }
-
-
-
-
-
-
-
- public static Bitmap compressBitmapAuto(Bitmap map, int scalePix) {
- BitmapFactory.Options opts = new BitmapFactory.Options();
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- byte[] data = os.toByteArray();
- opts.inJustDecodeBounds = true;
- map.compress(CompressFormat.PNG, 100, os);
- Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
- opts.inJustDecodeBounds = false;
- int be = (int) (opts.outHeight / (float) scalePix);
- if (be <= 0)
- be = 1;
- opts.inSampleSize = be;
- bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
- return bitmap;
- }
-
-
- public static Bitmap compressBitmapFixDisplay(Activity context, byte[] data) {
- BitmapFactory.Options opts = new Options();
- opts.inJustDecodeBounds = true;
- BitmapFactory.decodeByteArray(data, 0, data.length, opts);
- int height = context.getWindowManager().getDefaultDisplay().getHeight();
- int width = context.getWindowManager().getDefaultDisplay().getWidth();
- int hratio = (int) Math.ceil(opts.outHeight / (float) height);
- int wratio = (int) Math.ceil(opts.outWidth / (float) width);
- if (hratio > 1 || wratio > 1) {
- if (hratio > wratio)
- opts.inSampleSize = hratio;
- else
- opts.inSampleSize = wratio;
- }
- opts.inJustDecodeBounds = false;
- Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
- opts);
- return bitmap;
- }
-
-
-
-
-
-
-
-
-
-
- public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
-
- int width = bm.getWidth();
- int height = bm.getHeight();
-
- float scaleWidth = ((float) newWidth) / width;
- float scaleHeight = ((float) newHeight) / height;
-
- Matrix matrix = new Matrix();
- matrix.postScale(scaleWidth, scaleHeight);
-
- Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
- true);
- if (!bm.isRecycled())
- bm.recycle();
- return newbm;
- }
-
-
-
-
-
-
-
-
-
-
-
- public static void setImagePixes(ImageView iv, int width, int height) {
- ViewGroup.LayoutParams params = iv.getLayoutParams();
- if (width == 0 && height != 0)
- {
- params.height = height;
- params.width = ViewGroup.LayoutParams.FILL_PARENT;
- } else if (height == 0 && width != 0) {
- params.height = ViewGroup.LayoutParams.FILL_PARENT;
- params.width = width;
- } else if (width == 0 && height == 0) {
- params.height = ViewGroup.LayoutParams.FILL_PARENT;
- params.width = ViewGroup.LayoutParams.FILL_PARENT;
- } else {
- params.height = height;
- params.width = width;
- }
- iv.setLayoutParams(params);
- }
-
-
- @SuppressWarnings("deprecation")
- public static View activityToView(Context parent, Intent intent) {
- LocalActivityManager mLocalActivityManager = new LocalActivityManager(
- (Activity) parent, true);
- final Window w = mLocalActivityManager.startActivity("TagName", intent);
- final View wd = w != null ? w.getDecorView() : null;
- if (wd != null) {
- wd.setVisibility(View.VISIBLE);
- wd.setFocusableInTouchMode(true);
- ((ViewGroup) wd)
- .setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
- }
- return wd;
- }
-
-
-
-
-
-
- public static void setListViewHeightBasedOnChildren(ListView listView) {
- ListAdapter listAdapter = listView.getAdapter();
- if (listAdapter == null) {
- return;
- }
- int totalHeight = 0;
- for (int i = 0; i < listAdapter.getCount(); i++) {
- View listItem = listAdapter.getView(i, null, listView);
- listItem.measure(0, 0);
- totalHeight += listItem.getMeasuredHeight();
- }
- ViewGroup.LayoutParams params = listView.getLayoutParams();
- params.height = totalHeight
- + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
-
-
-
-
-
- listView.setLayoutParams(params);
- }
-
-
-
-
-
-
-
- public static Bitmap drawableToBitmap(Drawable drawable) {
- int width = drawable.getIntrinsicWidth();
- int height = drawable.getIntrinsicHeight();
- Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
- .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
- : Bitmap.Config.RGB_565);
- Canvas canvas = new Canvas(bitmap);
- drawable.setBounds(0, 0, width, height);
- drawable.draw(canvas);
- return bitmap;
- }
-
-
-
-
-
-
-
-
-
- public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int radius) {
-
- Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
- bitmap.getHeight(), Config.ARGB_8888);
-
- Canvas canvas = new Canvas(output);
-
-
- final int color = Color.RED;
- final Paint paint = new Paint();
-
- final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
- final RectF rectF = new RectF(rect);
-
- final float roundPx = radius;
-
- paint.setAntiAlias(true);
- canvas.drawARGB(0, 0, 0, 0);
- paint.setColor(color);
-
- canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
-
- paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
- canvas.drawBitmap(bitmap, rect, rect, paint);
-
- return output;
- }
-
-
-
-
-
-
-
- public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
- final int reflectionGap = 4;
- int width = bitmap.getWidth();
- int height = bitmap.getHeight();
- Matrix matrix = new Matrix();
- matrix.preScale(1, -1);
- Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
- width, height / 2, matrix, false);
- Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
- (height + height / 2), Config.ARGB_8888);
- Canvas canvas = new Canvas(bitmapWithReflection);
- canvas.drawBitmap(bitmap, 0, 0, null);
- Paint deafalutPaint = new Paint();
- canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
- canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
- Paint paint = new Paint();
- LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
- bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
- 0x00ffffff, TileMode.CLAMP);
- paint.setShader(shader);
-
- paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
-
- canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
- + reflectionGap, paint);
- return bitmapWithReflection;
- }
-
-
-
-
-
-
-
-
-
-
-
- public static void writeToPreferences(Context context, String filename,
- String key, String value) {
-
- SharedPreferences.Editor editor = context.getSharedPreferences(
- filename, android.content.Context.MODE_PRIVATE).edit();
-
- editor.putString(key, value);
- editor.commit();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String readFromPreferences(Context context, String filename,
- String key, String defaultValue) {
-
- SharedPreferences preferences = context.getSharedPreferences(filename,
- android.content.Context.MODE_PRIVATE
- | android.content.Context.MODE_APPEND);
- return preferences.getString(key, defaultValue);
- }
-
-
-
-
-
-
-
-
-
- public static Properties loadProperties(Context context, String file,
- String encode) throws Exception {
- Properties properties = new Properties();
- FileInputStream s = new FileInputStream(file);
- properties.load(s);
- return properties;
- }
-
-
-
-
-
-
-
-
-
- public static void saveProperties(Context context, String file,
- String encode, Properties properties) throws Exception {
- FileOutputStream s = new FileOutputStream(file, false);
- properties.store(s, "");
- }
-
-
-
-
-
-
-
-
-
-
- public static Bitmap getBitMapFromUrl(String url) throws IOException {
- Bitmap bitmap = null;
- URL u = null;
- HttpURLConnection conn = null;
- InputStream is = null;
- u = new URL(url);
- conn = (HttpURLConnection) u.openConnection();
- is = conn.getInputStream();
- bitmap = BitmapFactory.decodeStream(is);
- return bitmap;
- }
-
-
-
-
-
-
-
-
-
- public static void loadImage(final String src, final ImageView iv,
- final ImageCallBack callback) {
- final Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- callback.setImageBitmap((Bitmap) msg.obj, iv, src);
- }
- };
- new Thread(new Runnable() {
- @Override
- public void run() {
- Bitmap bitmap = null;
- try {
- bitmap = getBitMapFromUrl(src);
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (bitmap != null) {
- Message msg = handler.obtainMessage(0, bitmap);
- handler.sendMessage(msg);
- }
- }
- }).start();
- }
-
-
-
-
-
-
-
-
- public static byte[] getImageBytes(String src) throws Exception {
- URL url = new URL(src);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoInput(true);
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(5000);
- InputStream is = conn.getInputStream();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- int len = 0;
- byte[] buffer = new byte[1024];
- while ((len = is.read(buffer)) != -1) {
- bos.write(buffer, 0, len);
- }
- return bos.toByteArray();
- }
-
-
-
-
-
-
-
-
-
-
- public static Bitmap zoomBitmap(byte[] data, int newWidth, int newHeight) {
- BitmapFactory.Options opts = new Options();
- opts.inJustDecodeBounds = false;
- opts.inSampleSize = 10;
-
- Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
- opts);
-
- int width = bitmap.getWidth();
- int height = bitmap.getHeight();
-
- float scaleWidth = ((float) newWidth) / width;
- float scaleHeight = ((float) newHeight) / height;
-
- Matrix matrix = new Matrix();
- matrix.postScale(scaleWidth, scaleHeight);
-
- Bitmap newbm = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
- true);
- if (!bitmap.isRecycled())
- bitmap.recycle();
- return newbm;
- }
-
-
-
-
-
-
-
-
-
-
-
- public static void AsycloadImage(final String src, final ImageView iv,
- final ImageCallBack callback) {
- final Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- callback.setImageBitmap((Bitmap) msg.obj, iv, src);
- }
- };
- new Thread(new Runnable() {
- @Override
- public void run() {
- byte[] data = null;
- Bitmap bitmap = null;
- try {
- data = getImageBytes(src);
- bitmap = compressBitmap(data, 3);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- if (bitmap != null) {
- Message msg = handler.obtainMessage(0, bitmap);
- handler.sendMessage(msg);
- }
- }
- }).start();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static void AyncLoadImageFromUrl(final String url,
- final ImageView iv,
- final Map<String, SoftReference<Bitmap>> imgCache,
- final ImageCallBack callback) {
- if (imgCache.containsKey(url))
- {
- iv.setImageBitmap(imgCache.get(url).get());
- return;
- }
- final Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- callback.setImageBitmap((Bitmap) msg.obj, iv, url);
- }
- };
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- byte[] data = null;
- Bitmap bitmap = null;
- try {
- data = getImageBytes(url);
- bitmap = compressBitmap(data, 3);
- } catch (Exception e) {
- e.printStackTrace();
- }
- if (bitmap != null) {
-
-
- imgCache.put(url, new SoftReference<Bitmap>(bitmap));
- Message msg = handler.obtainMessage(0, bitmap);
- handler.sendMessage(msg);
- }
- }
- }).start();
- }
-
-
-
-
-
-
-
-
-
-
-
- public static String saveImgToSdcard(Context context, String fileName,
- String photo) throws IOException {
- String url = photo;
-
- String imgName = url.substring(url.lastIndexOf("/") + 1, url.length());
- URL Url = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
- InputStream is = conn.getInputStream();
- String saveUrl = context.getFilesDir() + "/" + fileName + "/" + imgName;
- File file = new File(saveUrl);
-
- if (file.exists())
- return imgName;
- FileOutputStream fos = new FileOutputStream(file);
- byte[] data = new byte[512];
- int len = 0;
- while ((len = is.read(data)) != -1) {
- fos.write(data, 0, len);
- }
- fos.flush();
- fos.close();
- return imgName;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static void saveBitmapToSdcard(Context context, String filedir,
- String name, Bitmap bitmap) throws Exception {
- String path = context.getFilesDir() + File.separator + filedir
- + File.separator;
- File file = new File(path);
- if (!file.exists()) {
- file.mkdir();
- }
- file = new File(path + name + ".png");
- if (file.exists())
- return;
- FileOutputStream fos = new FileOutputStream(file);
- bitmap.compress(CompressFormat.PNG, 100, fos);
- fos.close();
- }
-
-
- public static Bitmap getBitmapFromSdcard(Context context, String file,
- String name) {
- String src = context.getFilesDir() + "/" + file + "/" + name;
- Bitmap bitmap = BitmapFactory.decodeFile(src);
- return bitmap;
- }
-
-
-
-
-
-
-
-
- public static Bitmap getImgFromCache(final String url, final ImageView iv,
- final Map<String, SoftReference<Bitmap>> imgCache,
- final ImageCallBack callback) throws Exception {
-
- if (imgCache.containsKey(url)) {
- synchronized (imgCache) {
- SoftReference<Bitmap> bitmapReference = imgCache.get(url);
- if (null != bitmapReference) {
- return bitmapReference.get();
- }
- }
- }
- final Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- callback.setImageBitmap((Bitmap) msg.obj, iv, url);
- }
- };
-
- new Thread(new Runnable() {
- @Override
- public void run() {
- Bitmap bitmap = null;
- try {
- bitmap = getBitMapFromUrl(url);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- imgCache.put(url, new SoftReference<Bitmap>(bitmap));
- Message msg = handler.obtainMessage(0, bitmap);
- handler.sendMessage(msg);
- }
- }).start();
- return null;
- }
-
- public interface ImageCallBack {
- public void setImageBitmap(Bitmap bitmap, ImageView iv, String url);
- }
-
-
-
-
-
-
-
-
-
- public static HttpResponse get(String url) throws Exception {
- HttpResponse response = null;
- HttpClient client = new DefaultHttpClient();
-
- client.getParams().setIntParameter(
- HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
-
-
-
-
- HttpGet httpRequest = new HttpGet(url);
-
-
- response = client.execute(httpRequest);
- return response;
- }
-
-
-
-
-
-
-
-
-
-
-
- public static InputStream postRequest(String path,
- Map<String, String> params) throws Exception {
-
- List<NameValuePair> pair = new ArrayList<NameValuePair>();
- if (params != null && !params.isEmpty()) {
- for (Map.Entry<String, String> entry : params.entrySet()) {
- pair.add(new BasicNameValuePair(entry.getKey(), entry
- .getValue()));
- }
- }
-
- UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
-
-
-
- final HttpPost post = new HttpPost(path);
-
- post.setEntity(uee);
-
- DefaultHttpClient dhc = new DefaultHttpClient();
-
- dhc.getParams().setIntParameter(
- HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
- dhc.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000);
- HttpResponse response = dhc.execute(post);
- Log.e("TAG", "服務器返回狀態:----" + response.getStatusLine().getStatusCode());
- if (response != null && response.getStatusLine().getStatusCode() == 200) {
- return response.getEntity().getContent();
- } else
- post.abort();
- return null;
- }
-
-
-
-
-
-
-
-
-
-
-
- public static HttpResponse post(String url, List<BasicNameValuePair> list,
- String encode) throws Throwable {
- HttpResponse response = null;
- HttpClient client = new DefaultHttpClient();
-
- client.getParams().setIntParameter(
- HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
- client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
- 5000);
-
- HttpPost httpRequest = new HttpPost(url);
- if (list != null) {
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
-
- httpRequest.setEntity(entity);
- }
-
- response = client.execute(httpRequest);
- return response;
-
- }
-
-
-
-
-
- public static InputStream upload(String uploadUrl, String fileName,
- String fileUrl) throws Exception {
- String end = "\r\n";
- String twoHyphens = "--";
- String boundary = "*****";
- InputStream is = null;
- URL url = new URL(uploadUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
- conn.setDoInput(true);
- conn.setDoOutput(true);
- conn.setUseCaches(false);
-
- conn.setRequestMethod("POST");
-
- conn.setRequestProperty("Connection", "Keep-Alive");
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="
- + boundary);
-
-
- if (fileName != null && fileUrl != null) {
- conn.setRequestProperty("picName", fileName);
-
- DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
- ds.writeBytes(twoHyphens + boundary + end);
- ds.writeBytes("Content-Disposition: form-data; "
- + "name=\"file1\";filename=\"" + fileName + "\"" + end);
- ds.writeBytes(end);
-
-
- FileInputStream fStream = new FileInputStream(fileUrl);
-
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
-
- int length = -1;
-
- while ((length = fStream.read(buffer)) != -1) {
-
- ds.write(buffer, 0, length);
- }
- ds.writeBytes(end);
- ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
-
-
- fStream.close();
- ds.flush();
- ds.close();
- }
-
- is = conn.getInputStream();
- return is;
- }
-
-
-
-
-
-
-
-
- public static boolean isMobileNO(String mobiles) {
-
-
- Pattern p = Pattern.compile("^([0-9]{3})\\d{8}$");
- Matcher m = p.matcher(mobiles);
- return m.matches();
- }
-
-
-
-
-
-
-
- public static boolean isEmail(String strEmail) {
- String strPattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
- Pattern p = Pattern.compile(strPattern);
- Matcher m = p.matcher(strEmail);
- return m.matches();
- }
-
-
-
-
-
-
-
- public static boolean isCode(String strCode) {
- String strPattern = "^[0-9]{6}";
- Pattern p = Pattern.compile(strPattern);
- Matcher m = p.matcher(strCode);
- return m.matches();
- }
-
-
-
-
-
-
-
- public static boolean isCheckCode(String strCode) {
- String strPattern = "^[0-9a-zA-Z]{6}";
- Pattern p = Pattern.compile(strPattern);
- Matcher m = p.matcher(strCode);
- return m.matches();
- }
-
-
-
-
-
-
-
- public static boolean isPassCode(String strCode) {
- String strPattern = "^[0-9a-zA-Z@*%#()><!_~]{6,12}";
- Pattern p = Pattern.compile(strPattern);
- Matcher m = p.matcher(strCode);
- return m.matches();
- }
-
-
-
-
-
-
-
- public static boolean isLegalUrlParameters(String str) {
- String strPattern = "[&=\\s]+";
- Pattern p = Pattern.compile(strPattern);
- Matcher m = p.matcher(str);
- return m.find();
- }
-
-
-
-
-
-
-
- public static boolean isIp(String text) {
- if (text != null && text != "") {
-
- String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
- + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
- + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
- + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
-
- if (text.matches(regex)) {
-
- return true;
- } else {
- return false;
- }
- }
- return false;
- }
-
-
-
-
-
-
-
-
- public final static String MD5(String s) throws Exception {
- char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'a', 'b', 'c', 'd', 'e', 'f' };
-
- byte[] strTemp = s.getBytes();
- MessageDigest mdTemp = MessageDigest.getInstance("MD5");
- mdTemp.update(strTemp);
- byte[] md = mdTemp.digest();
- int j = md.length;
- char str[] = new char[j * 2];
- int k = 0;
- for (int i = 0; i < j; i++) {
- byte byte0 = md[i];
- str[k++] = hexDigits[byte0 >>> 4 & 0xf];
- str[k++] = hexDigits[byte0 & 0xf];
- }
- return new String(str);
- }
-
-
-
-
-
-
-
-
-
-
-
- public static String AESEncrypt(String sSrc, String sKey) throws Exception {
- if (sKey == null) {
- System.out.print("Key爲空null");
- return null;
- }
-
- if (sKey.length() != 16) {
- System.out.print("Key無效");
- return null;
- }
- byte[] raw = sKey.getBytes();
- SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
- cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
- byte[] encrypted = cipher.doFinal(sSrc.getBytes());
- return byte2hex(encrypted).toLowerCase();
- }
-
-
-
-
-
-
-
-
-
- public static String AESDecrypt(String sSrc, String sKey) throws Exception {
-
- if (sKey == null) {
- System.out.print("Key爲空null");
- return null;
- }
-
- if (sKey.length() != 16) {
- System.out.print("Key無效");
- return null;
- }
- byte[] raw = sKey.getBytes("ASCII");
- SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
- cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
- byte[] encrypted1 = hex2byte(sSrc);
- byte[] original = cipher.doFinal(encrypted1);
- String originalString = new String(original);
- return originalString;
- }
-
- private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1',
- (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6',
- (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B',
- (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' };
-
-
-
-
-
-
-
-
- public static String getHex(byte[] raw, int len) {
- byte[] hex = new byte[2 * len];
- int index = 0;
- int pos = 0;
-
- for (byte b : raw) {
- if (pos >= len)
- break;
-
- pos++;
- int v = b & 0xFF;
- hex[index++] = HEX_CHAR_TABLE[v >>> 4];
- hex[index++] = HEX_CHAR_TABLE[v & 0xF];
- }
- return new String(hex);
- }
-
-
-
-
-
-
-
- public static long getDec(byte[] bytes) {
- long result = 0;
- long factor = 1;
- for (int i = 0; i < bytes.length; ++i) {
- long value = bytes[i] & 0xffl;
- result += value * factor;
- factor *= 256l;
- }
- return result;
- }
-
-
-
-
-
-
-
- public static String byte2hex(byte[] b) {
- String hs = "";
- String stmp = "";
- for (int n = 0; n < b.length; n++) {
- stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
- if (stmp.length() == 1) {
- hs = hs + "0" + stmp;
- } else {
- hs = hs + stmp;
- }
- }
- return hs.toUpperCase();
- }
-
-
-
-
-
-
-
- public static byte[] hex2byte(String strhex) {
- if (strhex == null) {
- return null;
- }
- int l = strhex.length();
- if (l % 2 == 1) {
- return null;
- }
- byte[] b = new byte[l / 2];
- for (int i = 0; i != l / 2; i++) {
- b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
- 16);
- }
- return b;
- }
-
-
-
-
-
-
-
- public static int reverseToInt(char c) {
- if (c == 'A')
- return 10;
- else if (c == 'B')
- return 11;
- else if (c == 'C')
- return 12;
- else if (c == 'D')
- return 13;
- else if (c == 'E')
- return 14;
- else if (c == 'F')
歡迎關注本站公眾號,獲取更多信息