首页 > 代码库 > Android设备网络、屏幕尺寸、SD卡、本地IP、存储空间等信息获取工具类
Android设备网络、屏幕尺寸、SD卡、本地IP、存储空间等信息获取工具类
Android设备网络、屏幕尺寸、SD卡、本地IP、存储空间、服务、进程、应用包名等信息获取的整合工具类。
1 package com.qiyu.ddb.util; 2 3 import android.annotation.SuppressLint; 4 import android.annotation.TargetApi; 5 import android.app.Activity; 6 import android.app.ActivityManager; 7 import android.content.ClipData; 8 import android.content.ClipboardManager; 9 import android.content.ComponentName; 10 import android.content.Context; 11 import android.content.Intent; 12 import android.content.pm.PackageInfo; 13 import android.content.pm.PackageManager; 14 import android.content.pm.ResolveInfo; 15 import android.content.res.Resources; 16 import android.database.Cursor; 17 import android.net.ConnectivityManager; 18 import android.net.NetworkInfo; 19 import android.net.Uri; 20 import android.os.Environment; 21 import android.os.StatFs; 22 import android.os.Vibrator; 23 import android.provider.MediaStore; 24 import android.telephony.TelephonyManager; 25 import android.text.TextUtils; 26 import android.util.DisplayMetrics; 27 import android.view.View; 28 import android.view.ViewTreeObserver; 29 import android.view.Window; 30 import android.view.inputmethod.InputMethodManager; 31 32 import java.io.File; 33 import java.net.InetAddress; 34 import java.net.NetworkInterface; 35 import java.net.SocketException; 36 import java.util.ArrayList; 37 import java.util.Enumeration; 38 import java.util.List; 39 import java.util.Map; 40 41 42 /** 43 * Desction:设备相关工具类 44 * Author:pengjianbo 45 * Date:17/4/30 上午5:09 46 */ 47 public class DeviceUtils 48 { 49 50 /** 51 * Unknown network class 52 */ 53 public static final int NETWORK_CLASS_UNKNOWN = 0; 54 55 /** 56 * wifi net work 57 */ 58 public static final int NETWORK_WIFI = 1; 59 60 /** 61 * "2G" networks 62 */ 63 public static final int NETWORK_CLASS_2_G = 2; 64 65 /** 66 * "3G" networks 67 */ 68 public static final int NETWORK_CLASS_3_G = 3; 69 70 /** 71 * "4G" networks 72 */ 73 public static final int NETWORK_CLASS_4_G = 4; 74 75 /** 76 * 判断SDCard是否可用 77 */ 78 public static boolean existSDCard() 79 { 80 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) 81 { 82 return true; 83 } 84 else 85 { 86 return false; 87 } 88 } 89 90 /** 91 * 获取本机IP地址 92 * 93 * @return 94 */ 95 public static String getLocalIPAddress() 96 { 97 98 try 99 { 100 for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) 101 { 102 NetworkInterface intf = en.nextElement(); 103 for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) 104 { 105 InetAddress inetAddress = enumIpAddr.nextElement(); 106 if (!inetAddress.isLoopbackAddress()) 107 { 108 return inetAddress.getHostAddress().toString(); 109 } 110 } 111 } 112 } 113 catch (SocketException ex) 114 { 115 return "0.0.0.0"; 116 } 117 return "0.0.0.0"; 118 } 119 120 /** 121 * 多个SD卡时 取外置SD卡 122 * 123 * @return 124 */ 125 public static String getExternalStorageDirectory() 126 { 127 // 参考文章 128 // http://blog.csdn.net/bbmiku/article/details/7937745 129 Map<String, String> map = System.getenv(); 130 String[] values = new String[map.values().size()]; 131 map.values().toArray(values); 132 String path = values[values.length - 1]; 133 if (path.startsWith("/mnt/") && !Environment.getExternalStorageDirectory().getAbsolutePath().equals(path)) 134 { 135 return path; 136 } 137 else 138 { 139 return null; 140 } 141 } 142 143 /** 144 * 获取可用空间大小 145 * 146 * @return 147 */ 148 public static long getAvailaleSize() 149 { 150 if (!existSDCard()) 151 { 152 return 0l; 153 } 154 File path = Environment.getExternalStorageDirectory(); //取得sdcard文件路径 155 StatFs stat = new StatFs(path.getPath()); 156 long blockSize = stat.getBlockSize(); 157 long availableBlocks = stat.getAvailableBlocks(); 158 return availableBlocks * blockSize; 159 } 160 161 /** 162 * 获取SD大小 163 * 164 * @return 165 */ 166 public static long getAllSize() 167 { 168 if (!existSDCard()) 169 { 170 return 0l; 171 } 172 File path = Environment.getExternalStorageDirectory(); 173 StatFs stat = new StatFs(path.getPath()); 174 long blockSize = stat.getBlockSize(); 175 long availableBlocks = stat.getBlockCount(); 176 return availableBlocks * blockSize; 177 } 178 179 public static boolean isOnline(Context context) 180 { 181 try 182 { 183 ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 184 NetworkInfo ni = cm.getActiveNetworkInfo(); 185 return ni != null ? ni.isConnectedOrConnecting() : false; 186 } 187 catch (Exception e) 188 { 189 e.printStackTrace(); 190 return false; 191 } 192 } 193 194 /** 195 * 服务是否运行 196 * 197 * @param mContext 198 * @param className 199 * @return 200 */ 201 public static boolean isServiceRunning(Context mContext, String className) 202 { 203 boolean isRunning = false; 204 ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); 205 List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE); 206 if (serviceList.size() == 0) 207 { 208 return false; 209 } 210 for (int i = 0; i < serviceList.size(); i++) 211 { 212 if (serviceList.get(i).service.getClassName().equals(className) == true) 213 { 214 isRunning = true; 215 break; 216 } 217 } 218 return isRunning; 219 } 220 221 /** 222 * 进程是否运行 223 */ 224 public static boolean isProessRunning(Context context, String proessName) 225 { 226 boolean isRunning = false; 227 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 228 229 List<ActivityManager.RunningAppProcessInfo> lists = am.getRunningAppProcesses(); 230 for (ActivityManager.RunningAppProcessInfo info : lists) 231 { 232 if (info.processName.equals(proessName)) 233 { 234 isRunning = true; 235 return isRunning; 236 } 237 } 238 239 return isRunning; 240 } 241 242 /** 243 * 震动 244 * 245 * @param context 246 * @param duration 247 */ 248 public static void vibrate(Context context, long duration) 249 { 250 Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); 251 long[] pattern = {0, duration}; 252 vibrator.vibrate(pattern, -1); 253 } 254 255 /** 256 * 获取最后一次拍照的图片 257 * 258 * @param context 259 * @return 260 */ 261 public static String getLatestCameraPicture(Context context) 262 { 263 264 if (!existSDCard()) 265 { 266 return null; 267 } 268 269 String[] projection = new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns 270 .BUCKET_DISPLAY_NAME, MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images.ImageColumns.MIME_TYPE}; 271 Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images 272 .ImageColumns.DATE_TAKEN + " DESC"); 273 if (cursor.moveToFirst()) 274 { 275 String path = cursor.getString(1); 276 return path; 277 } 278 return null; 279 } 280 281 /** 282 * 获取手机大小(分辨率) 283 * 284 * @param activity 285 * @return 286 */ 287 public static DisplayMetrics getScreenPix(Activity activity) 288 { 289 // DisplayMetrics 一个描述普通显示信息的结构,例如显示大小、密度、字体尺寸 290 DisplayMetrics displaysMetrics = new DisplayMetrics(); 291 // 获取手机窗口的Display 来初始化DisplayMetrics 对象 292 // getManager()获取显示定制窗口的管理器。 293 // 获取默认显示Display对象 294 // 通过Display 对象的数据来初始化一个DisplayMetrics 对象 295 activity.getWindowManager().getDefaultDisplay().getMetrics(displaysMetrics); 296 return displaysMetrics; 297 } 298 299 /** 300 * 复制到剪切板 301 * 302 * @param context 303 * @param content 304 */ 305 @TargetApi(11) 306 public static void coptyToClipBoard(Context context, String content) 307 { 308 int currentapiVersion = android.os.Build.VERSION.SDK_INT; 309 if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) 310 { 311 ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 312 ClipData clip = ClipData.newPlainText("label", content); 313 clipboard.setPrimaryClip(clip); 314 } 315 else 316 { 317 android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); 318 clipboard.setText(content); 319 } 320 } 321 322 /** 323 * 获取非系统应用包名 324 * 325 * @param context 326 * @return 327 */ 328 public static List<String> getAppPackageNamelist(Context context) 329 { 330 List<String> packList = new ArrayList<>(); 331 PackageManager pm = context.getPackageManager(); 332 List<PackageInfo> packinfos = pm.getInstalledPackages(0); 333 for (PackageInfo packinfo : packinfos) 334 { 335 String packname = packinfo.packageName; 336 packList.add(packname); 337 } 338 339 return packList; 340 } 341 342 /** 343 * 判断某个应用是否已经安装 344 * 345 * @param context 上下文 346 * @param packageName 包名 347 * @return 是否已经安装 348 */ 349 public static boolean isAppInstall(Context context, String packageName) 350 { 351 // 获取packagemanager 352 final PackageManager packageManager = context.getPackageManager(); 353 // 获取所有已安装程序的包信息 354 List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0); 355 // 用于存储所有已安装程序的包名 356 List<String> packageNames = new ArrayList<String>(); 357 // 从pinfo中将包名字逐一取出,压入pName list中 358 if (packageInfos != null) 359 { 360 for (int i = 0; i < packageInfos.size(); i++) 361 { 362 String packName = packageInfos.get(i).packageName; 363 packageNames.add(packName); 364 } 365 } 366 // 判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE 367 return packageNames.contains(packageName); 368 } 369 370 public static int dip2px(Context context, float dipValue) 371 { 372 final float scale = context.getResources().getDisplayMetrics().density; 373 return (int) (dipValue * scale + 0.5f); 374 } 375 376 public static int px2dip(Context context, float pxValue) 377 { 378 final float scale = context.getResources().getDisplayMetrics().density; 379 return (int) (pxValue / scale + 0.5f); 380 } 381 382 /** 383 * 判断是否有软控制键(手机底部几个按钮) 384 * 385 * @param activity 386 * @return 387 */ 388 public boolean isSoftKeyAvail(Activity activity) 389 { 390 final boolean[] isSoftkey = {false}; 391 final View activityRootView = (activity).getWindow().getDecorView().findViewById(android.R.id.content); 392 activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() 393 { 394 @Override 395 public void onGlobalLayout() 396 { 397 int rootViewHeight = activityRootView.getRootView().getHeight(); 398 int viewHeight = activityRootView.getHeight(); 399 int heightDiff = rootViewHeight - viewHeight; 400 if (heightDiff > 100) 401 { // 99% of the time the height diff will be due to a keyboard. 402 isSoftkey[0] = true; 403 } 404 } 405 }); 406 return isSoftkey[0]; 407 } 408 409 /** 410 * 获取statusbar高度 411 * 412 * @param context 413 * @return 414 */ 415 public static int getStatusBarHeight(Context context) 416 { 417 int height = 0; 418 int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); 419 if (resourceId > 0) 420 { 421 height = context.getResources().getDimensionPixelSize(resourceId); 422 } 423 424 return height; 425 } 426 427 /** 428 * 获取navigationbar高度 429 * 430 * @param context 431 * @return 432 */ 433 public static int getNavigationBarHeight(Context context) 434 { 435 int height = 0; 436 Resources resources = context.getResources(); 437 int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); 438 //获取NavigationBar的高度 439 if (resourceId > 0) 440 { 441 height = resources.getDimensionPixelSize(resourceId); 442 } 443 return height; 444 } 445 446 /** 447 * 获取状态栏高度+标题栏(ActionBar)高度 448 * (注意,如果没有ActionBar,那么获取的高度将和上面的是一样的,只有状态栏的高度) 449 * 450 * @param activity 451 * @return 452 */ 453 public static int getTopBarHeight(Activity activity) 454 { 455 return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); 456 } 457 458 459 /** 460 * @param @param context 461 * @param @param packageName 包名 462 * @return void 返回类型 463 * @throws 464 * @Title: startActivityForPackage 465 * @Description: TODO(通过) 466 */ 467 @SuppressLint("NewApi") 468 public static boolean startActivityForPackage(Context context, String packageName) 469 { 470 PackageInfo pi = null; 471 try 472 { 473 pi = context.getPackageManager().getPackageInfo(packageName, 0); 474 } 475 catch (PackageManager.NameNotFoundException e) 476 { 477 e.printStackTrace(); 478 return false; 479 } 480 481 Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null); 482 resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER); 483 resolveIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 484 // resolveIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 485 resolveIntent.setPackage(pi.packageName); 486 487 List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0); 488 489 ResolveInfo ri = apps.iterator().next(); 490 if (ri != null) 491 { 492 String packageName1 = ri.activityInfo.packageName; 493 String className = ri.activityInfo.name; 494 495 Intent intent = new Intent(Intent.ACTION_MAIN); 496 intent.addCategory(Intent.CATEGORY_LAUNCHER); 497 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 498 499 ComponentName cn = new ComponentName(packageName1, className); 500 501 intent.setComponent(cn); 502 context.startActivity(intent); 503 return true; 504 } 505 return false; 506 } 507 508 /** 509 * 隐藏键盘 510 * :强制隐藏 511 * 512 * @param context 513 */ 514 public static void hideInputSoftFromWindowMethod(Context context, View view) 515 { 516 try 517 { 518 InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 519 imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 520 } 521 catch (Exception e) 522 { 523 e.printStackTrace(); 524 } 525 } 526 527 /** 528 * 显示输入法 529 * 530 * @param context 531 * @param view 532 */ 533 public static void showInputSoftFromWindowMethod(Context context, View view) 534 { 535 try 536 { 537 InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 538 imm.showSoftInput(view, InputMethodManager.SHOW_FORCED); 539 } 540 catch (Exception e) 541 { 542 e.printStackTrace(); 543 } 544 } 545 546 /** 547 * 判断输入负是否处于激活状态 548 * 549 * @param context 550 * @return 551 */ 552 public static boolean isActiveSoftInput(Context context) 553 { 554 InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 555 return imm.isActive(); 556 } 557 558 /** 559 * 主动回到Home,后台运行 560 * 561 * @param context 562 */ 563 public static void goHome(Context context) 564 { 565 Intent mHomeIntent = new Intent(Intent.ACTION_MAIN); 566 mHomeIntent.addCategory(Intent.CATEGORY_HOME); 567 mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 568 context.startActivity(mHomeIntent); 569 } 570 571 /** 572 * 返回移动终端类型 573 * PHONE_TYPE_NONE :0 手机制式未知 574 * PHONE_TYPE_GSM :1 手机制式为GSM,移动和联通 575 * PHONE_TYPE_CDMA :2 手机制式为CDMA,电信 576 * PHONE_TYPE_SIP:3 577 * 578 * @param context 579 * @return 580 */ 581 public static int getPhoneType(Context context) 582 { 583 TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 584 return telephonyManager.getPhoneType(); 585 } 586 587 /** 588 * 判断手机连接的网络类型(wifi,2G,3G,4G) 589 * 联通的3G为UMTS或HSDPA,移动和联通的2G为GPRS或EGDE,电信的2G为CDMA,电信的3G为EVDO 590 * 591 * @param context 592 * @return 593 */ 594 public static int getNetType(Context context) 595 { 596 int netWorkType = NETWORK_CLASS_UNKNOWN; 597 598 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 599 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); 600 601 if (networkInfo != null && networkInfo.isConnected()) 602 { 603 int type = networkInfo.getType(); 604 605 if (type == ConnectivityManager.TYPE_WIFI) 606 { 607 netWorkType = NETWORK_WIFI; 608 } 609 else if (type == ConnectivityManager.TYPE_MOBILE) 610 { 611 TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 612 switch (telephonyManager.getNetworkType()) 613 { 614 case TelephonyManager.NETWORK_TYPE_GPRS: 615 case TelephonyManager.NETWORK_TYPE_EDGE: 616 case TelephonyManager.NETWORK_TYPE_CDMA: 617 case TelephonyManager.NETWORK_TYPE_1xRTT: 618 case TelephonyManager.NETWORK_TYPE_IDEN: 619 return NETWORK_CLASS_2_G; 620 case TelephonyManager.NETWORK_TYPE_UMTS: 621 case TelephonyManager.NETWORK_TYPE_EVDO_0: 622 case TelephonyManager.NETWORK_TYPE_EVDO_A: 623 case TelephonyManager.NETWORK_TYPE_HSDPA: 624 case TelephonyManager.NETWORK_TYPE_HSUPA: 625 case TelephonyManager.NETWORK_TYPE_HSPA: 626 case TelephonyManager.NETWORK_TYPE_EVDO_B: 627 case TelephonyManager.NETWORK_TYPE_EHRPD: 628 case TelephonyManager.NETWORK_TYPE_HSPAP: 629 return NETWORK_CLASS_3_G; 630 631 case TelephonyManager.NETWORK_TYPE_LTE: 632 return NETWORK_CLASS_4_G; 633 default: 634 return NETWORK_CLASS_UNKNOWN; 635 } 636 } 637 } 638 639 return netWorkType; 640 } 641 642 /** 643 * 跳转至拨号界面 644 * 645 * @param context 646 * @param phoneNumber 电话号码电话号码 647 */ 648 public static void callDial(Context context, String phoneNumber) 649 { 650 context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber))); 651 } 652 653 /** 654 * 发送短信 655 * 656 * @param context 657 * @param phoneNumber 658 * @param content 659 */ 660 public static void sendSms(Context context, String phoneNumber, String content) 661 { 662 Uri uri = Uri.parse("smsto:" + (TextUtils.isEmpty(phoneNumber) ? "" : phoneNumber)); 663 Intent intent = new Intent(Intent.ACTION_SENDTO, uri); 664 intent.putExtra("sms_body", TextUtils.isEmpty(content) ? "" : content); 665 context.startActivity(intent); 666 } 667 668 /** 669 * 判断当前设备是否为手机 670 * 671 * @param context 672 * @return 673 */ 674 public static boolean isPhone(Context context) 675 { 676 TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 677 if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) 678 { 679 return false; 680 } 681 else 682 { 683 return true; 684 } 685 } 686 }
Android设备网络、屏幕尺寸、SD卡、本地IP、存储空间等信息获取工具类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。