android 工具类
16lz
2022-07-06
Android的获取外部存储设备。
/ / 1。这个是获取安卓内置的SD卡 。Environment.getExternalStorageDirectory()getAbsolutePath(); <pre name="code" class="java">String[] paths =null;StorageManager sm = (StorageManager) this.getSystemService(Context.STORAGE_SERVICE);// 获取sdcard的路径:外置和内置try { paths = (String[]) sm.getClass().getMethod("getVolumePaths", null).invoke(sm, null);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();}//getPath2(); Toast.makeText(this, paths[0] +"======"+ paths[1]+ "===="+ paths.length , Toast.LENGTH_LONG).show();
获取SD卡上的图片的缩略图和视频的缩略图
/ ** *根据指定的图像路径和大小来获取缩略图 * 1。使用较小的内存空间,第一次获取的bitmap实际上为null,只是为了读取宽度和高度, *第二次读取的bitmap是根据比例压缩过的图像,第三次读取的bitmap是所要的缩略图。 * 2。缩略图对于原图像来讲没有拉伸,这里使用了2.2版本的新工具ThumbnailUtils,使 *用这个工具生成的图像不会被拉伸。 * @参数IMAGEPATH图像的路径 * @参数宽度指定输出图像的宽度 * @参数高度指定输出图像的高度 * @返回生成的缩略图 * / 私人点阵图getImageThumbnail(IMAGEPATH字符串,整型宽度,高度诠释){ 位图位图= NULL; BitmapFactory.Options选项=新BitmapFactory.Options(); options.inJustDecodeBounds = TRUE; / /获取这个图片的宽和高,注意此处的点阵图为空 位图= BitmapFactory.decodeFile(IMAGEPATH,期权); options.inJustDecodeBounds = FALSE; / /设为假 / /计算缩放比 整型H = options.outHeight; 整型W = options.outWidth; 整型beWidth = W /宽度; 整型beHeight = H /高度; 整型是= 1; 如果(beWidth <beHeight){ 是= beWidth; }其他{ 是= beHeight; } 如果(被<= 0){ 是= 1; } options.inSampleSize =是; / /重新读入图片,读取缩放后的位图,注意这次要把options.inJustDecodeBounds设为假 位图= BitmapFactory.decodeFile(IMAGEPATH,期权); / /利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个位图对象/ /位图= ThumbnailUtils.extractThumbnail(位图,宽度,高度,/ / ThumbnailUtils.OPTIONS_RECYCLE_INPUT); 返回位图; } / ** *获取视频的缩略图 *先通过ThumbnailUtils来创建一个视频的缩略图,然后再利用ThumbnailUtils来生成指定大小的缩略图。 *如果想要的缩略图的宽和高都小于MICRO_KIND,则类型要使用MICRO_KIND作为kind的值, * @参数videoPath视频的路径 * @参数宽度指定输出视频缩略图的宽度 * @参数高度指定输出视频缩略图的高度度 * @参数类型的参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。 *其中,MINI_KIND:512×384,MICRO_KIND:96×96 * @返回指定大小的视频缩略图 * / 私人点阵图getVideoThumbnail(字符串videoPath,诠释宽度,高度诠释, 整型的那种){ 位图位图= NULL; / /获取视频的缩略图 尝试{ 位图= ThumbnailUtils.createVideoThumbnail(videoPath,实物); 。Toast.makeText(这一点,“W =”+ bitmap.getWidth()+“ - H =”+ bitmap.getHeight(),Toast.LENGTH_SHORT)的show(); 位图= ThumbnailUtils.extractThumbnail(位图,宽度,高度, ThumbnailUtils.OPTIONS_RECYCLE_INPUT); }赶上(例外五){。Toast.makeText(这一点,“异常=”+ e.toString(),Toast.LENGTH_SHORT)的show();} 返回位图; }
获取手机的IP地址
/ **获取本地的IP经过修改的只获取IPv4的** / 公共静态字符串getMyLocalIpAddress(){ 尝试{ 对于(枚举<NetworkInterface> EN =的NetworkInterface 。getNetworkInterfaces(); en.hasMoreElements();} { 的NetworkInterface INTF = en.nextElement(); 对于(枚举<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();} { InetAddress类InetAddress类= enumIpAddr.nextElement(); 如果(!inetAddress.isLoopbackAddress()&&!inetAddress.isLinkLocalAddress()){ 返回inetAddress.getHostAddress()的toString(); } } } }赶上(例外){ Log.e(“WifiPreference Ip地址”,ex.toString()); } 返回null; } / **获取手机的IP 3G WIFI可以NetworkInterface.getHardwareAddress()没修改的获取到的是的IPv6的地址在4.0上* / 公共静态字符串getLocalIpAddress(){ 尝试{ 对于(枚举<NetworkInterface> EN = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();} { 的NetworkInterface INTF = en.nextElement(); 对于(枚举<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();} { InetAddress类InetAddress类= enumIpAddr.nextElement(); 如果(!inetAddress.isLoopbackAddress()){ 返回inetAddress.getHostAddress()的toString(); } } } }赶上(例外){ Log.e(“AAAA”,ex.toString()); } 返回null; } / **通过无线网络获取IP IPv6的* / 公共静态字符串GetIpAddress是(上下文CTX){ WifiManager wifi_service =(WifiManager)ctx.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcpInfo = wifi_service.getDhcpInfo(); WifiInfo wifiinfo = wifi_service.getConnectionInfo(); System.out.println(“无线信息----->”+ wifiinfo.getIpAddress()); System.out.println(“DHCP信息门户----->”+ Formatter.formatIpAddress(dhcpInfo.gateway)); System.out.println(“DHCP信息网络掩码----->”+ Formatter.formatIpAddress(dhcpInfo.netmask)); / / DhcpInfo中的ip地址是一个整数型的变量,通过格式化程序将其转化为字符串的IP地址 返回Formatter.formatIpAddress(dhcpInfo.ipAddress); } / **根据无线信息获取本地的Mac必须打开无线网络的IPv6 ** / 公共静态字符串getLocalMacAddressFromWifiInfo(上下文上下文){ WifiManager无线=(WifiManager)context.getSystemService(Context.WIFI_SERVICE); WifiInfo信息= wifi.getConnectionInfo(); 返回info.getMacAddress(); }/ ** *获取程序的网络环境 * /公共静态布尔getNetWorkStatus(上下文上下文){布尔B =真; ConnectivityManager connManager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 的NetworkInfo的wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 的NetworkInfo移动= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 如果(!wifi.isConnectedOrConnecting()&&!mobile.isConnectedOrConnecting()){ B = FALSE; } 返回b;}贴2张IPV64的图
获取手机的相关信息
StringBuilder phoneInfo = new StringBuilder(); phoneInfo.append("Product: " + android.os.Build.PRODUCT + System.getProperty("line.separator")); phoneInfo.append( "CPU_ABI: " + android.os.Build.CPU_ABI + System.getProperty("line.separator")); phoneInfo.append( "TAGS: " + android.os.Build.TAGS + System.getProperty("line.separator")); phoneInfo.append( "VERSION_CODES.BASE: " + android.os.Build.VERSION_CODES.BASE + System.getProperty("line.separator")); phoneInfo.append( "MODEL: " + android.os.Build.MODEL + System.getProperty("line.separator")); phoneInfo.append( "SDK: " + android.os.Build.VERSION.SDK + System.getProperty("line.separator")); phoneInfo.append( "VERSION.RELEASE: " + android.os.Build.VERSION.RELEASE + System.getProperty("line.separator")); phoneInfo.append( "DEVICE: " + android.os.Build.DEVICE + System.getProperty("line.separator")); phoneInfo.append( "DISPLAY: " + android.os.Build.DISPLAY + System.getProperty("line.separator")); phoneInfo.append( "BRAND: " + android.os.Build.BRAND + System.getProperty("line.separator")); phoneInfo.append( "BOARD: " + android.os.Build.BOARD + System.getProperty("line.separator")); phoneInfo.append( "FINGERPRINT: " + android.os.Build.FINGERPRINT + System.getProperty("line.separator")); phoneInfo.append( "ID: " + android.os.Build.ID + System.getProperty("line.separator")); phoneInfo.append( "MANUFACTURER: " + android.os.Build.MANUFACTURER + System.getProperty("line.separator")); phoneInfo.append( "USER: " + android.os.Build.USER + System.getProperty("line.separator")); TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); phoneInfo.append("DeviceId(IMEI) = " + tm.getDeviceId() + System.getProperty("line.separator")); phoneInfo.append("DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + System.getProperty("line.separator")); phoneInfo.append("Line1Number = " + tm.getLine1Number() + System.getProperty("line.separator")); phoneInfo.append("NetworkCountryIso = " + tm.getNetworkCountryIso() + System.getProperty("line.separator")); phoneInfo.append("NetworkOperator = " + tm.getNetworkOperator() + System.getProperty("line.separator")); phoneInfo.append("NetworkOperatorName = " + tm.getNetworkOperatorName() + System.getProperty("line.separator")); phoneInfo.append("NetworkType = " + tm.getNetworkType() + System.getProperty("line.separator")); phoneInfo.append("PhoneType = " + tm.getPhoneType() + System.getProperty("line.separator")); phoneInfo.append("SimCountryIso = " + tm.getSimCountryIso() + System.getProperty("line.separator")); phoneInfo.append("SimOperator = " + tm.getSimOperator() + System.getProperty("line.separator")); phoneInfo.append("SimOperatorName = " + tm.getSimOperatorName() + System.getProperty("line.separator")); phoneInfo.append("SimSerialNumber = " + tm.getSimSerialNumber() + System.getProperty("line.separator")); phoneInfo.append("SimState = " + tm.getSimState() + System.getProperty("line.separator")); phoneInfo.append("SubscriberId(IMSI) = " + tm.getSubscriberId() + System.getProperty("line.separator")); phoneInfo.append("VoiceMailNumber = " + tm.getVoiceMailNumber() + System.getProperty("line.separator"));附上2张图
经纬度方面的转换
public class ConvertLatlng {// 经纬度度分秒转换为小数public static double convertToDecimal(double du, double fen, double miao) {if (du < 0)return -(Math.abs(du) + (Math.abs(fen) + (Math.abs(miao) / 60)) / 60);return Math.abs(du) + (Math.abs(fen) + (Math.abs(miao) / 60)) / 60;}public static double convertTodecimal(String sdu, String sfen, String smiao) {double du = Double.parseDouble(sdu);double fen = Double.parseDouble(sfen);double miao = Double.parseDouble(smiao);if (du < 0)return -(Math.abs(du) + (Math.abs(fen) + (Math.abs(miao) / 60)) / 60);return Math.abs(du) + (Math.abs(fen) + (Math.abs(miao) / 60)) / 60;}// 以字符串形式输入经纬度的转换public static double convertToDecimalByString(String latlng) {double du = 0;double fen = 0;double miao = 0;if (latlng.indexOf("°") != -1) {du = Double.parseDouble(latlng.substring(0, latlng.indexOf("°")));if (latlng.indexOf("′") != -1) {fen = Double.parseDouble(latlng.substring(latlng.indexOf("°") + 1, latlng.indexOf("′")));if (latlng.indexOf("″") != -1) {miao = Double.parseDouble(latlng.substring(latlng.indexOf("′") + 1, latlng.indexOf("″")));}}}if (du < 0)return -(Math.abs(du) + (fen + (miao / 60)) / 60);return du + (fen + (miao / 60)) / 60;}// 将小数转换为度分秒public static String convertToSexagesimal(double num) {int du = (int) Math.floor(Math.abs(num)); // 获取整数部分double temp = getdPoint(Math.abs(num)) * 60;int fen = (int) Math.floor(temp); // 获取整数部分double miao = getdPoint(temp) * 60;if (num < 0)return "-" + du + "°" + fen + "′" + miao + "″";return du + "°" + fen + "′" + miao + "″";}// 获取小数部分public static double getdPoint(double num) {double d = num;int fInt = (int) d;BigDecimal b1 = new BigDecimal(Double.toString(d));BigDecimal b2 = new BigDecimal(Integer.toString(fInt));double dPoint = b1.subtract(b2).floatValue();return dPoint;}//public void test1() {double convertTodecimal = convertTodecimal("123", "19", "15");System.out.println(convertTodecimal);}}
获取状态栏的高度
//获取状态栏的高度1Rect frame = new Rect();getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);int statusBarHeight = frame.top;//2.转自别人的,有些手机必须要用下面的方法才能获取到public static int getStatusBarHeight(Context context){ Class<?> c = null; Object obj = null; Field field = null; int x = 0, statusBarHeight = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); statusBarHeight = context.getResources().getDimensionPixelSize(x); Log.v("@@@@@@", "the status bar height is : " + statusBarHeight); } catch (Exception e1) { e1.printStackTrace(); } return statusBarHeight; }
判断输入的文本 是否有中文字符
private static final boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { return true; } return false;}public static final boolean isChinese(String strName) { char[] ch = strName.toCharArray(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (isChinese(c)) { return true; } } return false;}
查看手机磁盘空间
public static long isEnough(){ StatFs statFs = new StatFs(Environment.getExternalStorageDirectory() .getAbsolutePath()); //sd卡分区数 int blockCounts = statFs.getBlockCount(); Log.e("ray", "blockCounts" + blockCounts); //sd卡可用分区数 int avCounts = statFs.getAvailableBlocks(); Log.e("ray", "avCounts" + avCounts); //一个分区数的大小 long blockSize = statFs.getBlockSize(); Log.e("ray", "blockSize" + blockSize); //sd卡可用空间 long spaceLeft = avCounts * blockSize; Log.e("ray", "spaceLeft" + spaceLeft); System.out.println("=spaceLeft"+ spaceLeft); return spaceLeft; }
默认方法执行日志类,
public final class LogHelper { private static boolean mIsDebugMode = true;//获取堆栈信息会影响性能,发布应用时记得关闭DebugMode private static String mLogTag = "LogHelper"; private static final String CLASS_METHOD_LINE_FORMAT = "%s.%s() Line:%d (%s)"; public static void trace() { if (mIsDebugMode) { StackTraceElement traceElement = Thread.currentThread() .getStackTrace()[3];//从堆栈信息中获取当前被调用的方法信息 String logText = String.format(CLASS_METHOD_LINE_FORMAT, traceElement.getClassName(), traceElement.getMethodName(), traceElement.getLineNumber(), traceElement.getFileName()); Log.d(mLogTag, logText);//打印Log } } }
系统异常捕捉
/** * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告. * * 需要在Application中注册,为了要在程序启动器就监控整个程序。 */ public class CrashHandler implements UncaughtExceptionHandler { public static final String TAG = "CrashHandler"; //系统默认的UncaughtException处理类 private Thread.UncaughtExceptionHandler mDefaultHandler; //CrashHandler实例 private static CrashHandler instance; //程序的Context对象 private Context mContext; //用来存储设备信息和异常信息 private Map<String, String> infos = new HashMap<String, String>(); //用于格式化日期,作为日志文件名的一部分 private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); /** 保证只有一个CrashHandler实例 */ private CrashHandler() {} /** 获取CrashHandler实例 ,单例模式 */ public static CrashHandler getInstance() { if(instance == null) instance = new CrashHandler(); return instance; } /** * 初始化 */ public void init(Context context) { mContext = context; //获取系统默认的UncaughtException处理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); //设置该CrashHandler为程序的默认处理器 Thread.setDefaultUncaughtExceptionHandler(this); } /** * 当UncaughtException发生时会转入该函数来处理 */ @Override public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { //如果用户没有处理则让系统默认的异常处理器来处理 mDefaultHandler.uncaughtException(thread, ex); } else { try { Thread.sleep(3000); } catch (InterruptedException e) { Log.e(TAG, "error : ", e); } //退出程序 android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); } } /** * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. * * @param ex * @return true:如果处理了该异常信息;否则返回false. */ private boolean handleException(Throwable ex) { if (ex == null) { return false; } //收集设备参数信息 collectDeviceInfo(mContext); //使用Toast来显示异常信息 new Thread() { @Override public void run() { Looper.prepare(); Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show(); Looper.loop(); } }.start(); //保存日志文件 saveCatchInfo2File(ex); return true; } /** * 收集设备参数信息 * @param ctx */ public void collectDeviceInfo(Context ctx) { try { PackageManager pm = ctx.getPackageManager(); PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); if (pi != null) { String versionName = pi.versionName == null ? "null" : pi.versionName; String versionCode = pi.versionCode + ""; infos.put("versionName", versionName); infos.put("versionCode", versionCode); } } catch (NameNotFoundException e) { Log.e(TAG, "an error occured when collect package info", e); } Field[] fields = Build.class.getDeclaredFields(); for (Field field : fields) { try { field.setAccessible(true); infos.put(field.getName(), field.get(null).toString()); Log.d(TAG, field.getName() + " : " + field.get(null)); } catch (Exception e) { Log.e(TAG, "an error occured when collect crash info", e); } } } /** * 保存错误信息到文件中 * * @param ex * @return 返回文件名称,便于将文件传送到服务器 */ private String saveCatchInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : infos.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(key + "=" + value + "\n"); } Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.close(); String result = writer.toString(); sb.append(result); try { long timestamp = System.currentTimeMillis(); String time = formatter.format(new Date()); String fileName = "crash-" + time + "-" + timestamp + ".log"; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String path = "/mnt/sdcard/crash/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } FileOutputStream fos = new FileOutputStream(path + fileName); fos.write(sb.toString().getBytes()); //发送给开发人员 sendCrashLog2PM(path+fileName); fos.close(); } return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } return null; } /** * 将捕获的导致崩溃的错误信息发送给开发人员 * * 目前只将log日志保存在sdcard 和输出到LogCat中,并未发送给后台。 */ private void sendCrashLog2PM(String fileName){ if(!new File(fileName).exists()){ Toast.makeText(mContext, "日志文件不存在!", Toast.LENGTH_SHORT).show(); return; } FileInputStream fis = null; BufferedReader reader = null; String s = null; try { fis = new FileInputStream(fileName); reader = new BufferedReader(new InputStreamReader(fis, "GBK")); while(true){ s = reader.readLine(); if(s == null) break; //由于目前尚未确定以何种方式发送,所以先打出log日志。 Log.i("info", s.toString()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ // 关闭流 try { reader.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
根据 资源名称 获取 资源ID
//<span style="color:#333333;"><span style="font-family: Monaco, 'DejaVu sans Mono', 'Bitstream Vera sans Mono', Consolas, 'Courier new', monospace; font-size: 14px; word-wrap: normal; word-break: normal; line-height: 21px;"><span style="word-wrap: normal; word-break: normal;">第一个参数</span></span><span style="font-family: Monaco, 'DejaVu sans Mono', 'Bitstream Vera sans Mono', Consolas, 'Courier new', monospace; font-size: 14px; word-wrap: normal; word-break: normal; line-height: 21px;">格式是:包名 + : + 资源文件夹名 + / +资源名;</span><span style="font-family: Monaco, 'DejaVu sans Mono', 'Bitstream Vera sans Mono', Consolas, 'Courier new', monospace; font-size: 14px; word-wrap: normal; word-break: normal; line-height: 21px;"><span style="word-wrap: normal; word-break: normal;">是这种格式<wbr>然后其他的可以为null</wbr></span></span></span>Resources resources = context.getResources();int indentify = resources.getIdentifier(org.loveandroid.androidtest:drawable/icon",null,null);if(indentify>0){icon = resources.getDrawable(indentify);}第一个参数为资源名,第二个为资源属性是ID或者是Drawable,第三个为包名。
Resources resources = context.getResources();int indentify= getResources().getIdentifier("icon", "drawable", "org.anddev.android.testproject");
Resources themeResources=null; PackageManager pm=context.getPackageManager(); try { themeResources=pm.getResourcesForApplication(packageName); return themeResources.getIdentifier(name, type, packageName); } catch (NameNotFoundException e) { e.printStackTrace(); }
更多相关文章
- 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
- Android屏幕分辨率正确获取及PX,DPI,DP,SP等的对应关系
- android 获取唯一标识
- android拍照与读取相册
- Android(安卓)热点开关状态的判断和获取热点ssid
- Android软键盘适配问题
- AIR Native Extension的使用(Android)一 : 打包ane
- android之BitMap
- Android中GPS定位的简单应用