如下图:

查看工具类:下载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<File>() {// 下载成功的时候调用@Overridepublic void onSuccess(ResponseInfo<File> arg0) {CommonLoading.getInstance().closeDialog();Toast.makeText(activity.getApplicationContext(), "下载成功", Toast.LENGTH_SHORT).show();// 安装最新版本install(filePath, activity);}// 下载失败的时候调用@Overridepublic void onFailure(HttpException arg0, String arg1) {Log.e("下载失败", "失败了:" + arg0.getLocalizedMessage());Toast.makeText(activity.getApplicationContext(), "下载失败了," + arg0.getLocalizedMessage(), Toast.LENGTH_LONG).show();}@Overridepublic 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<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {NetworkInterface intf = en.nextElement();for (Enumeration<InetAddress> 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<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {NetworkInterface intf = en.nextElement();for (Enumeration<InetAddress> 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设备参数信息相关推荐

  1. android 获取年月日时分秒,Android开发中 获取当前Android的年月日时分秒的时间

    Android的文件有建议用Time代替Calendar.用Time对CPU的负荷会较小.在写Widget时特别重要. Time t=new Time(); // or Time t=new Time ...

  2. android获取版本号报错,Android开发:获取安卓App版本号的方法步骤

    在Android开发过程中,想要开发一个完整功能的App,各个地方的内容都要涉及到,比如获取App的系统版本号就是必须要有的功能.Android的App版本号相关内容比iOS的App版本号内容要多,而 ...

  3. Android移动开发-Android开发日历时常用的农历和公历换算代码工具类

    下面是与Android开发日历时常用的有关农历计算.公历计算.二十四气节相关的代码工具类的代码. Constant.java逻辑代码如下: package com.fukaimei.calendar. ...

  4. android获取安卓版本,Android开发:获取安卓App版本号的方法步骤

    今天国庆节,在这举国欢庆的日子里,发一篇博文留念一下这个特殊的日子,国庆依然奋战在工作一线. 在Android开发过程中,想要开发一个完整功能的App,各个地方的内容都要涉及到,比如获取App的系统版 ...

  5. Android开发之获取相册照片和获取拍照照片

    在Android的开发过程中,我们可能会读取手机里面的照片或者通过相机拍摄获取照片,这是两种常用的获取图片的方式,在做项目过程中也会经常遇到,下面来介绍一下这两种获取方式.. 1.从本地相册获取照片: ...

  6. Android开发之获取通话记录

    上一篇讲的是Android开发之获取手机通讯录,这一篇博客也将针对手机联系人这一块进行开发.下面是获取手机通话记录的详细步骤: 1. 首先,我们需要新建一个类CallLogInfo,用于通话记录的数据 ...

  7. android开发:获取键盘的高度(实测真实有效)

    android开发:获取键盘的高度(实测真实有效) 由于最近在做即时通讯,做类似于微信的点击键盘消失,弹出表情页面(表情页面的高度和键盘的高度一致),于是在网上看了好多android测键盘高度的代码, ...

  8. Android开发——后台获取用户点击位置坐标(可获取用户支付宝密码)

    1. getevent命令 我们首先是根据adb shell getevent命令获取到被点击位置的信息. 这里要说明的是,不同的手机手机获得的点击输出是不一样的.以我的真机为例,输出如下 本文原创, ...

  9. android studio开发工具介绍,Android应用开发之Android开发工具介绍、Android Studio配置...

    本文将带你了解Android应用开发之Android开发工具介绍.Android Studio配置,希望本文对大家学Android有所帮助. 2.1   Android Studio配置 2.1.1 ...

最新文章

  1. 四种Java线程池用法解析
  2. WARNING:tensorflow:Layer gru will not use cuDNN kernels since it doesn‘t meet the criteria. It will
  3. python3安装venv虚拟环境
  4. 【CodeForces - 1047B 】Cover Points (数学,构造,思维)
  5. mysql innodb文件_MySQL的InnoDB文件介绍
  6. linux关闭网卡休眠_CentOS_Linux常用实用指令整理三:高级指令
  7. 解决 sublime text3 运行python文件无法input的问题
  8. 推箱子游戏的java设计思路_用JAVA实现一个推箱子游戏
  9. 计算机课ppt插入图片,ppt2010官方基础教程:插入照片-powerpoint技巧-电脑技巧收藏家...
  10. 校验子解码问题(Syndrome Decoding)
  11. A6 词根:-vict- = -vinc-;单词:evince、vincible
  12. 关闭Win 11自动更新工具
  13. 微软Surface Pro 3:优秀由内而外
  14. 首席新媒体运营商学院黎想:裂变活动要避免40个坑!
  15. python拍七游戏代码_拍七数字游戏 - Johannes-Jensen - 博客园
  16. 区块链技术改进身份和访问管理(IAM)的10种用例
  17. 计算机应用基ata,《计算机应用基》知识宝典.doc
  18. pygame 实现键盘鼠标映射
  19. 苹果支付php服务端处理,以及双重验证,收据,状态码
  20. 码分多址cdma通信_码分多址(CDMA)| 计算机网络

热门文章

  1. 一位嵌入式工程师,硬核单片机编程思想!
  2. VHDL简易电子琴的设计
  3. JESD204B的AXI4-Lite时序分析(对比SRIO的AXI4-Lite时序分析)
  4. linux 采集cpu 内存,Linux环境获取(cpu、内存、网卡流量等)系统性能数据
  5. php tostring(),【php】“__toString()”方法使用,php__tostring
  6. 20220202--CTF刷题MISC方向--第5题--反编译
  7. 均值定理最大值最小值公式_如何理解中值定理?三大微分中值定理的几何意义及其证明介绍。...
  8. navicat创建计算列_Tableau Part 9 计算字段amp;粒度聚合比率amp;表计算
  9. mac上java文件如何编译_如何在Mac上用Java编译和运行程序?
  10. 【Leetcode_easy】657. Robot Return to Origin