How to Get Android Device Information

Sometimes we need the user hardware information to keep track what type of user android device using our application. In the Android SDK, there have problem some classes to get the android hardware information in the application. The information that we can get are Android version, Android Model, Sim card telco, IMEI and more. Every device have different attributes and we need to know about it. In this tutorial, I will teach you how to get android device information in your new project.
Creating a New Project
1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “DeviceInfoExample”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Empty Activity” and Click Next button
5. Lastly, press finish button.
Add recyclerview dependency
I add this dependency in the build.gradle(Module:app), so i can use recyclerview to display the list of device information.
1 |
compile 'com.android.support:recyclerview-v7:25.0.1' |
Add new permissions
Go to your AndroidManifest file and add 3 new permissions which are READ_PHONE_STATE, ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE.
1 2 3 |
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> |
Create a new Model Class
Right click your project name and create a new class for device model. Copy the source code in the below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class Device { String key; String value; public Device(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
Create a new Adapter class
Adapter is the middle man of the view and model, the adapter will pass the model and display it in the activity view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.MyViewHolder> { private List<Device> deviceList; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView key, value; public MyViewHolder(View view) { super(view); key = (TextView) view.findViewById(R.id.txtKey); value = (TextView) view.findViewById(R.id.txtValue); } } public DeviceAdapter(List<Device> deviceList) { this.deviceList = deviceList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.row_item, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { Device device = deviceList.get(position); holder.key.setText(device.getKey()); holder.value.setText(device.getValue()); } @Override public int getItemCount() { return deviceList.size(); } } |
Add a new xml layout
Create a new xml layout for the recyclerview item row. The xml name “row_item”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_margin="@dimen/activity_horizontal_margin" android:layout_height="wrap_content"> <TextView android:text="Key" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/txtKey" /> <TextView android:text="Value" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/txtValue" /> </LinearLayout> |
Edit activity_main.xml layout
Open your activity_main and change to the following layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.questdot.deviceinfoexample.MainActivity"> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/recyclerview" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> </RelativeLayout> |
Edit MainActivity.java class
Change this class source code, and it will display all the device information in your activity. Note : Android M and above should allow the permissions access for the device infomation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
public class MainActivity extends AppCompatActivity { private List<Device> deviceList = new ArrayList<>(); private RecyclerView recyclerView; private DeviceAdapter mAdapter; private final int REQUEST_READ_PHONE_STATE =1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recyclerview); int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE); } else { getDeviceInfo(); } } public void getDeviceInfo(){ TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); deviceList.add(new Device("Device Id(IMEI)",tm.getDeviceId())); deviceList.add(new Device("Device Software Version",tm.getDeviceSoftwareVersion())); deviceList.add(new Device("Line1 Number",tm.getLine1Number())); deviceList.add(new Device("Network Country Iso",tm.getNetworkCountryIso())); deviceList.add(new Device("Network Operator",tm.getNetworkOperator())); deviceList.add(new Device("Network Operator Name",tm.getNetworkOperatorName())); deviceList.add(new Device("Network Type",String.valueOf(tm.getNetworkType()))); deviceList.add(new Device("Phone Type",String.valueOf(tm.getPhoneType()))); deviceList.add(new Device("Sim Country Iso",tm.getSimCountryIso())); deviceList.add(new Device("Sim Operator",tm.getSimOperator())); deviceList.add(new Device("Sim Operator Name",tm.getSimOperatorName())); deviceList.add(new Device("Sim Serial Number",tm.getSimSerialNumber())); deviceList.add(new Device("Sim State",String.valueOf(tm.getSimState()))); deviceList.add(new Device("Subscriber Id(IMSI)",tm.getSubscriberId())); deviceList.add(new Device("Voice Mail Number",tm.getVoiceMailNumber())); deviceList.add(new Device("Mac Address",getMacInfo())); String rom = formatSize(getRomMemory()) + " / " + formatSize(getRomRemain()); deviceList.add(new Device("ROM Storage",rom)); String sdcard = formatSize(getSDCardTotal()) + " / " + formatSize(getSDCardMemoryLeft()); deviceList.add(new Device("SD Card Storage",sdcard)); String a[] = getCpuInfo(); deviceList.add(new Device("CPU",a[1])); String b[] = getVersion(); deviceList.add(new Device("Android version",b[1])); deviceList.add(new Device("Phone Model",b[2])); deviceList.add(new Device("Screen Resolution",getScreenResolution())); deviceList.add(new Device("Screen Size",getScreenSize())); deviceList.add(new Device("APN Type",getAPNType(getApplicationContext()))); deviceList.add(new Device("Root Access",isRoot()+"")); WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress()); deviceList.add(new Device("Wifi IP address",ip)); mAdapter = new DeviceAdapter(deviceList); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_READ_PHONE_STATE: if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { getDeviceInfo(); } break; default: break; } } public String formatSize(long size) { String suffix = null; float fSize = 0; if (size >= 1024) { suffix = "KB"; fSize = size / 1024; if (fSize >= 1024) { suffix = "MB"; fSize /= 1024; } if (fSize >= 1024) { suffix = "GB"; fSize /= 1024; } } else { fSize = size; } java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00"); StringBuilder resultBuffer = new StringBuilder(df.format(fSize)); if (suffix != null) resultBuffer.append(suffix); return resultBuffer.toString(); } public String getMacInfo() { String mac; WifiManager wifiManager = (WifiManager) this .getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo.getMacAddress() != null) { mac = wifiInfo.getMacAddress(); } else { mac = "Fail"; } return mac; } public long getRomMemory() { long romInfo; romInfo = getTotalInternalMemorySize(); return romInfo; } public long getRomRemain() { long romInfo; romInfo = getTotalInternalMemorySize(); File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); romInfo = blockSize * availableBlocks; return romInfo; } public long getTotalInternalMemorySize() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } public long getSDCardTotal() { long sdCardInfo = 0; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { File sdcardDir = Environment.getExternalStorageDirectory(); StatFs sf = new StatFs(sdcardDir.getPath()); long bSize = sf.getBlockSize(); long bCount = sf.getBlockCount(); sdCardInfo = bSize * bCount;//total } return sdCardInfo; } public long getSDCardMemoryLeft() { long sdCardInfo = 0; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { File sdcardDir = Environment.getExternalStorageDirectory(); StatFs sf = new StatFs(sdcardDir.getPath()); long bSize = sf.getBlockSize(); long availBlocks = sf.getAvailableBlocks(); sdCardInfo = bSize * availBlocks;//left storage } return sdCardInfo; } public String[] getCpuInfo() { String str1 = "/proc/cpuinfo"; String str2 = ""; String[] cpuInfo = { "", "" }; String[] arrayOfString; try { FileReader fr = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); str2 = localBufferedReader.readLine(); arrayOfString = str2.split("\\s+"); for (int i = 2; i < arrayOfString.length; i++) { cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " "; } str2 = localBufferedReader.readLine(); arrayOfString = str2.split("\\s+"); cpuInfo[1] += arrayOfString[2]; localBufferedReader.close(); } catch (IOException e) { } return cpuInfo; } public String[] getVersion() { String[] version = { "null", "null", "null", "null" }; String str1 = "/proc/version"; String str2; String[] arrayOfString; try { FileReader localFileReader = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader( localFileReader, 8192); str2 = localBufferedReader.readLine(); arrayOfString = str2.split("\\s+"); version[0] = arrayOfString[2];// KernelVersion localBufferedReader.close(); } catch (IOException e) { } version[1] = Build.VERSION.RELEASE;// firmware version version[2] = Build.MODEL;// model version[3] = Build.DISPLAY;// system version return version; } public String getScreenResolution(){ DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int width = metrics.widthPixels; int height = metrics.heightPixels; return ""+width+"/"+height; } public String getScreenSize(){ DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int width=dm.widthPixels; int height=dm.heightPixels; int dens=dm.densityDpi; double wi=(double)width/(double)dens; double hi=(double)height/(double)dens; double x = Math.pow(wi,2); double y = Math.pow(hi,2); double screenInches = Math.sqrt(x+y); return ""+screenInches; } public static String getAPNType(Context context) { String netType = "nono_connect"; ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo == null) { return netType; } int nType = networkInfo.getType(); if (nType == ConnectivityManager.TYPE_WIFI) { //WIFI netType = "wifi"; } else if (nType == ConnectivityManager.TYPE_MOBILE) { int nSubType = networkInfo.getSubtype(); TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); //4G if (nSubType == TelephonyManager.NETWORK_TYPE_LTE && !telephonyManager.isNetworkRoaming()) { netType = "4G"; } else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0 && !telephonyManager.isNetworkRoaming()) { netType = "3G"; } else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS || nSubType == TelephonyManager.NETWORK_TYPE_EDGE || nSubType == TelephonyManager.NETWORK_TYPE_CDMA && !telephonyManager.isNetworkRoaming()) { netType = "2G"; } else { netType = "2G"; } } return netType; } public static boolean isRoot() { String binPath = "/system/bin/su"; String xBinPath = "/system/xbin/su"; if (new File(binPath).exists() && isExecutable(binPath)) return true; if (new File(xBinPath).exists() && isExecutable(xBinPath)) return true; return false; } private static boolean isExecutable(String filePath) { Process p = null; try { p = Runtime.getRuntime().exec("ls -l " + filePath); BufferedReader in = new BufferedReader(new InputStreamReader( p.getInputStream())); String str = in.readLine(); if (str != null && str.length() >= 4) { char flag = str.charAt(3); if (flag == 's' || flag == 'x') return true; } } catch (IOException e) { e.printStackTrace(); } finally { if (p != null) { p.destroy(); } } return false; } } |
Run your Project
Lastly, you can now try to run and view the device information on your mobile device.