android上层相关服务使用

系统服务:

public class SystemService {

    /**
     * 音视频录制service是否正在运行
     */
    public static boolean isRecordServiceRunning(Context context, Class<Object> clazz) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (clazz.getName().equals(service.service.getClassName()))
                return true;
        }
        return false;
    }

    /**
     * 返回Home界面
     **/
    public static void goHome(Context m_con) {
        Intent goHome = new Intent(Intent.ACTION_MAIN);
        goHome.addCategory(Intent.CATEGORY_HOME);
        goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        m_con.startActivity(goHome);
    }

    /**
     * 得到当前系统配置语言的国家
     *
     * @param context
     * @return "zh_CN,en_US"下划线后半部分
     */
    public static String getSystemCountry(Context context) {
        Configuration conf = context.getResources().getConfiguration();
        Locale locale = conf.locale;
        return locale.getCountry();
    }

    /**
     * 根据字符串资源名字获取该资源ID
     *
     * @param context
     * @param sourcename
     * @return
     */
    public static int getSourceIdBySourceName(Context context, String sourcename) {
        return context.getResources().getIdentifier(sourcename, "string", context.getPackageName());// 根据资源名字获得资源ID
    }

    /**
     * 打开系统的音乐播放器
     */
    public static void openMusicPlayer(Context context) {

        Intent intent_music = new Intent(Intent.ACTION_MAIN);
        intent_music.setAction(Intent.ACTION_DEFAULT);
        intent_music.setType("audio/*");
        intent_music.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent_music);

    }

    /**
     * 打开系统的视频播放器
     */
    public static void openVideoPlayer(Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType("video/*");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * add the system volume
     *
     * @param am
     */
    public static void volumeAdd(AudioManager am) {
        am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
    }

    /**
     * decrease the system volume
     *
     * @param am
     */
    public static void volumeDecrease(AudioManager am) {
        am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
    }

    /**
     * set the system volume size
     *
     * @param am
     * @param volSize
     */
    public static void setSystemVol(AudioManager am, int volSize) {
        am.setStreamVolume(AudioManager.STREAM_MUSIC, volSize, AudioManager.FLAG_SHOW_UI);
    }

    /**
     * get system current package name
     *
     * @param context
     * @return
     */
    public static String getcurrentPackageName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasts = am.getRunningTasks(1);
        String currentPackageName = "";
        if (tasts.size() > 0) {
            RunningTaskInfo rti = tasts.get(0);
            currentPackageName = rti.topActivity.getPackageName();
        }
        return currentPackageName;
    }
//判断系统中是否存在某个Activity?它是否已经启动?
protected void startAndExit() {  
    logi(TAG, "---startAndExit---");  
    Intent intent = new Intent(this, ActivityMain.class);  
    ComponentName cmpName = intent.resolveActivity(getPackageManager());  
    boolean bIsExist = false;  
    if (cmpName != null) { // 说明系统中存在这个activity  
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);  
        List<RunningTaskInfo> taskInfoList = am.getRunningTasks(10);  
        logi(TAG, "---startAndExit---taskInfoList.size:" + taskInfoList.size());  
        for (RunningTaskInfo taskInfo : taskInfoList) {  
            LogUtils.logi(TAG, "---startAndExit---taskInfo:"  
                    + taskInfo.baseActivity);  
            if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了  
                bIsExist = true;  
                break;  
            }  
        }  
    }  
    logi(TAG, "---onStartAndExit---bIsExist:" + bIsExist);  
    if (bIsExist) {  
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
        intent.putExtra("isExit", (Boolean) true); //让它自行关闭  
        this.startActivity(intent);  
    }  
} 

//如果某个Activity的运行模式被设置为singleTask或singleInstance,再次启动它,会触发它的onNewIntent方法。
    @Override  
    protected void onNewIntent(Intent intent) {  
        logi(TAG, "---onNewIntent---");  
        super.onNewIntent(intent);  
        if (intent.getBooleanExtra("isExit", false)) {  
            finish(); // 自行关闭  
        }  
    }  

    /**
     * 得到当前显示界面Activity的名字
     *
     * @param context
     * @return
     */
    public static String getCurrentActivityName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo> tasts = am.getRunningTasks(1);
        String currentActivityName = "";
        if (tasts.size() > 0) {
            RunningTaskInfo rti = tasts.get(0);
            currentActivityName = rti.topActivity.getClassName();
        }
        return currentActivityName;
    }

    /**
     * 根据包名和activity名称进入该activity
     *
     * @param context
     * @param packageName
     * @param activityName
     */
    public static boolean startActivityByPackageName(Context context, String packageName, String activityName) {
        if (!SystemService.isExistApp(context, packageName)) {
            Toast.makeText(context, "该应用已被卸载", Toast.LENGTH_LONG).show();
            return false;
        }
        Intent intent = new Intent();
        intent.setClassName(packageName, activityName);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
        return true;
    }

    /**
     * 判断该app是否存在
     *
     * @param context
     * @param pkg
     * @return true  存在   false  不存在
     */
    public static boolean isExistApp(Context context, String pkg) {
        PackageManager pckMan = context.getPackageManager();
        List<PackageInfo> packs = pckMan.getInstalledPackages(0);
        int count = packs.size();
        for (int i = 0; i < count; i++) {
            PackageInfo p = packs.get(i);
            if (p.versionName == null) {
                continue;
            }
            ApplicationInfo appInfo = p.applicationInfo;
            if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                // 系统app
                // name = p.applicationInfo.loadLabel(pckMan).toString();
                String packageName = p.packageName;
                if (packageName.equals(pkg))
                    return true;
            } else {
                // 不是系统app
                String packageName = p.packageName;
                if (packageName.equals(pkg))
                    return true;
            }
        }
        return false;
    }

    /**
     * ActivityManager类可以获取运行信息,如下:
     * <p/>
     * 1.getRecentTasks() 最近开的task,HOME键长按会看到这个
     * <p/>
     * 2.getRunningAppProcesses() 运行中的作为app容器的process
     * <p/>
     * 3.getRunningServices()运行中的后台服务
     * <p/>
     * 4.getRunningTasks() 运行中的任务
     */
    public static final String APP_ICON = "last_app_icon";
    public static final String APP_LABEL = "last_app_label";

    /**
     * 获取最近运行的程序列表(近期任务第一个),长按home键所示效果:
     *
     * @param context
     */
    public static Map<String, Object> getTaskList(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager pm = context.getPackageManager();
        try {
            List<RecentTaskInfo> list = am.getRecentTasks(64, 0);
            for (RecentTaskInfo rti : list) {
                Intent intent = rti.baseIntent;
                ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
                if (resolveInfo != null) {
                    Map<String, Object> RecentTask = new HashMap<String, Object>();
                    Drawable d = resolveInfo.loadIcon(pm);
                    String app = String.valueOf(resolveInfo.loadLabel(pm));
                    // String packageName = resolveInfo.resolvePackageName;
                    // System.out.println(packageName);
                    RecentTask.put(APP_ICON, d);
                    RecentTask.put(APP_LABEL, app);
                    System.out.println("app = " + app);
                    return RecentTask;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 获取正在运行的程序信息  
     */
    public static void getRunningProcess(final Context context) {
        PackageManager pm = context.getPackageManager();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ApplicationInfo> infos = pm.getInstalledApplications(0);
        List<RunningAppProcessInfo> runnings = am.getRunningAppProcesses();
        for (ApplicationInfo info : infos) {
            String appName = info.loadLabel(pm) + "";
            // String s = info.labelRes+ "";
            String packageName = info.packageName;
            String className = info.className;
            String name = info.name;

            for (RunningAppProcessInfo running : runnings) {
                if (running.processName.equals(packageName)) {
                    System.out.println("-appName-" + appName + "-packageName-" + packageName + "-className-" + className + "-name-" + name);// 正在运行的应用程序名
                }
            }
        }
    }

    public static List<String> getAllInstalledPackages(Context context) {
        List<String> allApps = new ArrayList<String>();
        PackageManager pckMan = context.getPackageManager();
        List<PackageInfo> packs = pckMan.getInstalledPackages(0);
        int count = packs.size();
        for (int i = 0; i < count; i++) {
            PackageInfo p = packs.get(i);
            if (p.versionName == null) {
                continue;
            }
            // 判断该软件包是否在/data/app目录下
            ApplicationInfo appInfo = p.applicationInfo;
            if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                // 系统程序
                // name = p.applicationInfo.loadLabel(pckMan).toString();
            } else {
                // 不是系统程序
                // name = p.applicationInfo.loadLabel(pckMan).toString();
                String packageName = p.packageName;
                allApps.add(packageName);
            }
        }
        return allApps;
    }

    /**
     * 判断程序是否是栈顶程序
     */
    public static boolean isTopActivity(String packageName, Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        return (currentPackageName != null && currentPackageName.equals(packageName));
    }

    /**
     * 获取当前应用的版本号:
     */
    private String getVersionName(Context context, String packageName) throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名,0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(packageName, 0);
        String version = packInfo.versionName;
        return version;
    }

    /**
     * 获取当前系统版本号
     */
    public static String getSystemVersion() {
        String systemVersion = android.os.Build.MODEL + "," + android.os.Build.VERSION.SDK + "," + android.os.Build.VERSION.RELEASE;
        return systemVersion;// ca03, 16, 4.1.1
    }
}

电源操作:

/**
 * <uses-permission android:name="android.permission.WRITE_SETTINGS" />
 * <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 * <uses-permission android:name="android.permission.DEVICE_POWER" />
 * <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
 * <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 */
public class BrightnessTools {
    /*
     * Android的屏幕亮度好像在2.1+的时候提供了自动调节的功能, 所以,如果当开启自动调节功能的时候, 我们进行调节好像是没有一点作用的,
     * 这点让我很是无语,结果只有进行判断,看是否开启了屏幕亮度的自动调节功能。
     */

    /**
     * 判断是否开启了自动亮度调节
     */
    public static boolean isAutoBrightness(ContentResolver contentResolver) {
        boolean automicBrightness = false;
        try {
            automicBrightness = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        return automicBrightness;
    }

    // 然后就是要觉得当前的亮度了,这个就比较纠结了:

    /**
     * 获取屏幕的亮度
     */

    public static int getScreenBrightness(ContentResolver contentResolver) {
        int nowBrightnessValue = 0;
        try {
            nowBrightnessValue = android.provider.Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nowBrightnessValue;
    }

    // 那如何修改屏幕的亮度呢?

    /**
     * 设置亮度
     */
    public static void setBrightness(Activity activity, int brightness) {
        // Settings.System.putInt(activity.getContentResolver(),
        // Settings.System.SCREEN_BRIGHTNESS_MODE,
        // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        activity.getWindow().setAttributes(lp);
    }

    // 那么,能设置了,但是为什么还是会出现,设置了,没反映呢?
    // 嘿嘿,那是因为,开启了自动调节功能了,那如何关闭呢?这才是最重要的:

    /**
     * 停止自动亮度调节
     */
    public static void stopAutoBrightness(Activity activity) {
        Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
    }

    // 能开启,那自然应该能关闭了哟哟,那怎么关闭呢?很简单的:

    /**
     * * 开启亮度自动调节 *
     *
     * @param activity
     */
    public static void startAutoBrightness(Activity activity) {
        Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
    }

    // 至此,应该说操作亮度的差不多都有了,结束!
    // 哎,本来认为是应该结束了,但是悲剧得是,既然像刚才那样设置的话,只能在当前的activity中有作用,一段退出的时候,会发现毫无作用,悲剧,原来是忘记了保存了。汗!

    /**
     * 保存亮度设置状态
     */
    public static void saveBrightness(ContentResolver resolver, int brightness) {
        Uri uri = android.provider.Settings.System.getUriFor("screen_brightness");
        android.provider.Settings.System.putInt(resolver, "screen_brightness", brightness);
        // resolver.registerContentObserver(uri, true, myContentObserver);
        resolver.notifyChange(uri, null);
    }


    /**
     * 获得当前屏幕亮度的模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    private int getScreenMode(Context ctx) {
        int screenMode = 0;
        try {
            screenMode = Settings.System.getInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        } catch (Exception localException) {

        }
        return screenMode;
    }

    /**
     * 设置当前屏幕亮度的模式
     *
     * @param ctx
     * @param paramInt SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     *                 SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    public static void setScreenMode(Context ctx, int paramInt) {
        try {
            Settings.System.putInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, paramInt);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    /**
     * 获得当前屏幕亮度值 0--255
     */
    private int getScreenBrightness(Context ctx) {
        int screenBrightness = 255;
        try {
            screenBrightness = Settings.System.getInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception localException) {

        }
        return screenBrightness;
    }

    /**
     * 设置当前屏幕亮度值 0--255
     */
    private void saveScreenBrightness(int paramInt, Context ctx) {
        try {
            Settings.System.putInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, paramInt);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    /**
     * 保存当前的屏幕亮度值,并使之生效
     */
    private void setScreenBrightness(int paramInt, Activity ctx) {
        Window localWindow = ctx.getWindow();
        WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
        float f = paramInt / 255.0F;
        localLayoutParams.screenBrightness = f;
        localWindow.setAttributes(localLayoutParams);
    }


//  protected void onCreate( ) {
//      boolean isAuto = BrightnessTools.isAutoBrightness(getContentResolver());
//      System.out.println("是否自动调节屏幕亮度  = " + isAuto);
//  }
//
//  public void setRight() {
        BrightnessTools.setBrightness(this, 50);
//      BrightnessTools.saveBrightness(getContentResolver(), 50);
//  }
//
//  public void currBright( ) {
//      int currBright = BrightnessTools.getScreenBrightness(this);
//      System.out.println("当前屏幕亮度:" + currBright);
//  }
}

APP相关:

public class AppUtil {

    public static void installApk(Context context, File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static void uninstallApk(Context context, String packageName) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        Uri packageURI = Uri.parse("package:" + packageName);
        intent.setData(packageURI);
        context.startActivity(intent);
    }

    public static boolean isServiceRunning(Context ctx, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningServiceInfo> servicesList = activityManager.getRunningServices(Integer.MAX_VALUE);
        Iterator<RunningServiceInfo> l = servicesList.iterator();
        while (l.hasNext()) {
            RunningServiceInfo si = (RunningServiceInfo) l.next();
            if (className.equals(si.service.getClassName())) {
                isRunning = true;
            }
        }
        return isRunning;
    }

    public static boolean stopRunningService(Context ctx, String className) {
        Intent intent_service = null;
        boolean ret = false;
        try {
            intent_service = new Intent(ctx, Class.forName(className));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (intent_service != null) {
            ret = ctx.stopService(intent_service);
        }
        return ret;
    }

    public static int getNumCores() {
        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    // Check if filename is "cpu", followed by “a” single digit
                    // number
                    if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                        return true;
                    }
                    return false;
                }

            });
            // Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            // Default to return 1 core
            return 1;
        }
    }

    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public static boolean isGpsEnabled(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public static boolean isWifiEnabled(Context context) {
        ConnectivityManager mgrConn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager mgrTel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return ((mgrConn.getActiveNetworkInfo() != null
                && mgrConn.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED)
                || mgrTel.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
    }

    public static boolean isWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    public static boolean is3G(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            return true;
        }
        return false;
    }


}

屏幕DisplayUtil显示相关:

public class DisplayUtil {
    /**
     * dip转px
     *
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * px转dip
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取屏幕宽度和高度,单位为px
     *
     * @param context
     * @return
     */
    public static Point getScreenMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);
    }

    /**
     * 获取屏幕长宽比
     *
     * @param context
     * @return
     */
    public static float getScreenRate(Context context) {
        Point P = getScreenMetrics(context);
        float H = P.y;
        float W = P.x;
        return (H / W);
    }

    /**
     * 把dip单位转成px单位
     *
     * @param context
     *            context对象
     * @param dip
     *            dip数值
     * @return
     * @使用说明 使用dp设计, 在代码里转化为不同分辨率下的px值, 显示效果一样, 占用像素值不一样
     */
    public static int formatDipToPx(Context context, int dip) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return (int) Math.ceil(dip * dm.density);
    }

    /**
     * 把px单位转成dip单位
     *
     * @param context
     *            context对象
     * @param px
     *            px数值
     * @return
     * @使用说明 使用px设计, 在代码里转化为不同分辨率下的dp值, 显示效果长短不一样, 占用像素值一样
     */
    public static int formatPxToDip(Context context, int px) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return (int) Math.ceil(((px * 160) / dm.densityDpi));
    }

      /**
     * 判断屏幕分辨率
     * @param activity
     * @return
     */
    public static int Dpi(Activity activity) {
        SharedPreferences sh = activity.getSharedPreferences("dpi", 0);
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenHeight = dm.heightPixels;
        int screenWidth = dm.widthPixels;
        // 判断高分辨率低分辨率
        if (sh.getInt("dpi_type", -1) == -1) {
            if (screenHeight >= 960 && screenWidth >= 720) {
                sh.edit().putInt("dpi_type", 1).commit();
                Log.i("dpi_type", "超高分辨率");
            } else if (screenHeight >= 640 && screenWidth >= 480) {
                sh.edit().putInt("dpi_type", 2).commit();
                Log.i("dpi_type", "高分辨率");
            } else if (screenHeight >= 470 && screenWidth >= 320) {
                sh.edit().putInt("dpi_type", 3).commit();
                Log.i("dpi_type", "中分辨率");
            } else if (screenHeight >= 426 && screenWidth >= 320) {
                sh.edit().putInt("dpi_type", 4).commit();
                Log.i("dpi_type", "低分辨率");
            }  else if (screenHeight >= 426 && screenWidth >= 320) {
                sh.edit().putInt("dpi_type", 4).commit();
                Log.i("dpi_type", "低分辨率");
            }
        }
        return sh.getInt("dpi_type", -1);
    }


    /**
     * 获取状态栏的高度(不能获取到状态栏的高度)
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = context.getResources().getDimensionPixelSize(i5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 以下为正确获取
        // Class<?> c = null;
        // Object obj = null;
        // Field field = null;
        // int x = 0, sbar = 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());
        // sbar = getResources().getDimensionPixelSize(x);
        // } catch(Exception e1) {
        // loge("get status bar height fail");
        // e1.printStackTrace();
        // }

        return statusHeight;
    }

    /**
     * 用于获取状态栏的高度。
     *
     * @return 返回状态栏高度的像素值。
     */
    public static int getStatusBarHeight(Context context) {
        // 状态栏高度
        int statusBarHeight = 0;
        if (statusBarHeight == 0) {
            try {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object o = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = (Integer) field.get(o);
                statusBarHeight = context.getResources().getDimensionPixelSize(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusBarHeight;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值