获取手机的基本信息和手机型号

本文介绍了一个用于获取手机基本信息的工具类,包括MAC地址、设备唯一标识、渠道号、设备ID等内容,并实现了统计分析功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取手机信息的工具类

package com.sanbanhui.helper.utils;

import java.util.UUID;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import static android.content.Context.TELEPHONY_SERVICE;

public class DeviceUtil {
    /**
     * 获取mac地址
     * 
     * @param context
     * @return
     */
    public static String getMac(Context context) {
        if (context == null) {
            return "";
        }

        String mac = null;
        try {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            if (null != info) {
                mac = info.getMacAddress();
            }
        } catch (Exception e) {}

        return null != mac ? Base64.encodeToString(mac.getBytes(), Base64.DEFAULT) : "";
    }

    /**
     * 获取设备唯一标识
     * 
     * @param context
     * @return
     */
    public synchronized static String getUUID(Context context) {
        if (context == null) {
            return "";
        }

        final TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = ""
                + android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
        UUID uuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        return uuid.toString();
    }

    /**
     * 获取设备ID,友盟统计分析使用
     * 
     * @param context
     * @return
     */
    public static String getDevId(Context context) {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        final String tmDevice = tm.getDeviceId();
        return tmDevice;
    }

    /**
     * 渠道号
     * 
     * @return
     */
    public static String getChannel(Context context) {
        String metaData = null;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            if (info != null && info.metaData != null) {
                metaData = info.metaData.getString("UMENG_CHANNEL");
            } else {
                metaData = "unknow";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return metaData;
    }

    /**
     * Return true if sdcard is available.
     * 
     * @return
     */
    public static boolean isSdCardExist() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * get application version name defined in manifest
     * 
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageManager pm = context.getPackageManager();
        String verName = "";
        try {
            PackageInfo pInfo = pm.getPackageInfo(context.getPackageName(), 0);
            verName = pInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    /**
     * get application version code defined in manifest
     * 
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        PackageManager pm = context.getPackageManager();
        int verCode = 0;
        try {
            PackageInfo pInfo = pm.getPackageInfo(context.getPackageName(), 0);
            verCode = pInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return verCode;
    }

    /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static boolean isConnect(Context context) {
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理) 
        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) {
            e.printStackTrace();
        }
        return false;
    }

    /*
     * public static void addShortCut(Context context, String name, int ic) { context = context.getApplicationContext();
     * Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); // 是否允许重复创建
     * shortcut.putExtra("duplicate", false);
     * 
     * // 设置名称 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
     * 
     * //设置桌面快捷方式的图标 Parcelable icon = Intent.ShortcutIconResource.fromContext(context, ic);
     * shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
     * 
     * //点击快捷方式的操作 Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClass(context, LoginActivity.class);
     * 
     * // 设置启动程序 shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
     * 
     * //广播通知桌面去创建 context.sendBroadcast(shortcut); }
     */

//  public static void addShortCut(Context context) {
//      Intent addShortCut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//      // 不能重复创建快捷方式
//      addShortCut.putExtra("duplicate", false);
//      String title = context.getString(R.string.app_name);// 名称
//      Parcelable icon = Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_launcher);// 图标
//      // 点击快捷方式后操作Intent,快捷方式建立后,再次启动该程序
//      Intent intent = new Intent(context, LoginActivity.class);
//      // 设置快捷方式的标题
//      addShortCut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
//      // 设置快捷方式的图标
//      addShortCut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//      // 设置快捷方式对应的Intent
//      addShortCut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
//      // 发送广播添加快捷方式
//      context.sendBroadcast(addShortCut);
//  }

    public static void showInputMethod(Context context, View forceView) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(forceView, InputMethodManager.SHOW_FORCED);
    }

    public static void hideInputMethod(Context context, View forceView) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(forceView.getWindowToken(), 0); //强制隐藏键盘  
    }

    public static void hideInputMethod(Context context, IBinder windowToken) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//      if(imm.isActive())toggleInputMethod(context);
        imm.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS); //强制隐藏键盘  
    }

    public static void toggleInputMethod(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 手机型号
     *
     * @param context
     * @return
     */

    public static String getModelInfo(Context context) {
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        return android.os.Build.MODEL;
    }


    /**
     * 手机品牌
     *
     * @param context
     * @return
     */

    public static String getBrandInfo(Context context) {
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        return android.os.Build.BRAND;
    }

    /**
     * 运营商
     *
     * @param context
     * @return
     */

    public static String getOperatorInfo(Context context) {
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        String ProvidersName = "N/A";
        try{
            String IMSI = mTm.getSubscriberId();
            // IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。
            System.out.println(IMSI);
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
                ProvidersName = "中国移动";
            } else if (IMSI.startsWith("46001")) {
                ProvidersName = "中国联通";
            } else if (IMSI.startsWith("46003")) {
                ProvidersName = "中国电信";
            }
        } catch (Exception e){
            //e.printStackTrace();
        }
        return ProvidersName;
    }

    /**
     * 分辨率
     *
     * @param context
     * @return
     */

    public static String getWHInfo(Context context) {
        return Utils.getWindowWidth(context) + "x" + Utils.getWindowHeight(context);
    }


    /**
     * 操作系统
     *
     * @param context
     * @return
     */

    public static String getOSInfo(Context context) {
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        return Build.VERSION.RELEASE;
    }
}

创建提交信息的API

 //统计分析
         public static final String getStat = ipShao + "/statisticsservice/addStatistics";

创建服务类

 package com.sanbanhui.helper.service;

 import android.app.Service;
 import android.content.Intent;
 import android.os.IBinder;

 import com.sanbanhui.helper.interactor.StatisticsInfoInteractor;
 import com.sanbanhui.helper.interactorimpl.StatisticsInfoInteractorImpl;

 public class StatisticsDataService extends Service implements StatisticsInfoInteractor.OnLoadDataFinishedListener {

     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }

     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
         loadData();
         return super.onStartCommand(intent, flags, startId);
     }

     private void loadData() {
         StatisticsInfoInteractorImpl statisticsInfoInteractor = new StatisticsInfoInteractorImpl();
         statisticsInfoInteractor.execute(this);
     }

     @Override
     public void onDestroy() {
         super.onDestroy();
     }

     @Override
     public void onSuccess() {
         stopSelf();
     }

     @Override
     public void onFailure(String message) {
         stopSelf();
     }
 }

创建网络请求post请求

package com.sanbanhui.helper.interactorimpl;

 import android.text.TextUtils;

 import com.sanbanhui.helper.AndroidApplication;
 import com.sanbanhui.helper.R;
 import com.sanbanhui.helper.interactor.StatisticsInfoInteractor;
 import com.sanbanhui.helper.manage.AccountManage;
 import com.sanbanhui.helper.manage.TokenManage;
 import com.sanbanhui.helper.net.utils.RequestUtils;
 import com.sanbanhui.helper.net.utils.ServiceResult;
 import com.sanbanhui.helper.utils.Constants;
 import com.sanbanhui.helper.utils.DeviceUtil;
 import com.sanbanhui.helper.utils.LogUtils;
 import com.sanbanhui.helper.utils.ResourceUtils;
 import com.sanbanhui.helper.utils.Utils;

 import java.util.HashMap;
 import java.util.Map;

 /**
  * Created by lixiaoming on 2016/5/17.
  */
 public class StatisticsInfoInteractorImpl implements StatisticsInfoInteractor {

     @Override
     public void execute(OnLoadDataFinishedListener listener) {
         String time = String.valueOf(System.currentTimeMillis());
         String name = Utils.getParams(time);

         Map<String, String> params = new HashMap<>();
         params.put("_time", time);
         params.put("token", TokenManage.getInstance().getToken());

         params.put("deviceBrand", DeviceUtil.getBrandInfo(AndroidApplication.getInstance()));
         params.put("deviceModle", DeviceUtil.getModelInfo(AndroidApplication.getInstance()));
         params.put("deviceResol", DeviceUtil.getWHInfo(AndroidApplication.getInstance()));
         params.put("oprSystem", "android");
         params.put("oprator", DeviceUtil.getOperatorInfo(AndroidApplication.getInstance()));
         params.put("appVersion", DeviceUtil.getVersionCode(AndroidApplication.getInstance()) + "");
         params.put("location", AccountManage.getManage().getLocation());
         params.put("oprSysVersion", DeviceUtil.getOSInfo(AndroidApplication.getInstance()));

         params.put("deviceId", DeviceUtil.getUUID(AndroidApplication.getInstance()));
         params.put("fakeId", AccountManage.getManage().getFakeid());

         RequestUtils.RequestPost(Constants.ConnectService.getStat , "getStat", name, params, new ExecuteServiceResult(listener));
     }

     class ExecuteServiceResult implements ServiceResult {

         OnLoadDataFinishedListener listener;
         ExecuteServiceResult(OnLoadDataFinishedListener listener) {
             this.listener = listener;
         }

         @Override
         public void onSuccess(String message) {
             LogUtils.showLog("stat", message);
             try {
                 if (Utils.isSucc(message)) {
                 } else {
                     listener.onFailure(Utils.getErrorMsg(message));
                 }
             } catch (Exception e) {
                 listener.onFailure(ResourceUtils.getString(R.string.error_json));
             }
         }

         @Override
         public void onFailure(String message) {
             if (TextUtils.isEmpty(message)) {
                 listener.onFailure(ResourceUtils.getString(R.string.failture));
             } else {
                 listener.onFailure(message);
             }
         }

     }
 }

继承接口

 public interface StatisticsInfoInteractor {


     public interface OnLoadDataFinishedListener {
         void onSuccess();

         void onFailure(String message);
     }

     void execute(OnLoadDataFinishedListener listener);
 }

主页面添加

private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                address = location.getAddrStr();
                AccountManage.getManage().setLocation(address);
                //ToastUtils.show(ListInfoActivity.this, address, Toast.LENGTH_SHORT);
            }
        }

    };

在哪统计调用

 startService(new Intent(this, StatisticsDataService.class));

在清单文件中加入server权限

 <service android:name="com.sanbanhui.helper.service.StatisticsDataService" >
             <intent-filter>
                 <action android:name="com.sanbanhui.helper.service.StatisticsDataService" />
             </intent-filter>
         </service>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值