- How to Get Android Hardware and System Information Programmatically
- Detect android device MANUFACTURER name and model name on button click.
- How to get android mobile phone model programmatically.
- Click here to download How to get android mobile phone model programmatically project.
- How to Get Android Device Information
- Creating a New Project
- Add recyclerview dependency
- Add new permissions
- Create a new Model Class
- Create a new Adapter class
- Add a new xml layout
- Edit activity_main.xml layout
- Edit MainActivity.java class
- Run your Project
- Получить Android Phone Model программно
- Библиотека AndroidDeviceNames на Github
How to Get Android Hardware and System Information Programmatically
The android hardware and system information is different from device to device. You can find your android device info manually in About device section of settings. In this tutorial, you will learn to get android device system and hardware information programmatically. We will focus on some of the properties like serial number, model no, id, android SDK, brand, manufacture, version code, etc.
There are many other info you can get from a android device but here we will focus on some of the android properties. To get system info, we are going to add a button and a textview to display information of android device when button is clicked.
Related:
Embed and Play MP3 Songs/Music in Android Application Using WebView
Android Custom Horizontal Icons Menu
Material Ripple Effect/Animation in Android
There are different methods to retrieve the platform related information of the device programmatically. To obtain the hardware and software related information of an android device that runs your application, follow the following steps. Here we will only display information in TextView but you can also track to your server. You can get info like;
- CPU Manufacturer
- Model and serial number
- SD Card Manufacturer
- Camera Manufacturer and other related specs
- Bluetooth related information
- WiFi related information
- Display vendor and model
Android Example: Getting Android Hardware and System Information Programmatically
Create a new android project with project name AndroidSystemInfo packagecom.viralandroid.androidsysteminfo.
Open your activity_main.xml file and add a Button and TextView with different id. TextView is used to display device info when we click the button. Following is the complete code XML layout file.
res/layout/activity_main.xml
Java Activity File
Open your MainActivity.java activity file and define button and textview that we have created above in xml layout file. To get and display system info, see the following code.
And colors.xml, styles.xml file will look like below;
res/values/styles.xml
You have done all things. Now, run your application by clicking run button and click Get Android System Info button; you will see all information below the button like the screenshot presented above.
Detect android device MANUFACTURER name and model name on button click.
Every android mobile phone contain its model number and manufacturer name but most of peoples doesn’t know their mobile phone model number because there are so much different types of models coming with numbered values. So here is the complete step by step tutorial for How to get android mobile phone model programmatically.
How to get android mobile phone model programmatically.
Code for MainActivity.java file.
package com.getandroidmobilephonemodel_android_examples.com; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity < String DeviceModel, DeviceName; TextView model, device; Button getboth; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); model = (TextView)findViewById(R.id.textView1); device = (TextView)findViewById(R.id.textView2); getboth = (Button)findViewById(R.id.button1); getboth.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < DeviceModel= android.os.Build.MODEL; DeviceName= android.os.Build.MANUFACTURER; model.setText(DeviceModel); device.setText(DeviceName); > >); > >
Code for activity_main.xml layout file.
Screenshot :
Click here to download How to get android mobile phone model programmatically project.
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.
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.
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.
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.
public class DeviceAdapter extends RecyclerView.Adapter < private ListdeviceList; 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 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”.
Edit activity_main.xml layout
Open your activity_main and change to the following layout.
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.
public class MainActivity extends AppCompatActivity < private ListdeviceList = 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[], 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.
Получить Android Phone Model программно
На многих популярных устройствах рыночное название устройства недоступно. Например, на Samsung Galaxy S6 значение Build.MODEL может быть «SM-G920F» , «SM-G920I» или «SM-G920W8» . Я создал небольшую библиотеку, которая получила название устройства (потребительское). Он получает правильное имя для более чем 10 000 устройств и постоянно обновляется. Если вы хотите использовать мою библиотеку, нажмите ссылку ниже:
Библиотека AndroidDeviceNames на Github
Если вы не хотите использовать библиотеку выше, то это лучшее решение для получения удобного для пользователя имени устройства:
/** Returns the consumer friendly device name */ public static String getDeviceName() < String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) < return capitalize(model); >return capitalize(manufacturer) + " " + model; > private static String capitalize(String str) < if (TextUtils.isEmpty(str)) < return str; >char[] arr = str.toCharArray(); boolean capitalizeNext = true; StringBuilder phrase = new StringBuilder(); for (char c : arr) < if (capitalizeNext && Character.isLetter(c)) < phrase.append(Character.toUpperCase(c)); capitalizeNext = false; continue; >else if (Character.isWhitespace(c)) < capitalizeNext = true; >phrase.append(c); > return phrase.toString(); >
// using method from above System.out.println(getDeviceName()); // Using https://github.com/jaredrummler/AndroidDeviceNames System.out.println(DeviceName.getDeviceName());
Спасибо, Джаред. Мне это нужно было сегодня, но для Xamarin.Android перевел ваш файл на C #. Если кому-то еще это нужно, вы можете найти его здесь. gist.github.com/mohibsheth/5e1b361ae49c257b8caf
Есть ли способ получить «удобочитаемое» имя устройства, такое как «Xperia Z3» или «Galaxy S3» без этого класса устройств? Я не хотел бы использовать статический список всех устройств, чтобы быть уверенным, что даже все будущие устройства будут поддерживаться.
@Radon8472 Radon8472 Вы пробовали использовать статический фабричный метод, названный выше getDeviceName() ? Если это не даст вам результатов, которые вы ищете, я не знаю лучшего решения, о котором я знаю.
@Jared: У меня уже есть имя устройства, похожее на результаты getDeviceName (), но мне нравится отображать имя, которое конечные пользователи знают из своих удобных магазинов 🙁
Привет всем, я написал угловой модуль для этого под названием ng-fone, используя список от Джареда. Ниже ссылка дает инструкции о том, как его использовать. tphangout.com/?p=83
@RajaYogan RajaYogan Вау, круто. Я хочу определить производителя по номеру модели, ваш набор объектов действительно хорош для этого. Кстати, где вы взяли эту большую базу данных?
Я использую следующий код, чтобы получить полное имя устройства. Он получает строки модели и производителя и объединяет их, если модельная строка уже содержит имя производителя (на некоторых телефонах):
public String getDeviceName() < String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) < return capitalize(model); >else < return capitalize(manufacturer) + " " + model; >> private String capitalize(String s) < if (s == null || s.length() == 0) < return ""; >char first = s.charAt(0); if (Character.isUpperCase(first)) < return s; >else < return Character.toUpperCase(first) + s.substring(1); >>
Вот несколько примеров имен устройств, которые я получил от пользователей:
Samsung GT-S5830L
Motorola MB860
Sony Ericsson LT18i
LGE LG-P500
HTC Desire V
HTC Wildfire S A510e
.
Это где-то список, в котором хранятся все возможные ответы, которые вы можете получить из телефона. Скажите, если вам нужно перенаправить пользователя о том, как установить что-то на телефон определенного типа или продать что-то определенной модели.