Android开发之获取常用android设备参数信息
16lz
2021-01-24
如下图:
查看工具类:下载apk的方法缺少xutils库,可以自己添加xutils库
package com.mchsdk.paysdk.utils;import android.Manifest;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.graphics.Point;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.net.Uri;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.os.Build;import android.os.Environment;import android.provider.Settings;import android.support.v4.app.ActivityCompat;import android.support.v4.content.FileProvider;import android.telephony.TelephonyManager;import android.util.DisplayMetrics;import android.util.Log;import android.view.Display;import android.view.View;import android.widget.TextView;import android.widget.Toast;import com.lidroid.xutils.HttpUtils;import com.lidroid.xutils.exception.HttpException;import com.lidroid.xutils.http.ResponseInfo;import com.lidroid.xutils.http.callback.RequestCallBack;import java.io.File;import java.lang.reflect.Method;import java.math.BigDecimal;import java.net.Inet4Address;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;import java.util.Locale;import java.util.UUID;/** * @author xiayiye5 * 2020年6月3日11:24:04 * Android 开发用到的工具类 */public class YhshUtils { //静态内部内实现单例设计模式 private YhshUtils() { } public static YhshUtils getInstance() { return YhshSingle.CREATE; } private static class YhshSingle { private static final YhshUtils CREATE = new YhshUtils(); } /** * 判断是否安装某APP * * @param context 上下文 * @param packageName apk包名 * @return 返回结果 */ public boolean isInstallApk(Context context, String packageName) { if (TextUtils.isEmpty(packageName)) { return false; } try { ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES); return info != null; } catch (PackageManager.NameNotFoundException e) { return false; } } /** * 下载apk的方法 * * @param activity 上下文 * @param downloadTextView 显示下载的TextView */ private void downloadApk(final Activity activity, final View downloadTextView) { //将按钮设置成正在下载中 ((TextView) downloadTextView).setText("正在下载中……"); HttpUtils httpUtils = new HttpUtils(); // 判断sd卡是否挂载 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { final String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gfan.apk"; //获取下载apk的地址 String apkDownUrl = "http://cdn1.down.apk.gfan.net.cn/Pfiles/2020/05/21/gfanxapp_20200521194529_45df3390-b57e-4c16-b0fb-fb0ebcac1a80.apk"; SharedPreferences downApkFile = activity.getSharedPreferences("DownApkFile", Context.MODE_PRIVATE); apkDownUrl = downApkFile.getString("downUrl", apkDownUrl); MCLog.e("打印apk下载url", apkDownUrl); httpUtils.download(apkDownUrl, filePath, new RequestCallBack() { // 下载成功的时候调用 @Override public void onSuccess(ResponseInfo arg0) { CommonLoading.getInstance().closeDialog(); Toast.makeText(activity.getApplicationContext(), "下载成功", Toast.LENGTH_SHORT).show(); // 安装最新版本 install(filePath, activity); } // 下载失败的时候调用 @Override public void onFailure(HttpException arg0, String arg1) { Log.e("下载失败", "失败了:" + arg0.getLocalizedMessage()); Toast.makeText(activity.getApplicationContext(), "下载失败了," + arg0.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } @Override public void onLoading(long total, long current, boolean isUploading) { super.onLoading(total, current, isUploading); int progress = (int) (((float) current / (float) total) * 100); Log.e("下载进度", current + "/" + total + ":进度" + progress + "%"); //将按钮设置成正在下载中// ((TextView) downloadTextView).setText(new StringBuilder("正在下载中……").append(progress).append("%")); } }); } } /** * 安装最新版本 * * @param filePath 安装包的路径 */ private void install(String filePath, Activity activity) { Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); Uri fileUri; File file = new File(filePath); if (Build.VERSION.SDK_INT >= 24) { fileUri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".provider", file); } else { //android70.以下手机 fileUri = Uri.fromFile(file); } //Android7.0以上必须添加如下代码 activity.grantUriPermission(activity.getPackageName(), fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(fileUri, "application/vnd.android.package-archive"); // 当当前的activity退出的时候,会调用之前activity的onActivityResult方法 activity.startActivityForResult(intent, 0); } //先定义 private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}; public void checkPermission(Activity activity, View downloadTextView) { try { //检测是否有写的权限 int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); } else { //下载安装 downloadApk(activity, downloadTextView); } } catch (Exception e) { e.printStackTrace(); } } /** * @param activity 当前activity * @return 1:竖屏 2 横屏 */ public int screenOrientation(Activity activity) { //获取设置的配置信息 return activity.getResources().getConfiguration().orientation; } /** * 保存token * * @param loginToken token * @param activity activity页面 */ public void setLoginToken(Context activity, String loginToken) { SharedPreferences tokenFile = activity.getSharedPreferences("token_file", Context.MODE_PRIVATE); tokenFile.edit().putString("token_key", loginToken).apply(); } /** * 取出登录的token * * @return 返回登录的token */ public String getLoginToken(Activity activity) { SharedPreferences tokenFile = activity.getSharedPreferences("token_file", Context.MODE_PRIVATE); String tokenValue = tokenFile.getString("token_key", ""); MCLog.e("打印保存的token", tokenValue + "="); return tokenValue; } /** * 获取手机参数为了调用数据统计接口 */ public PackageInfo getPhoneParam(Activity activity) { //获取包管理器 PackageManager pm = activity.getPackageManager(); //获取包信息 try { PackageInfo packageInfo = pm.getPackageInfo(activity.getPackageName(), 0); //返回版本号 String versionName = packageInfo.versionName; int versionCode = packageInfo.versionCode; return packageInfo; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * 获取手机IMSI */ public String getIMSI(Activity context) { try { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); //获取IMSI号 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { context.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1008); } } String imsi = telephonyManager.getSubscriberId(); if (null == imsi) { imsi = ""; } return imsi; } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 获取当前手机系统语言。 * * @return 返回当前系统语言。例如:当前设置的是“中文-中国”,则返回“zh-CN” */ public String getSystemLanguage() { return Locale.getDefault().getLanguage(); } /** * 获取当前系统上的语言列表(Locale列表) * * @return 语言列表 */ public Locale[] getSystemLanguageList() { return Locale.getAvailableLocales(); } /** * 获取当前手机系统版本号 * * @return 系统版本号 */ public String getSystemVersion() { return android.os.Build.VERSION.RELEASE; } /** * 获取手机型号 * * @return 手机型号 */ public String getSystemModel() { return android.os.Build.MODEL; } /** * 获取手机厂商 * * @return 手机厂商 */ public String getDeviceBrand() { return android.os.Build.BRAND; } /** * 获取IP地址 * * @param context 上下文 * @return 返回值 */ public String getIpAddress(Context context) { NetworkInfo info = ((ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 3/4g网络 if (info.getType() == ConnectivityManager.TYPE_MOBILE) { try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } } else if (info.getType() == ConnectivityManager.TYPE_WIFI) { // wifi网络 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); return toIpAddress(wifiInfo.getIpAddress()); } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) { // 有限网络 return getLocalIp(); } } return null; } /** * 将int类型的IP地址转为String类型的IP * * @param ip IP地址 * @return 返回IP数据 */ private static String toIpAddress(int ip) { return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF); } /** * 获取有限网IP * * @return 返回 */ private String getLocalIp() { try { for (Enumeration en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return "0.0.0.0"; } /** * 获取屏幕尺寸 * * @param context 当前activity * @return 返回尺寸 */ public double getScreenInch(Activity context) { double mInch = 0; try { int realWidth = 0, realHeight = 0; Display display = context.getWindowManager().getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); if (android.os.Build.VERSION.SDK_INT >= 17) { Point size = new Point(); display.getRealSize(size); realWidth = size.x; realHeight = size.y; } else if (android.os.Build.VERSION.SDK_INT < 17 && android.os.Build.VERSION.SDK_INT >= 14) { Method mGetRawH = Display.class.getMethod("getRawHeight"); Method mGetRawW = Display.class.getMethod("getRawWidth"); realWidth = (Integer) mGetRawW.invoke(display); realHeight = (Integer) mGetRawH.invoke(display); } else { realWidth = metrics.widthPixels; realHeight = metrics.heightPixels; } mInch = formatDouble(Math.sqrt((realWidth / metrics.xdpi) * (realWidth / metrics.xdpi) + (realHeight / metrics.ydpi) * (realHeight / metrics.ydpi)), 1); } catch (Exception e) { e.printStackTrace(); } return mInch; } /** * Double类型保留指定位数的小数,返回double类型(四舍五入) * newScale 为指定的位数 */ private double formatDouble(double d, int newScale) { BigDecimal bd = new BigDecimal(d); return bd.setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 获取android的唯一标识 * * @param context 上下文 * @return 返回androidId */ public String getAndroidId(Context context) { final String uuid = UUID.randomUUID().toString(); String androidId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); if (TextUtils.isEmpty(androidId)) { return uuid; } else { return androidId; } }}
更多相关文章
- Android-中常用方法集锦
- 从android模拟器中提取文件系统
- android 双击事件的实现
- Android及系统架构目录结构介绍
- android开发工具合集(Zipalign)
- android wifi 无线调试
- Android(安卓)apk的安装、卸载
- 解决Android(安卓)Toobar与状态栏重叠
- Android清除所有应用的缓存(包括系统应用)的两种实现方法