热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Android开发之超实用的系统管理工具类【SD卡,网络,uri,屏幕,网络,软键盘,文本,进程等】

这篇文章主要介绍了Android开发之超实用的系统管理工具类,涉及Android针对SD卡,网络,uri,屏幕,网络,软键盘,文本,进程等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Android开发之超实用的系统管理工具类。分享给大家供大家参考,具体如下:

这是一个系统管理工具类,管理sd卡,判断网络,uri转换,获取屏幕宽高,获取网络类型,隐藏软键盘,复制文本到粘贴板,获取状态栏高度,获取当前进程等。

上代码

import java.io.File;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
@SuppressWarnings("deprecation")
public class SystemUtil {
  public static final int NETTYPE_WIFI = 0x01;
  public static final int NETTYPE_CMWAP = 0x02;
  public static final int NETTYPE_CMNET = 0x03;
  /** 判断是否手机插入Sd卡 */
  public static boolean sdCardUseable() {
    return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
  }
  /**
   * 获取Sd卡的总容量
   *
   * @return
   */
  @SuppressLint("NewApi") public static long getSdCardTotalSize() {
    if(!sdCardUseable()){
      return 0;
    }
    // 取得SD卡文件路径
    File path = Environment.getExternalStorageDirectory();
    StatFs sf = new StatFs(path.getPath());
    // 获取单个数据块的大小(Byte)
    long blockSize = sf.getBlockSizeLong();
    // 获取所有数据块数
    long allBlocks = sf.getBlockCountLong();
    // 返回SD卡大小
    // return allBlocks * blockSize; //单位Byte
    // return (allBlocks * blockSize)/1024; //单位KB
    return (allBlocks * blockSize) / 1024 / 1024; // 单位MB
  }
  /**
   * 获取Sd卡的可用容量
   *
   * @return
   */
  @SuppressLint("NewApi") public static long getSdCardFreeSize() {
    if(!sdCardUseable()){
      return 0;
    }
    // 取得SD卡文件路径
    File path = Environment.getExternalStorageDirectory();
    StatFs sf = new StatFs(path.getPath());
    // 获取单个数据块的大小(Byte)
    long blockSize = sf.getBlockSizeLong();
    // 空闲的数据块的数量
    long freeBlocks = sf.getAvailableBlocksLong();
    // 返回SD卡空闲大小
    // return freeBlocks * blockSize; //单位Byte
    // return (freeBlocks * blockSize)/1024; //单位KB
    return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
  }
  /**
   * 判断是否联网或者漫游
   *
   * @param context
   * @return boolean
   */
  public static boolean hasNet(Context context) {
    // 获得ConnectivityManager的管理器
    NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (info == null || !info.isConnected()) {
      return false;
    }
    if (info.isRoaming()) { // 漫游判断
      return true;
    }
    return true;
  }
  /** 获得The data stream for the file */
  public static String getUrlPath(Activity context, Uri uri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.managedQuery(uri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
  }
  /** 从传入Uri获得真实的path */
  public String getRealPathFromURI(Activity context, Uri contentUri) {
    // can post image
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.managedQuery(contentUri, proj, // Which columns
                                // to return
        null, // WHERE clause; which rows to return (all rows)
        null, // WHERE clause selection arguments (none)
        null); // Order-by clause (ascending by name)
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
  }
  /** 获得屏幕的宽度 */
  public static int getScreenWidth(Activity context) {
    DisplayMetrics outMetrics = new DisplayMetrics();
    context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
    return outMetrics.widthPixels;
  }
  /** 获取屏幕的高度 */
  public static int getScreenHeight(Activity context) {
    DisplayMetrics outMetrics = new DisplayMetrics();
    context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
    return outMetrics.heightPixels;
  }
  /** 获得网络的类型 */
  public static int getNetworkType(Context context) {
    int netType = 0;
    ConnectivityManager cOnnectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo == null) { // 判断是否联网
      return netType;
    }
    int nType = networkInfo.getType(); // 获得
    if (nType == ConnectivityManager.TYPE_MOBILE) {
      String extraInfo = networkInfo.getExtraInfo();
      if (!TextUtils.isEmpty(extraInfo)) {
        if (extraInfo.toLowerCase().equals("cmnet")) {
          netType = NETTYPE_CMNET;
        } else {
          netType = NETTYPE_CMWAP;
        }
      }
    } else if (nType == ConnectivityManager.TYPE_WIFI) {
      netType = NETTYPE_WIFI;
    }
    return netType;
  }
  /** 隐藏软件盘 */
  public static void hideSoftKeyborad(Activity context) {
    final View v = context.getWindow().peekDecorView(); // Retrieve the
                              // current decor
                              // view
    if (v != null && v.getWindowToken() != null) {
      InputMethodManager imm = (InputMethodManager) context // 获得输入方法的Manager
          .getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
  }
  /**
   * 复制文本到剪切板
   *
   * @param context
   * @param text
   */
  @TargetApi(value = 11)
  @SuppressLint({ "NewApi", "NewApi" })
  public static void copyText(Context context, String text) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) context
          .getSystemService(Context.CLIPBOARD_SERVICE);
      ClipData clipData = ClipData.newPlainText("label", text);
      clipboardManager.setPrimaryClip(clipData);
    } else {
      android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
      clipboardManager.setText(text);
    }
  }
  /**
   * 获取状态栏高度
   *
   * @return
   */
  public static int getStatusBarHeight(Context context) {
    Class<&#63;> c = null;
    Object obj = null;
    java.lang.reflect.Field field = null;
    int x = 0;
    int 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);
      return statusBarHeight;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return statusBarHeight;
  }
  /**
   * 获取当前进程名
   * @param context
   * @return 进程名
   */
  public static final String getProcessName(Context context) {
    String processName = null;
    // ActivityManager
    ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
    while (true) {
      for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
        if (info.pid == android.os.Process.myPid()) {
          processName = info.processName;
          break;
        }
      }
      // go home
      if (!TextUtils.isEmpty(processName)) {
        return processName;
      }
      // take a rest and again
      try {
        Thread.sleep(100L);
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    }
  }
}

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。


