Last active
January 2, 2017 12:10
-
-
Save rameshakulapc/3fb4d6cced76ec99f062 to your computer and use it in GitHub Desktop.
Basic system utility methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.andhradroid.util; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.RandomAccessFile; | |
import java.net.InetAddress; | |
import java.net.NetworkInterface; | |
import java.net.SocketException; | |
import java.text.DecimalFormat; | |
import java.util.Enumeration; | |
import java.util.List; | |
import java.util.Locale; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import android.app.ActivityManager; | |
import android.app.ActivityManager.MemoryInfo; | |
import android.app.ActivityManager.RunningTaskInfo; | |
import android.content.ComponentName; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import android.content.pm.PackageManager; | |
import android.net.ConnectivityManager; | |
import android.net.wifi.WifiInfo; | |
import android.net.wifi.WifiManager; | |
import android.os.BatteryManager; | |
import android.os.Build; | |
import android.os.Environment; | |
import android.os.Handler; | |
import android.os.StatFs; | |
import android.provider.Settings.Secure; | |
import android.telephony.PhoneStateListener; | |
import android.telephony.SignalStrength; | |
import android.telephony.TelephonyManager; | |
import android.text.format.Formatter; | |
import android.util.Log; | |
/** | |
* The Class SystemUtil. | |
*/ | |
public class SystemUtil { | |
/** The Constant TAG. */ | |
private static final String TAG = SystemUtil.class.getSimpleName(); | |
/** | |
* Model name. | |
* @return the string | |
*/ | |
public static String modelName() { | |
return Build.MODEL.toString(); | |
} | |
/** | |
* Phone number. | |
* @param mContext the m context | |
* @return the string | |
*/ | |
public static String phoneNumber(Context mContext) { | |
TelephonyManager teleponyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); | |
return teleponyManager.getLine1Number(); | |
} | |
/** | |
* Checks if is foreground. | |
* @param context the context | |
* @return true, if is foreground | |
*/ | |
public static boolean isForeground(Context context) { | |
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); | |
List<RunningTaskInfo> list = activityManager.getRunningTasks(1); | |
ComponentName cn = list.get(0).topActivity; | |
String name = cn.getPackageName(); | |
return name.indexOf(context.getPackageName()) > -1; | |
} | |
/** | |
* Checks if is app alive. | |
* @param mContext the m context | |
* @return true, if is app alive | |
*/ | |
public static boolean isAppAlive(Context mContext) { | |
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); | |
List<RunningTaskInfo> list = activityManager.getRunningTasks(100); | |
for (RunningTaskInfo task : list) { | |
ComponentName cn = task.topActivity; | |
String name = cn.getPackageName(); | |
if (name.indexOf(mContext.getPackageName()) > -1) | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Checks if is top activity. | |
* @param mContext the m context | |
* @param name the name | |
* @return true, if is top activity | |
*/ | |
public static boolean isTopActivity(Context mContext, String name) { | |
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); | |
List<RunningTaskInfo> list = activityManager.getRunningTasks(1); | |
ComponentName cn = list.get(0).topActivity; | |
return cn.getClassName().equals(name); | |
} | |
/** | |
* At the bottom of the stack check if the name of the database activity. | |
* @param mContext the m context | |
* @param name the name | |
* @return true, if is base activity | |
*/ | |
public static boolean isBaseActivity(Context mContext, String name) { | |
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); | |
List<RunningTaskInfo> list = activityManager.getRunningTasks(1); | |
ComponentName cn = list.get(0).baseActivity; | |
return cn.getClassName().equals(name); | |
} | |
/** | |
* Checks if is connected wi fi. | |
* @param mContext the m context | |
* @return true, if is connected wi fi | |
*/ | |
public static boolean isConnectedWiFi(Context mContext) { | |
ConnectivityManager connectivityManager = (ConnectivityManager) mContext | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected(); | |
} | |
/** | |
* Checks if is connected mobile network. | |
* @param mContext the m context | |
* @return true, if is connected mobile network | |
*/ | |
public static boolean isConnectedMobileNetwork(Context mContext) { | |
boolean kResult = false; | |
try { | |
ConnectivityManager connectivityManager = (ConnectivityManager) mContext | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
kResult = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return kResult; | |
} | |
/** | |
* Is any network connected?. | |
* @param mContext the m context | |
* @return true=connected | |
*/ | |
public static boolean isConnectNetwork(Context mContext) { | |
return isConnectedWiFi(mContext) || isConnectedMobileNetwork(mContext); | |
} | |
/** | |
* Gets the connected network. | |
* @return the connected network | |
*/ | |
public static String getConnectedNetwork(Context context) { | |
if (isConnectedWiFi(context)) { | |
return "WIFI"; | |
} else if (isConnectedMobileNetwork(context)) { | |
return "Mobile"; | |
} else { | |
return "NONE"; | |
} | |
} | |
/** | |
* Android id. | |
* @param context the context | |
* @return the string | |
*/ | |
public static String androidId(Context context) { | |
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); | |
} | |
/** | |
* Return Sd-Card device that you have. | |
* @return the string | |
*/ | |
public static String isHasSDCard() { | |
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ? "Yes" : "No"; | |
} | |
/** | |
* Checks if is GPS support. | |
* @param mContext the m context | |
* @return true, if is GPS support | |
*/ | |
public static boolean isGPSSupport(Context mContext) { | |
PackageManager pm = mContext.getPackageManager(); | |
boolean hasGps = pm.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS); | |
return hasGps; | |
} | |
/** | |
* Gets the local ip address. | |
* @return the local ip address | |
*/ | |
public static String getLocalIpAddress() { | |
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()) { | |
// String ip = Formatter.formatIpAddress(inetAddress.hashCode()); | |
String ip = Formatter.formatIpAddress(inetAddress.hashCode()); | |
Log.i(TAG, "***** IP=" + ip); | |
return ip; | |
} | |
} | |
} | |
} catch (SocketException ex) { | |
Log.e(TAG, ex.toString()); | |
} | |
return ""; | |
} | |
/** | |
* Display ip address. | |
* @param mContext the m context | |
* @return the string | |
*/ | |
public static String displayIpAddress(Context mContext) { | |
String ip = ""; | |
try { | |
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); | |
WifiInfo info = wifiManager.getConnectionInfo(); | |
if (info != null && info.getNetworkId() > -1) { | |
int i = info.getIpAddress(); | |
ip = String.format(Locale.ENGLISH, "%d.%d.%d.%d", i & 0xff, i >> 8 & 0xff, i >> 16 & 0xff, | |
i >> 24 & 0xff); | |
} | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
return ip; | |
} | |
/** | |
* Gets the battery level. | |
* @param mContext the m context | |
* @return the battery level | |
*/ | |
public static float getBatteryLevel(Context mContext) { | |
Intent batteryIntent = mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); | |
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); | |
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); | |
// Error checking that probably isn't needed but I added just in case. | |
if (level == -1 || scale == -1) { | |
return 50.0f; | |
} | |
return ((float) level / (float) scale) * 100.0f; | |
} | |
/** | |
* Gets the total internal memory. | |
* @return the total internal memory size | |
*/ | |
@SuppressWarnings("deprecation") | |
public static long getTotalInternalMemorySize() { | |
final File path = Environment.getDataDirectory(); | |
final StatFs stat = new StatFs(path.getPath()); | |
final long blockSize = stat.getBlockSize(); | |
final long totalBlocks = stat.getBlockCount(); | |
return totalBlocks * blockSize; | |
} | |
/** | |
* Gets the available internal memory size. | |
* @return the available internal memory size | |
*/ | |
public static long getAvailableInternalMemorySize() { | |
final File path = Environment.getDataDirectory(); | |
final StatFs stat = new StatFs(path.getPath()); | |
final long blockSize = stat.getBlockSize(); | |
final long availableBlocks = stat.getAvailableBlocks(); | |
return availableBlocks * blockSize; | |
} | |
/** | |
* Gets the total external memory size. | |
* @return the total external memory size | |
*/ | |
public static long getTotalExternalMemorySize() { | |
final File path = Environment.getExternalStorageDirectory(); | |
final StatFs stat = new StatFs(path.getPath()); | |
final long blockSize = stat.getBlockSize(); | |
final long totalBlocks = stat.getBlockCount(); | |
return totalBlocks * blockSize; | |
} | |
/** | |
* Gets the available external memory size. | |
* @return the available external memory size | |
*/ | |
public static long getAvailableExternalMemorySize() { | |
final File path = Environment.getExternalStorageDirectory(); | |
final StatFs stat = new StatFs(path.getPath()); | |
final long blockSize = stat.getBlockSize(); | |
final long availableBlocks = stat.getAvailableBlocks(); | |
return availableBlocks * blockSize; | |
} | |
/** | |
* Format size. | |
* @param size the size | |
* @return the string | |
*/ | |
public static String formatSize(final Long size) { | |
final String bytes = "B"; | |
if (size == null || size.longValue() <= 0) { | |
return "0 " + bytes; | |
} | |
final String kb = "KB"; | |
final String mb = "MB"; | |
final String gb = "GB"; | |
final String tb = "TB"; | |
final String[] units = new String[] { bytes, kb, mb, gb, tb }; | |
final int digitGroups = (int) (Math.log10(size.doubleValue()) / Math.log10(1024)); | |
final DecimalFormat decimalFormat = new DecimalFormat("#,##0.##"); | |
return decimalFormat.format(size.doubleValue() / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; | |
} | |
/** | |
* Gets the total ram. | |
* @return the total ram | |
*/ | |
public static String getTotalRAM() { | |
RandomAccessFile reader = null; | |
String load = null; | |
double totRam = 0; | |
try { | |
reader = new RandomAccessFile("/proc/meminfo", "r"); | |
load = reader.readLine(); | |
// Get the Number value from the string | |
Pattern p = Pattern.compile("(\\d+)"); | |
Matcher m = p.matcher(load); | |
String value = ""; | |
while (m.find()) { | |
value = m.group(1); | |
// System.out.println("Ram+ value); | |
} | |
reader.close(); | |
totRam = Double.parseDouble(value); | |
return formatSize((long) totRam); | |
} catch (NumberFormatException e) { | |
e.printStackTrace(); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} finally { | |
// Streams.close(reader); | |
} | |
return ""; | |
} | |
/** | |
* Gets the total ram. | |
* @param context the context | |
* @return the total ram | |
*/ | |
public static String getTotalRAM(Context context) { | |
MemoryInfo mi = new MemoryInfo(); | |
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); | |
activityManager.getMemoryInfo(mi); | |
long availableMegs = mi.availMem / 1048576L; | |
// Percentage can be calculated for API 16+ | |
long percentAvail = mi.availMem / mi.totalMem; | |
return formatSize(mi.totalMem); | |
} | |
/** | |
* Gets the available ram. | |
* @param context the context | |
* @return the available ram | |
*/ | |
public static String getAvailableRAM(Context context) { | |
MemoryInfo mi = new MemoryInfo(); | |
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); | |
activityManager.getMemoryInfo(mi); | |
// Percentage can be calculated for API 16+ | |
long percentAvail = mi.availMem / mi.totalMem; | |
return formatSize(mi.availMem); | |
} | |
/** | |
* Gets the imei number of the device. | |
* @param context the context | |
* @return the ime i no | |
*/ | |
public static String getImeINo(Context context) { | |
TelephonyManager mngr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
return mngr.getDeviceId(); | |
} | |
/** The m signal strength. */ | |
private static String mSignalStrength = "Un Known"; | |
/** | |
* Gets the signal strength in dBm. | |
* @param context the context | |
* @return the signal strength | |
*/ | |
public static String getSignalStrength(Context context) { | |
final TelephonyManager mngr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
new Handler(context.getMainLooper()).post(new Runnable() { | |
@Override | |
public void run() { | |
if (mngr != null) | |
mngr.listen(new PhoneStateListener() { | |
@Override | |
public void onSignalStrengthsChanged(SignalStrength signalStrength) { | |
super.onSignalStrengthsChanged(signalStrength); | |
mSignalStrength = signalStrength.getGsmSignalStrength() + "dBm"; | |
} | |
}, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); | |
} | |
}); | |
try { | |
Thread.sleep(500L); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
return mSignalStrength; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's helpful methods
Thanks a lot (: