Skip to content

Instantly share code, notes, and snippets.

@5ZSQ
Last active September 29, 2017 01:49
Show Gist options
  • Save 5ZSQ/a11198e6b4a7c3228b71f9a2f3b1031a to your computer and use it in GitHub Desktop.
Save 5ZSQ/a11198e6b4a7c3228b71f9a2f3b1031a to your computer and use it in GitHub Desktop.
Android通用工具类 - CommonUtil.java
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.Build.VERSION;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
import com.reyun.common.TrackingIOConst;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.Map.Entry;
import org.json.JSONObject;
public class CommonUtil {
private static final String TAG = "reyunsdk";
private static long RLong;
private static String sDeviceID;
public CommonUtil() {
}
public static void SetSdkNameAndVer(String sdkname, String sdkver) {
TrackingIOConst.ry_sdk_name = sdkname;
TrackingIOConst.ry_sdk_ver = sdkver;
}
@SuppressLint({"SimpleDateFormat"})
public static String getTime(long interval) {
SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
localSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return localSimpleDateFormat.format(Long.valueOf(interval));
}
public static long GetLong(Context context, String XMLName, String key) {
try {
SharedPreferences e = context.getSharedPreferences(XMLName, 0);
RLong = e.getLong(key, 0L);
if(RLong == 0L) {
RLong = System.currentTimeMillis();
}
return RLong;
} catch (Exception var4) {
return 0L;
}
}
public static String getTimeZone() {
int time_zone = TimeZone.getDefault().getRawOffset() / 1000 / 3600;
return time_zone > 0?"+" + time_zone:String.valueOf(time_zone);
}
public static String getPackageName(Context context) {
return context == null?"unknown":context.getPackageName();
}
/**
* 获取 AndroidId 这里为设备唯一标识
*
* @param context 上下文
* @return
*/
private static String getAndroidId(Context context) {
@SuppressLint("HardwareIds") String androidid = getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
return androidid == null ? "" : androidid;
}
public static String getDeviceID(Context context) {
String deviceId = "";
if (checkPermissions(context, Manifest.permission.READ_PHONE_STATE)) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return "";
}
deviceId = tm.getDeviceId();
if (TextUtils.isEmpty(deviceId)) {
deviceId = getAndroidId(context);
}
}
if (!TextUtils.isEmpty(deviceId)) {
return deviceId;
} else {
Log.w("MC Util", "deviceId is null");
return "unknown";
}
} else {
Log.w("MC Util", "lost----->android.permission.READ_PHONE_STATE");
return "unknown";
}
}
/**
*
* @param context - 上下文
* @param permission - Manifest.permission.xxx
* @return 是否被授权
*/
public static boolean checkPermissions(Context context, String permission) {
return context != null && ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
public static String getAndroidId(Context context) {
String androidid = Secure.getString(context.getContentResolver(), "android_id");
return androidid == null?"unknown":androidid;
}
public static String getOperatorName(Context context) {
if(checkPermissions(context, "android.permission.READ_PHONE_STATE")) {
String op = "unknown";
TelephonyManager tm = (TelephonyManager)context.getSystemService("phone");
op = tm.getSimOperatorName();
if(op != null) {
if(op.equals("")) {
op = "unknown";
}
if(TrackingIOConst.DebugMode) {
printLog("commonUtil", "op:" + op);
}
return op;
} else {
if(TrackingIOConst.DebugMode) {
Log.w("commonUtil", "deviceId is null");
}
return "unknown";
}
} else {
if(TrackingIOConst.DebugMode) {
Log.w("lost permissioin", "lost----->android.permission.READ_PHONE_STATE");
}
return "unknown";
}
}
public static String getPhoneResolution(Context context) {
try {
WindowManager e = (WindowManager)context.getSystemService("window");
DisplayMetrics displaysMetrics = new DisplayMetrics();
e.getDefaultDisplay().getMetrics(displaysMetrics);
return displaysMetrics.widthPixels + "*" + displaysMetrics.heightPixels;
} catch (Exception var3) {
return "unknown";
}
}
public static boolean checkPhoneState(Context context) {
PackageManager packageManager = context.getPackageManager();
return packageManager.checkPermission("android.permission.READ_PHONE_STATE", context.getPackageName()) == 0;
}
private static String getNetworkType(Context context) {
TelephonyManager manager = (TelephonyManager)context.getSystemService("phone");
int type = manager.getNetworkType();
String typeString = "unknown";
if(type == 4) {
typeString = "CDMA";
typeString = "2G";
} else if(type == 2) {
typeString = "EDGE";
typeString = "2G";
} else if(type == 5) {
typeString = "EVDO_0";
typeString = "3G";
} else if(type == 6) {
typeString = "EVDO_A";
typeString = "3G";
} else if(type == 1) {
typeString = "GPRS";
typeString = "2G";
} else if(type == 8) {
typeString = "HSDPA";
typeString = "3G";
} else if(type == 10) {
typeString = "HSPA";
} else if(type == 9) {
typeString = "HSUPA";
} else if(type == 3) {
typeString = "UMTS";
typeString = "3G";
} else if(type == 13) {
typeString = "4G";
} else if(type == 0) {
typeString = "UNKOWN";
}
return typeString;
}
public static String getConnectType(Context context) {
try {
if(checkPermissions(context, "android.permission.INTERNET")) {
ConnectivityManager cManager = (ConnectivityManager)context.getSystemService("connectivity");
NetworkInfo mWifi = cManager.getNetworkInfo(1);
NetworkInfo mMobile = cManager.getNetworkInfo(0);
if(mWifi != null && mWifi.isAvailable() && mWifi.isConnected()) {
return "WIFI";
}
if(mMobile != null && mMobile.isAvailable() && mMobile.isConnected()) {
return getNetworkType(context);
}
return "unknown";
}
if(TrackingIOConst.DebugMode) {
Log.w(" lost permission", "lost----> android.permission.INTERNET");
}
} catch (Exception var4) {
;
}
return "unknown";
}
public static String getVersion(Context context) {
String versionName = "unknown";
try {
PackageManager e = context.getPackageManager();
PackageInfo pi = e.getPackageInfo(context.getPackageName(), 0);
versionName = pi.versionName;
if(versionName == null || versionName.length() <= 0) {
return "unknown";
}
} catch (Exception var4) {
var4.printStackTrace();
}
return versionName;
}
public static void printLog(String tag, String log) {
if(TrackingIOConst.DebugMode) {
Log.d(tag, log);
}
}
public static void printWarningLog(String tag, String log) {
if(TrackingIOConst.DebugMode) {
Log.w(tag, log);
}
}
public static void printErrLog(String tag, String log) {
if(TrackingIOConst.DebugMode) {
Log.w(tag, log);
}
}
public static boolean checkAppid(String appId) {
return !isNullOrEmpty(appId);
}
public static boolean isTablet(Context context) {
return context == null?false:(context.getResources().getConfiguration().screenLayout & 15) >= 3;
}
public static boolean isNullOrEmpty(String str) {
return str == null || str.trim().length() == 0;
}
public static String checkStringValue(String str, String defaultStr, String errorMsg) {
String value = isNullOrEmpty(str)?defaultStr:str;
if(defaultStr.equals(value)) {
printWarningLog("reyunsdk", errorMsg);
}
return value;
}
public static String getLocalMacAddress(Context context) {
try {
String e = "android.permission.ACCESS_WIFI_STATE";
if(!checkPermissions(context, e)) {
Log.w("reyunsdk", "!!!MISSING permission [" + e + "]");
return "unknown";
} else {
WifiManager wifi = (WifiManager)context.getSystemService("wifi");
WifiInfo info = wifi.getConnectionInfo();
return info == null?"unknown":info.getMacAddress();
}
} catch (Exception var4) {
return "unknown";
}
}
public static String getInstalledApplications(Context context) {
PackageManager pm = context.getPackageManager();
List applicationList = pm.getInstalledApplications(8192);
StringBuilder sb = new StringBuilder();
int pkglist = 0;
for(int size = applicationList.size(); pkglist < size; ++pkglist) {
ApplicationInfo appInfo = (ApplicationInfo)applicationList.get(pkglist);
if((appInfo.flags & 1) == 0) {
sb.append(getAppPackageName(appInfo));
sb.append('\u0005');
sb.append(getAppLabelName(pm, appInfo));
sb.append('\u0005');
sb.append(getAppFirstTime(appInfo));
sb.append('\u0005');
sb.append(getAppUsageTime(appInfo));
sb.append('\u0005');
sb.append(getAppUsageCount(context, appInfo));
sb.append('\u0006');
}
}
if(sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
String var7 = sb.toString();
printLog("reyunsdk", "pkglist before compress:" + var7);
return compressString(var7);
}
private static String getAppPackageName(ApplicationInfo appInfo) {
return appInfo.packageName;
}
private static String getAppLabelName(PackageManager pm, ApplicationInfo appInfo) {
return (String)pm.getApplicationLabel(appInfo);
}
private static String getAppFirstTime(ApplicationInfo appInfo) {
return "unknown";
}
private static String getAppUsageTime(ApplicationInfo appInfo) {
return "unknown";
}
private static String getAppUsageCount(Context context, ApplicationInfo appInfo) {
return String.valueOf(getLuanchCountOfApp(context, appInfo));
}
public static final String compressString(String str) {
StringBuffer sb = new StringBuffer();
byte[] tempBytes = null;
try {
tempBytes = str.getBytes("utf-8");
} catch (UnsupportedEncodingException var6) {
var6.printStackTrace();
}
if(tempBytes != null) {
for(int i = 0; i < tempBytes.length; i += 2) {
char firstCharacter = (char)tempBytes[i];
char secondCharacter = 0;
if(i + 1 < tempBytes.length) {
secondCharacter = (char)tempBytes[i + 1];
}
firstCharacter = (char)(firstCharacter << 8);
sb.append((char)(firstCharacter + secondCharacter));
}
}
return sb.toString();
}
public static String getDeviceGps(Context context) {
try {
LocationManager e = (LocationManager)context.getSystemService("location");
Location location = e.getLastKnownLocation("gps");
if(location == null) {
location = e.getLastKnownLocation("network");
}
if(location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
return latitude + "|" + longitude;
} else {
printLog("reyunsdk", "Get deivce gps failed!");
return "unknown";
}
} catch (Exception var7) {
printLog("reyunsdk", "Get deivce gps failed!" + var7.getMessage());
return "unknown";
}
}
public static String getDeviceIps() {
String hostIp = "unknown";
try {
Enumeration e = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while(true) {
while(e.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface)e.nextElement();
Enumeration ias = ni.getInetAddresses();
while(ias.hasMoreElements()) {
ia = (InetAddress)ias.nextElement();
if(!(ia instanceof Inet6Address)) {
String ip = ia.getHostAddress();
if(!"127.0.0.1".equals(ip)) {
hostIp = ia.getHostAddress();
break;
}
}
}
}
return hostIp;
}
} catch (SocketException var6) {
var6.printStackTrace();
} catch (Exception var7) {
var7.printStackTrace();
}
return hostIp;
}
public static String getNetflow(Context context) {
long netflow = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
SharedPreferences sp = context.getSharedPreferences("netflow", 0);
long tmp = sp.getLong("netflow_total", 0L);
Editor e = sp.edit();
e.putLong("netflow_total", netflow);
e.commit();
if(tmp < netflow) {
netflow -= tmp;
} else {
netflow = tmp;
}
return String.valueOf(netflow);
}
public static String getNetflowWifi(Context context) {
SharedPreferences sp = context.getSharedPreferences("netflow", 0);
long totalBytes = sp.getLong("netflow_total", 0L);
long mobileBytes = sp.getLong("netflow_mobile", 0L);
long netflow = totalBytes - mobileBytes;
long tmp = sp.getLong("netflow_wifi", 0L);
Editor e = sp.edit();
e.putLong("netflow_wifi", netflow);
e.commit();
if(tmp < netflow) {
netflow -= tmp;
} else {
netflow = tmp;
}
return String.valueOf(netflow);
}
public static String getNetflowMobile(Context context) {
long netflow = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
SharedPreferences sp = context.getSharedPreferences("netflow", 0);
long tmp = sp.getLong("netflow_mobile", 0L);
Editor e = sp.edit();
e.putLong("netflow_mobile", netflow);
e.commit();
if(tmp < netflow) {
netflow -= tmp;
} else {
netflow = tmp;
}
return String.valueOf(netflow);
}
public static String getActions() {
return "unknown";
}
public static String getLocalMacAddressForAndroid6() {
String result = getMacAddress1();
if(!isNullOrEmpty(result)) {
return result;
} else {
result = getMacAddress3();
return !isNullOrEmpty(result)?result:getMacAddress2();
}
}
public static String getMacAddress3() {
try {
NetworkInterface e = NetworkInterface.getByName("wlan0");
return e == null?null:ConvertMacAddressBytesToString(e.getHardwareAddress());
} catch (Exception var1) {
return null;
}
}
private static String ConvertMacAddressBytesToString(byte[] hardwareAddress) {
return new String(hardwareAddress);
}
public static String getMacAddress1() {
String address = null;
try {
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while(true) {
NetworkInterface netWork;
byte[] by;
do {
do {
do {
if(!interfaces.hasMoreElements()) {
return address;
}
netWork = (NetworkInterface)interfaces.nextElement();
} while(netWork == null);
by = netWork.getHardwareAddress();
} while(by == null);
} while(by.length == 0);
StringBuilder builder = new StringBuilder();
byte[] var8 = by;
int var7 = by.length;
for(int var6 = 0; var6 < var7; ++var6) {
byte mac = var8[var6];
builder.append(String.format("%02X:", new Object[]{Byte.valueOf(mac)}));
}
if(builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
String var10 = builder.toString();
if(netWork.getName().equals("wlan0")) {
address = var10;
}
}
} catch (Exception var9) {
return address;
}
}
public static String getMacAddress2() {
String str = "";
String macSerial = "";
try {
Process e = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
InputStreamReader ir = new InputStreamReader(e.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
while(str != null) {
str = input.readLine();
if(str != null) {
macSerial = str.trim();
break;
}
}
} catch (Exception var6) {
var6.printStackTrace();
}
if(macSerial == null || "".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/eth0/address").toUpperCase(Locale.getDefault()).substring(0, 17);
} catch (Exception var5) {
var5.printStackTrace();
}
}
return macSerial != null && !"".equals(macSerial)?macSerial:"unknown";
}
public static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
public static String loadReaderAsString(Reader reader) throws Exception {
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
for(int readLength = reader.read(buffer); readLength >= 0; readLength = reader.read(buffer)) {
builder.append(buffer, 0, readLength);
}
return builder.toString();
}
public static void AddMapToJSONObject(Map<String, Object> extra, JSONObject mydata) {
if(extra != null) {
try {
JSONObject contextData = mydata.getJSONObject("context");
if(contextData != null) {
Iterator it = extra.entrySet().iterator();
while(it.hasNext()) {
Entry pEntry = (Entry)it.next();
String key = (String)pEntry.getKey();
Object value = pEntry.getValue();
if(key != null && value != null) {
contextData.put(key.toString(), value.toString());
}
}
}
} catch (Exception var7) {
;
}
}
}
public static void logi(String tag2, String string) {
if(TrackingIOConst.DebugMode) {
Log.i(tag2, string);
}
}
public static int getLuanchCountOfApp(Context context, ApplicationInfo appInfo) {
if(context == null) {
return 0;
} else {
SharedPreferences sp = context.getSharedPreferences("luanchCount", 0);
int luanchCount = 0;
if(sp != null) {
luanchCount = sp.getInt(appInfo.packageName, 0);
}
printLog("reyunsdk", appInfo.packageName + " luanched " + luanchCount);
return luanchCount;
}
}
@TargetApi(21)
public static void getTopApp(Context context) {
if(VERSION.SDK_INT >= 21) {
UsageStatsManager m = (UsageStatsManager)context.getSystemService("usagestats");
if(m != null) {
long now = System.currentTimeMillis();
List stats = m.queryUsageStats(4, now - 60000L, now);
Log.i("reyunsdk", "Running app number in last 60 seconds : " + stats.size());
String topActivity = "";
if(stats != null && !stats.isEmpty()) {
int j = 0;
for(int i = 0; i < stats.size(); ++i) {
if(((UsageStats)stats.get(i)).getLastTimeUsed() > ((UsageStats)stats.get(j)).getLastTimeUsed()) {
j = i;
}
}
topActivity = ((UsageStats)stats.get(j)).getPackageName();
}
Log.i("reyunsdk", "top running app is : " + topActivity);
}
}
}
public static void getPkgUsageStats() {
printErrLog("reyunsdk", "[getPkgUsageStats]");
try {
Class e = Class.forName("android.os.ServiceManager");
Method mGetService = e.getMethod("getService", new Class[]{String.class});
Object oRemoteService = mGetService.invoke((Object)null, new Object[]{"usagestats"});
Class cStub = Class.forName("com.android.internal.app.IUsageStats$Stub");
Method mUsageStatsService = cStub.getMethod("asInterface", new Class[]{IBinder.class});
Object oIUsageStats = mUsageStatsService.invoke((Object)null, new Object[]{oRemoteService});
Class cIUsageStatus = Class.forName("com.android.internal.app.IUsageStats");
Method mGetAllPkgUsageStats = cIUsageStatus.getMethod("getAllPkgUsageStats", (Class[])null);
Object[] oPkgUsageStatsArray = (Object[])mGetAllPkgUsageStats.invoke(oIUsageStats, (Object[])null);
printErrLog("reyunsdk", "[getPkgUsageStats] oPkgUsageStatsArray = " + oPkgUsageStatsArray);
Class cPkgUsageStats = Class.forName("com.android.internal.os.PkgUsageStats");
StringBuffer sb = new StringBuffer();
sb.append("nerver used : ");
Object[] var14 = oPkgUsageStatsArray;
int var13 = oPkgUsageStatsArray.length;
for(int var12 = 0; var12 < var13; ++var12) {
Object pkgUsageStats = var14[var12];
String packageName = (String)cPkgUsageStats.getDeclaredField("packageName").get(pkgUsageStats);
int launchCount = cPkgUsageStats.getDeclaredField("launchCount").getInt(pkgUsageStats);
long usageTime = cPkgUsageStats.getDeclaredField("usageTime").getLong(pkgUsageStats);
if(launchCount > 0) {
printErrLog("reyunsdk", "[getPkgUsageStats] " + packageName + " count: " + launchCount + " time: " + usageTime);
} else {
sb.append(packageName + "; ");
}
}
printErrLog("reyunsdk", "[getPkgUsageStats] " + sb.toString());
} catch (Exception var19) {
var19.printStackTrace();
}
}
public static String getADID(Context context) {
try {
Info e = null;
e = AdvertisingIdClient.getAdvertisingIdInfo(context);
if(e != null) {
return e.getId();
}
} catch (Exception var2) {
var2.printStackTrace();
} catch (Error var3) {
var3.printStackTrace();
}
return "unknown";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment