I have used geocoder to get the address through the location. However, the city name is in English and I want to show it in Arabic.
This is the code to get the address :
public String getAddress(double LATITUDE, double LONGITUDE) {
String city = "";
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
}
} catch (IOException e) {
e.printStackTrace();
}
return city;
}
And then this is where I show the city name in a TextView :
String country_and_city = getAddress(latitude, longitude);
TextView city_name = findViewById(R.id.city);
city_name.setText(country_and_city);
Here, the city name will be displayed in English, how can I translate it or use other methods to show it in Arabic? For example, maybe using google-translate api or something if that is even possible
In order to use the Google Cloud Translation API, you need to have a project which has this API enabled, so you can make authenticated calls. You can set it up here.
Google provide a lot of sample codes, here, which you can use. The code below is used to translate a string Spanish(es) to German(de),
Translation translation =
translate.translate(
"Hola Mundo!",
Translate.TranslateOption.sourceLanguage("es"),
Translate.TranslateOption.targetLanguage("de"),
// Use "base" for standard edition, "nmt" for the premium model.
Translate.TranslateOption.model("nmt"));
System.out.printf("TranslatedText:\nText: %s\n", translation.getTranslatedText());
This article explains in details how to integrate the API within your Android Studio project, it can give you a better overview of the whole process.
Lastly, I should point out that according to the documentation,
Prices are pro rata (proportional and incremental). Charges are scaled to the number of characters actually provided to Cloud Translation. For example, if you send 575,000 characters for processing within a month, you are charged $1.50. The first 500,000 characters are free, and then you are charged for the additional 75,000 characters sent for detection, translation, or both.
As another alternative you can also check the googletrans library, which according to the documentation:
Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make calls to such methods as detect and translate.
Related
An android mobile actually does know quite well where it is - but is there a way of retrieving the country by something like a country code?
No need of knowing the exact GPS position - the country is sufficient
I first thought of using the time zone, but actually I need more information than that since it makes a difference if the location is New York or Lima.
The background of the question: I have an application that uses temperature values, and I'd like to set the default unit either to Celsius or Fahrenheit, depending on whether the location is US or outside
/**
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
* #param context Context reference to get the TelephonyManager instance from
* #return country code or null
*/
public static String getUserCountry(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US);
}
else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
String networkCountry = tm.getNetworkCountryIso();
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
return networkCountry.toLowerCase(Locale.US);
}
}
}
catch (Exception e) { }
return null;
}
This will get the country code set for the phone (phones language, NOT user location):
String locale = context.getResources().getConfiguration().locale.getCountry();
can also replace getCountry() with getISO3Country() to get a 3 letter ISO code for the country. This will get the country name:
String locale = context.getResources().getConfiguration().locale.getDisplayCountry();
This seems easier than the other methods and rely upon the localisation settings on the phone, so if a US user is abroad they probably still want Fahrenheit and this will work :)
Editors note: This solution has nothing to do with the location of the phone. It is constant. When you travel to Germany locale will NOT change. In short: locale != location.
Use this link http://ip-api.com/json ,this will provide all the information as json. From this json you can get the country easily. This site works using your current IP,it automatically detects the IP and sendback details.
Docs http://ip-api.com/docs/api:json Hope it helps.
Example json
{
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "CA",
"regionName": "California",
"city": "San Francisco",
"zip": "94105",
"lat": "37.7898",
"lon": "-122.3942",
"timezone": "America/Los_Angeles",
"isp": "Wikimedia Foundation",
"org": "Wikimedia Foundation",
"as": "AS14907 Wikimedia US network",
"query": "208.80.152.201"
}
note : As this is a 3rd party solution, only use if others didn't work.
Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
Since it is the sim code it also should not change when traveling to other countries.
First, get the LocationManager. Then, call LocationManager.getLastKnownPosition. Then create a GeoCoder and call GeoCoder.getFromLocation. Do this is in a separate thread!! This will give you a list of Address objects. Call Address.getCountryName and you got it.
Keep in mind that the last known position can be a bit stale, so if the user just crossed the border, you may not know about it for a while.
You could use getNetworkCountryIso() from TelephonyManager to get the country the phone is currently in (although apparently this is unreliable on CDMA networks).
Here is a complete solution based on the LocationManager and as fallbacks the TelephonyManager and the Network Provider's locations. I used the above answer from #Marco W. for the fallback part(great answer as itself!).
Note: the code contains PreferencesManager, this is a helper class that saves and loads data from SharedPrefrences. I'm using it to save the country to S"P, I'm only getting the country if it is empty. For my product I don't really care for all the edge cases(user travels abroad and so on).
public static String getCountry(Context context) {
String country = PreferencesManager.getInstance(context).getString(COUNTRY);
if (country != null) {
return country;
}
LocationManager locationManager = (LocationManager) PiplApp.getInstance().getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location == null) {
log.w("Couldn't get location from network and gps providers")
return
}
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses != null && !addresses.isEmpty()) {
country = addresses.get(0).getCountryName();
if (country != null) {
PreferencesManager.getInstance(context).putString(COUNTRY, country);
return country;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
country = getCountryBasedOnSimCardOrNetwork(context);
if (country != null) {
PreferencesManager.getInstance(context).putString(COUNTRY, country);
return country;
}
return null;
}
/**
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
*
* #param context Context reference to get the TelephonyManager instance from
* #return country code or null
*/
private static String getCountryBasedOnSimCardOrNetwork(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US);
} else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
String networkCountry = tm.getNetworkCountryIso();
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
return networkCountry.toLowerCase(Locale.US);
}
}
} catch (Exception e) {
}
return null;
}
For some devices, if the default language is set different (an indian can set English (US)) then
context.getResources().getConfiguration().locale.getDisplayCountry();
will give wrong value .So this method is non reliable
Also, getNetworkCountryIso() method of TelephonyManager will not work on devices which don't have SIM card (WIFI tablets).
If a device doesn't have SIM then we can use Time Zone to get the country. For countries like India, this method will work
sample code used to check the country is India or not
(Time zone id : asia/calcutta)
private void checkCountry() {
TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telMgr == null)
return;
int simState = telMgr.getSimState();
switch (simState) {
//if sim is not available then country is find out using timezone id
case TelephonyManager.SIM_STATE_ABSENT:
TimeZone tz = TimeZone.getDefault();
String timeZoneId = tz.getID();
if (timeZoneId.equalsIgnoreCase(Constants.INDIA_TIME_ZONE_ID)) {
//do something
} else {
//do something
}
break;
//if sim is available then telephony manager network country info is used
case TelephonyManager.SIM_STATE_READY:
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null) {
String countryCodeValue = tm.getNetworkCountryIso();
//check if the network country code is "in"
if (countryCodeValue.equalsIgnoreCase(Constants.NETWORK_INDIA_CODE)) {
//do something
}
else {
//do something
}
}
break;
}
}
String locale = context.getResources().getConfiguration().locale.getCountry();
Is deprecated. Use this instead:
Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locale = context.getResources().getConfiguration().getLocales().get(0);
} else {
locale = context.getResources().getConfiguration().locale;
}
Java (which is what Android uses) allows for one to retrieve the current TZ (Timezone) database name.
Although your question mentioned that time zones may not be specific enough, using this method, you can get the country (and even city in some cases) of the user without needing location permissions.
A sample TZ Database Name:
Europe/Zurich reveals that the user is in Switzerland, while Asia/Seoul shows that the user is in South Korea.
(the user may not be in Zurich or Seoul respectively though, maybe in other states/provinces)
Here is a list of all available TZ Database Time Zones: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
So you can get the TZ Database name using:
public String usersCountryByTzDbName() {
return ZoneId.systemDefault().getId();
}
You can map these to the countries of your choice.
The advantages of this method:
Unlike context.getResources().getConfiguration().locale.getCountry() like others have suggested, this would work regardless of the user's locale. Imagine if the user lived in Japan and set the language to en_US, you'd detect that the user is in USA instead of Japan.
Works on Wi-Fi only devices (which would not work if you used the telephony manager API)
Reference: Java 8 - tz database time zones
Note that according to this SO answer, TZ Database Time Zones may change from time to time, so you should expect new timezones that you have not previously encountered. Also, if the user happens to travel to another country, the other country would be reflected in this method.
Thanks!
I have a mobile app (both iOS and Android) and I need to translate cities name in the language of the user. I can do the translation on mobile device or on my server (running php).
As of now I managed to translate country names, here the java code that translate all possible countries in all possible languages:
import java.util.Locale;
public class ListCountry {
public static void main(String[] args) {
ListCountry obj = new ListCountry();
obj.getListOfCountries();
}
public void getListOfCountries() {
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
String[] lingue = Locale.getISOLanguages();
for (String languageCode : lingue) {
System.out.println("Country Code = " + obj.getCountry()
+ ", Country Name = " + obj.getDisplayCountry(new Locale(languageCode)) + ", language = " + (new Locale(languageCode)).getDisplayLanguage());
}
}
}
}
How can I do a similar thing but with city names? I know CLDR and ICU but I really can't figure out how to do it (or if it's even possible). If there is a nice object oriented library out there it'll be better than parsing CLDR XMLs or other source.
I prefer to do it locally (on my server or even on mobile app) instead of calling Google API, example:
http://maps.googleapis.com/maps/api/geocode/json?address=turin&language=ES
http://maps.googleapis.com/maps/api/geocode/json?address=turin&language=IT
http://maps.googleapis.com/maps/api/geocode/json?address=turin&language=EN
(question is: I guess google DB of cities name is public, where is it? is it nicely wrapped in some user friendly cross-platform library?)
Thanks for your help
I guess you're looking for a file containing all cities and its translations instead of fetch them once per city?
If so, www.geonames.org has geo-data of different types (countries, adminzones, cities) in multiple languages. Next to their API call you can also download their files directly and parse it by yourself:
At the following URL, you'll find 3 Zip-Files prefixed by "alternativeNames"
http://download.geonames.org/export/dump/
They contain - hopefully - the necessary data.
I'm working on the recurring serial number topic to provide a unique id.
I try this :
String serial = null;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serial = (String) get.invoke(c, "ro.serialno");
} catch (Exception ignored) {
}
and
StringBuilder sb = new StringBuilder();
sb.append("SERIAL ").append(android.os.Build.SERIAL).append("\n");
textReportAdmin.setText(
sb.toString());
Both gives the same value : C4F12FDD949F22F
On the box and on the sticker of my tab, the serial number is : RF2C202WYME
I work on a tab, no way to use
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei = telephonyManager.getDeviceId();
IMEI is empty in my case.
SERIAL is what I need, but I need it in clear version as displayed on the sticker upon the barcode behind the tab.
I guess it is possible as, When going in the system app, and looking at the state of the device, it is displayed in clear...
How to convert the value returned by android.os.Build.SERIAL to the human visible one ?
EDITION : I also looked in :
sb.append("PRODUCT ").append(android.os.Build.PRODUCT).append("\n");
sb.append("BOARD ").append(android.os.Build.BOARD).append("\n");
sb.append("BOOTLOADER ").append(android.os.Build.BOOTLOADER).append("\n");
sb.append("BRAND ").append(android.os.Build.BRAND).append("\n");
sb.append("CPU_ABI ").append(android.os.Build.CPU_ABI).append("\n");
sb.append("CPU_ABI2 ").append(android.os.Build.CPU_ABI2).append("\n");
sb.append("DEVICE ").append(android.os.Build.DEVICE).append("\n");
sb.append("DISPLAY ").append(android.os.Build.DISPLAY).append("\n");
sb.append("FINGERPRINT ").append(android.os.Build.FINGERPRINT).append("\n");
sb.append("HARDWARE ").append(android.os.Build.HARDWARE).append("\n");
sb.append("HOST ").append(android.os.Build.HOST).append("\n");
sb.append("ID ").append(android.os.Build.ID).append("\n");
sb.append("MANUFACTURER ").append(android.os.Build.MANUFACTURER).append("\n");
sb.append("MODEL ").append(android.os.Build.MODEL).append("\n");
sb.append("PRODUCT ").append(android.os.Build.PRODUCT).append("\n");
sb.append("RADIO ").append(android.os.Build.RADIO).append("\n");
sb.append("SERIAL ").append(android.os.Build.SERIAL).append("\n");
sb.append("TAGS ").append(android.os.Build.TAGS).append("\n");
sb.append("TIME ").append(android.os.Build.TIME).append("\n");
sb.append("TYPE ").append(android.os.Build.TYPE).append("\n");
sb.append("USER ").append(android.os.Build.USER).append("\n");
nowhere, I get the serialnumber as on the sticker, while it can be possible to be found as ,the system itself is able to display it in "Parameters", "About", "State" (I don't know the words in english, I have a french tab, and it is "Paramètres", "A propos de", "Etat" and then "Serial Number", the clear version, as on the sticker.
Have you tried this?
String serial = null;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serial = (String) get.invoke(c, "ril.serialnumber");
} catch (Exception ignored) {
}
If you want to get the serial number as shown on the back of the device and if you are using the Samsung Galaxy Tab then why not use the 'ril.serialnumber' property
Items changed to what your device should show:
$ adb shell getprop | grep serial
[ril.serialnumber]: [RF2C202WYME]
[ro.boot.serialno]: [c4f12fdd949f22f]
[ro.serialno]: [c4f12fdd949f22f]
Pre-jellybean 'ro.boot.serialno' didn't exist
On many devices there is information displayed in the Settings --> About activity that is non-standard and is not available from any standard Android API. For example, the FCC ID is sometimes displayed there but is not available to apps.
Also, there is no requirement that the serial number available through the API's be the product's 'real' serial number (i.e. the one on the package). Just that it be unique.
So, I think there is no way to do what you want (read the serial number that is on the box and in the about activity) other then look through that product's source code (if available) and see if there is a way to get that info for that particular product or manufacturer.
you should use
sys.serialnumber ,some devices have ril.serialnumber and some have sys.serialnumber ,so you should try sys one
I am converting IP address in to its corresponding number. Now I want to know the location details i.e. long and lat, time zone etc. Is it possible in Java. Do i have to use some external jar for database ?
IP addresses themselves don't have location info. However a number of databases/services exist that have this mapping.
See this blog entry for a number of different options. There are a number of APIs and databases to connect to for this, and you have the option of downloading such info locally to avoid remote lookups.
So as others have correctly pointed out an IP address does not contain any of this 'metadata' about location. You will need to either rely on a third party to get this information, retrieve this information yourself, or go without it. Writing the library to scrape that information should be possible in Java.
ipAddress = request.getRemoteAddr();
GeoLocation gl = new GeoLocation();
gl.GetGeoLocationByIP(ipAddress);
String country = gl.Country;
refer
For getting location from IP address you have to buy the IP databases
where they will periodically update the IP table.
However if you want, you can get the location details viz city,region,country,longitude,latitude from request header.
It's only available for GAE user.
For more details go through
GAE ReleaseNotes
public static HashMap<String, Object> getLocationDetails(HttpServletRequest request)
{
HashMap<String, Object> locationMap = null;
String country = "",city="",region="",latitude="",longitude="",temp="",state="",title="",address="",zip="";
boolean primary = true;
try
{
locationMap = new HashMap<String, Object>();
country = request.getHeader("X-AppEngine-Country");
region = request.getHeader("X-AppEngine-Region");
city = request.getHeader("X-AppEngine-City");
temp = request.getHeader("X-AppEngine-CityLatLong");
latitude = (temp.split(","))[0];
longitude = (temp.split(","))[1];
log.info("country>>"+country+"region>>"+region+"city>>"+city+"temp>>"+temp+"latitude>>"+latitude+"longitude>>"+longitude);
locationMap.put("city" , city);
locationMap.put("state" , region);
locationMap.put("country" , country);
locationMap.put("latitude" , latitude);
locationMap.put("longitude" , longitude);
log.info("locationMap==>"+locationMap);
}catch (Exception e)
{
log.log(Level.SEVERE,"Exception while getting location"+e.getMessage(),e);
}
return locationMap;
}
How to get Android device name? I am using HTC desire. When I connected it via HTC Sync the software is displaying the Name 'HTC Smith' . I would like to fetch this name via code.
How is this possible in Android?
In order to get Android device name you have to add only a single line of code:
android.os.Build.MODEL;
Found here: getting-android-device-name
You can see answers at here Get Android Phone Model Programmatically
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);
}
}
I solved this by getting the Bluetooth name, but not from the BluetoothAdapter (that needs Bluetooth permission).
Here's the code:
Settings.Secure.getString(getContentResolver(), "bluetooth_name");
No extra permissions needed.
On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL could be "SM-G920F", "SM-G920I", or "SM-G920W8".
I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:
AndroidDeviceNames Library on Github
If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:
/** 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;
String phrase = "";
for (char c : arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase += Character.toUpperCase(c);
capitalizeNext = false;
continue;
} else if (Character.isWhitespace(c)) {
capitalizeNext = true;
}
phrase += c;
}
return phrase;
}
Example from my Verizon HTC One M8:
// using method from above
System.out.println(getDeviceName());
// Using https://github.com/jaredrummler/AndroidDeviceNames
System.out.println(DeviceName.getDeviceName());
Result:
HTC6525LVW
HTC One (M8)
Try it. You can get Device Name through Bluetooth.
Hope it will help you
public String getPhoneName() {
BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
String deviceName = myDevice.getName();
return deviceName;
}
You can use:
From android doc:
MANUFACTURER:
String MANUFACTURER
The manufacturer of the product/hardware.
MODEL:
String MODEL
The end-user-visible name for the end product.
DEVICE:
String DEVICE
The name of the industrial design.
As a example:
String deviceName = android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL;
//to add to textview
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(deviceName);
Furthermore, their is lot of attribute in Build class that you can use, like:
os.android.Build.BOARD
os.android.Build.BRAND
os.android.Build.BOOTLOADER
os.android.Build.DISPLAY
os.android.Build.CPU_ABI
os.android.Build.PRODUCT
os.android.Build.HARDWARE
os.android.Build.ID
Also their is other ways you can get device name without using Build class(through the bluetooth).
Following works for me.
String deviceName = Settings.Global.getString(.getContentResolver(), Settings.Global.DEVICE_NAME);
I don't think so its duplicate answer. The above ppl are talking about Setting Secure, for me setting secure is giving null, if i use setting global it works. Thanks anyways.
universal way to get user defined DeviceName working for almost all devices and not requiring any permissions
String userDeviceName = Settings.Global.getString(getContentResolver(), Settings.Global.DEVICE_NAME);
if(userDeviceName == null)
userDeviceName = Settings.Secure.getString(getContentResolver(), "bluetooth_name");
Try this code. You get android device name.
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return model;
}
return manufacturer + " " + model;
}
#hbhakhra's answer will do.
If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)
You will find:
DEVICE - A value chosen by the device implementer containing the
development name or code name identifying the configuration of the
hardware features and industrial design of the device. The value of
this field MUST be encodable as 7-bit ASCII and match the regular
expression “^[a-zA-Z0-9_-]+$”.
MODEL - A value chosen by the device implementer containing the name
of the device as known to the end user. This SHOULD be the same name
under which the device is marketed and sold to end users. There are no
requirements on the specific format of this field, except that it MUST
NOT be null or the empty string ("").
MANUFACTURER - The trade name of the Original Equipment Manufacturer
(OEM) of the product. There are no requirements on the specific format
of this field, except that it MUST NOT be null or the empty string
("").
UPDATE
You could retrieve the device from buildprop easitly.
static String GetDeviceName() {
Process p;
String propvalue = "";
try {
p = new ProcessBuilder("/system/bin/getprop", "ro.semc.product.name").redirectErrorStream(true).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
propvalue = line;
}
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return propvalue;
}
But keep in mind, this doesn't work on some devices.
Simply use
BluetoothAdapter.getDefaultAdapter().getName()
static String getDeviceName() {
try {
Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
Method getMethod = systemPropertiesClass.getMethod("get", String.class);
Object object = new Object();
Object obj = getMethod.invoke(object, "ro.product.device");
return (obj == null ? "" : (String) obj);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
you can get 'idol3' by this way.
Tried These libraries but nothing worked according to my expectation and was giving absolutely wrong names.
So i created this library myself using the same data.
Here is the link
AndroidPhoneNamesFinder
To use this library just add this for implementation
implementation 'com.github.aishik212:AndroidPhoneNamesFinder:v1.0.2'
Then use the following kotlin code
DeviceNameFinder.getPhoneValues(this, object : DeviceDetailsListener
{
override fun details(doQuery: DeviceDetailsModel?)
{
super.details(doQuery)
Log.d(TAG, "details: "+doQuery?.calculatedName)
}
})
These are the values you will get from DeviceDetailsModel
val brand: String? #This is the brandName of the Device
val commonName: String?, #This is the most common Name of the Device
val codeName: String?, #This is the codeName of the Device
val modelName: String?, #This is the another uncommon Name of the Device
val calculatedName: String?, #This is the special name that this library tries to create from the above data.
Example of Android Emulator -
brand=Google
commonName=Google Android Emulator
codeName=generic_x86_arm
modelName=sdk_gphone_x86
calculatedName=Google Android Emulator
Within the GNU/Linux environment of Android, e.g., via Termux UNIX shell on a non-root device, it's available through the /system/bin/getprop command, whereas the meaning of each value is explained in Build.java within Android (also at googlesource):
% /system/bin/getprop | fgrep ro.product | tail -3
[ro.product.manufacturer]: [Google]
[ro.product.model]: [Pixel 2 XL]
[ro.product.name]: [taimen]
% /system/bin/getprop ro.product.model
Pixel 2 XL
% /system/bin/getprop ro.product.model | tr ' ' _
Pixel_2_XL
For example, it can be set as the pane_title for the status-right within tmux like so:
tmux select-pane -T "$(getprop ro.product.model)"
Gets an Android system property, or lists them all
adb shell getprop >prop_list.txt
Find your device name in prop_list.txt to get the prop name
e.g. my device name is ro.oppo.market.name
Get oppo.market Operator
adb shell getprop ro.oppo.market.name
My case on windows as follows
D:\winusr\adbl
λ *adb shell getprop ro.oppo.market.name*
OPPO R17