推荐阅读
  • 本文介绍了如何使用PHP向系统日历中添加事件的方法,通过使用PHP技术可以实现自动添加事件的功能,从而实现全局通知系统和迅速记录工具的自动化。同时还提到了系统exchange自带的日历具有同步感的特点,以及使用web技术实现自动添加事件的优势。 ... [详细]
  • 2018年人工智能大数据的爆发,学Java还是Python?
    本文介绍了2018年人工智能大数据的爆发以及学习Java和Python的相关知识。在人工智能和大数据时代,Java和Python这两门编程语言都很优秀且火爆。选择学习哪门语言要根据个人兴趣爱好来决定。Python是一门拥有简洁语法的高级编程语言,容易上手。其特色之一是强制使用空白符作为语句缩进,使得新手可以快速上手。目前,Python在人工智能领域有着广泛的应用。如果对Java、Python或大数据感兴趣,欢迎加入qq群458345782。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 学习SLAM的女生,很酷
    本文介绍了学习SLAM的女生的故事,她们选择SLAM作为研究方向,面临各种学习挑战,但坚持不懈,最终获得成功。文章鼓励未来想走科研道路的女生勇敢追求自己的梦想,同时提到了一位正在英国攻读硕士学位的女生与SLAM结缘的经历。 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • 本文介绍了brain的意思、读音、翻译、用法、发音、词组、同反义词等内容,以及脑新东方在线英语词典的相关信息。还包括了brain的词汇搭配、形容词和名词的用法,以及与brain相关的短语和词组。此外,还介绍了与brain相关的医学术语和智囊团等相关内容。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • Echarts图表重复加载、axis重复多次请求问题解决记录
    文章目录1.需求描述2.问题描述正常状态:问题状态:3.解决方法1.需求描述使用Echats实现了一个中国地图:通过选择查询周期&#x ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • Python字典推导式及循环列表生成字典方法
    本文介绍了Python中使用字典推导式和循环列表生成字典的方法,包括通过循环列表生成相应的字典,并给出了执行结果。详细讲解了代码实现过程。 ... [详细]
author-avatar
张馨桐等你2502895757
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有