Android java get phone model

Android & Kotlin Examples code

Android kotlin tutorials and examples code for android apps developers.

how to get device model name programmatically in Android Kotlin

Android.os.Build.MODEL

public static final String MODEL, Added in API level 1
The end-user-visible name for the end product.

Android java function getDeviceName() code:
Utils.java :

import android.os.Build
class K_utils <
companion object <
@JvmStatic
fun getPhoneDeviceName():String <
val model = Build.MODEL // returns model name
return model;
>

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.example.espl.myapplication.K_utils.Companion.getPhoneDeviceName
import com.example.espl.myapplication.Utils.getDeviceName

class MainActivity : AppCompatActivity() <
override fun onCreate(savedInstanceState: Bundle?) <
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val tv_java_utils_output: TextView = findViewById(R.id.tv_java_utils_output) as TextView
//using java function getDeviceName()
tv_java_utils_output.text = «Using java Function::»+getDeviceName();

//using kotlin function getPhoneDeviceName()
val tv_kotlin_utils_output: TextView = findViewById(R.id.tv_kotlin_utils_output) as TextView
tv_kotlin_utils_output.text =»Using Kotlin version of Function::»+getPhoneDeviceName();
>
>

xmlns:android=»http://schemas.android.com/apk/res/android»
xmlns:tools=»http://schemas.android.com/tools»
xmlns:app=»http://schemas.android.com/apk/res-auto»
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:gravity=»center_horizontal»
android:orientation=»vertical»
tools:context=».MainActivity»>

android:gravity=»center_vertical|center_horizontal»
android:layout_width=»wrap_content»
android:id=»@+id/tv_java_utils_output»
android:layout_height=»wrap_content»
android:padding=»10dp»
android:background=»@color/colorGray»
android:layout_margin=»10dp»
android:textColor=»@color/colorPrimary»
app:layout_constraintBottom_toBottomOf=»parent»
app:layout_constraintLeft_toLeftOf=»parent»
app:layout_constraintRight_toRightOf=»parent»
app:layout_constraintTop_toTopOf=»parent»/>

android:padding=»10dp»
android:layout_margin=»10dp»
android:textColor=»@color/colorPrimary»
android:id=»@+id/tv_kotlin_utils_output»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:background=»@color/colorGray»
app:layout_constraintBottom_toBottomOf=»parent»
app:layout_constraintLeft_toLeftOf=»parent»
app:layout_constraintRight_toRightOf=»parent»
app:layout_constraintTop_toTopOf=»parent»/>

Output on HTC Desire 620G dual sim phone device model:

get android mobile phone model name programmatically — Kotlin

android.os.Build.MANUFACTURER returns public static final String MANUFACTURER — Added in API level 4
The manufacturer of the product/hardware.

Similarly to get the device manufacturer name in android programmatically use below code that returns a manufacturer name as a string.

Источник

Основы Contacts API в Android

Введение

Начиная с версии 5 API Android SDK интерфейс работы с контактами изменился, а основной контент провайдер Contacts и все его составляющие получили черную метку @Deprecated. Теперь за работу с контактами отвечает провайдер ContactsContract. Эти изменения связаны с изменением структуры хранения контактов, более адаптированной для Android устройств, которым требуется хранить контакты из множества разных источников и предоставлять их пользователю как единую сущность. Ведь сегодня, определенный контакт на нашем мобильном устройстве это не только имя и номер телефона, мы можем захотеть сохранить eMail, Im, Twitter, Facebook аккаунт определенного человека, и при этом, мы не хотим чтобы у нас нас появилось миллион непонятных записей. Поэтому новый Contacts API позволяет Android агрегировать похожие контакты и представлять их пользователю в одной записи, а также связывать контакт с разного рода данными.

Структура данных

На устройстве основная информация о контактах хранится в трех таблицах, на деле их там конечно больше, но мы рассмотрим основные три: contacts, raw_contacts и data. Чтобы было более наглядно я набросал простую схему в Dia.

В таблице contacts хранятся агрегированные контакты, каждая запись в этой таблице представляет собой пользовательский контакт (единую сущность) – объединение одного или нескольких сырых (необработанных) контактов из таблицы raw_contacts. Как видно на схеме, связь между этими таблицами один ко многим (1-N). Одна запись в таблице raw_contacts представляет собой так называемый сырой контакт. Сырой контакт, на языке Android, означает какой-то конкретный набор данных для определенного контакта. Но сами основные данные в этой таблице не хранятся, они хранятся в таблице data, и связь между raw_contacts и data также один ко многим. В таблице data хранятся непосредственно данные. Причем каждая строка этой таблицы это набор данных определенного типа для контакта. Какого именно типа данные хранятся в строке определяется столбцом mimetype_id, в котором содержится id типов данных определенных в таблице mimetype(например vnd.android.cursor.item/name, vnd.android.cursor.item/photo). Теперь разберемся во всем по подробней и с примерами.

Читайте также:  Морской бой ссср android

Работаем с контактами

Хорошо, допустим мы хотим добавить контакт (Robert Smith, моб.тел. 11-22-33), как нам это сделать? В таблицу contacts мы сами, явно, не можем добавить контакт, так как система сама формирует эту таблицу агрегируя похожие raw_contacts. Идентичность контактов система определяет в основном по имени (одинаковые имена, фамилии и т.п.), но и по другим критериям, каким именно и как ими управлять можно посмотреть в документации. То есть, если мы добавим raw_contact нашего Роберта (Robert Smith) и свяжем его с данными типа vnd.cursor.android.item/phone, а потом у нас появится “похожий”, для системы, Robert Smith связанный с данными типа vnd.cursor.android.item/email и еще один с данными типа vnd.cursor.android.item/photo, то у нас в контактах будет один Robert Smith с фотографией, мобильным и email’ом.

Теперь попробуем переложить это на код. За таблицы и их поля отвечает, как я уже говорил, класс ContactsContract и его внутренние классы и интерфейсы. Например интерфейсом к таблице raw_contacts является класс ContactsContract.RawContacts, а за таблицу data класс ContactsContract.Data. Будьте внимательны когда изучаете их константы – интерфейсы к столбцам – обращайте внимание на метки read/write и read only.

Из написанного выше следует, что для начала, мы должны добавить сырой контакт, а потом связывать его с данными. Добавить пустой контакт можно так:

В контактах у вас должен появиться пустой (Unknown) контакт, ни с чем не связанный. Добавим ему имя. Чтобы это сделать, мы должны связать наш новый контакт с новыми данными используя его id, который можно достать из прошлого запроса. Основные интерфейсы к полям таблицы данных содержаться в классе-контейнере ContactsContract.CommonDataKinds и его внутренних классах и интерфейсах. Например, сейчас нам понадобиться
класс ContactsContract.CommonDataKinds.StrucruredName содержащий нужные нам константы для добавления имени, а также константу MIME типа, которой мы пометим наше поле в таблице данных.

Если мы добавим контакт таким образом, то в списке контактов у нас появиться Robert Smith. Теперь идем дальше, добавим нашему контакту еще и телефон. Для этого нам понадобиться класс ContactsContract.CommonDataKinds.Phone, который является интерфейсом к данным телефонного номера.

Теперь в контактах у нас есть Robert Smith которому можно позвонить. Но вот так добавлять контакт и данные к нему, в несколько запросов, дорого и накладно. Поэтому существует класс ContentProviderOperation, который позволяет построить запрос, который выполнит все наши операции за одну транзакцию. Именно им и рекомендуют пользоваться. Вот так можно добавить нашего Роберта используя ContentProviderOperation.

Вот таким образом в Android можно добавлять контакты. Будьте осторожны используя ContentProviderOperation, так как слишком большой запрос может долго выполняться. Вообще все операции лучше производить в отдельном потоке, потому, что у пользователя, например, может быть слабый телефон и много контактов.

В остальном все другие операции выполняются обычным образом, используя те провайдеры, которые вам необходимы, с некоторыми оговорками. Например, удаление контакта из таблицы contacts удалит все raw_contacts с ним связанные и т.д.

Вот так можно попробовать найти нашего Роберта в контактах:

Читайте также:  Паркур карты для android

На этом хотелось бы завершить статью, все же это были только основные сведения о Contacts API в Andoid. Я надеюсь мне удалось описать здесь основные принципы, а вся конкретика зависит от того, что вам необходимо сделать в процессе работы. Можно просто руководствоваться этими принципами и находить в официальной документации интерфейсы которые вам нужны для работы. Успехов!

Источник

How to get an Android Device Nickname

Background

On most Android devices, users have the option to set a custom device nickname to make it easier for them to identity their device. When showing a user a list of their devices, we want their custom device name to be displayed instead of the factory default value if it’s available.

Research

I searched the web and found several different methods to read the user specified device nickname on Android:

Note: #3 requires Bluetooth permission.

Results

But how do they perform on various popular Android devices? The # columns in the table below refer to the methods used to access the device nickname referenced in the ‘Research’ section above. A green check indicates that we were able to successfully read the user’s custom device nickname.

Conclusion

There is no standardized Android API to read the user specified device nickname and not all Android devices support a custom nickname. There are ways to read this data but none work on all Android devices.

Although we didn’t find a consistent way to access the user specified device nickname, there are libraries available like AndroidDeviceNames that can provide a more readable device name than the factory set value (e.g. “sailfish”). For example, it can provide “Samsung S8+” which a user is more likely to recognize than the codename “dream2qltecan” or model number “SM-G955W”.

DISCLOSURE STATEMENT: These opinions are those of the author. Unless noted otherwise in this post, Capital One is not affiliated with, nor is it endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are the ownership of their respective owners. This article is © 2019 Capital One.

Источник

Save data in a local database using Room Part of Android Jetpack.

Apps that handle non-trivial amounts of structured data can benefit greatly from persisting that data locally. The most common use case is to cache relevant pieces of data so that when the device cannot access the network, the user can still browse that content while they are offline.

The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits:

  • Compile-time verification of SQL queries.
  • Convenience annotations that minimize repetitive and error-prone boilerplate code.
  • Streamlined database migration paths.

Because of these considerations, we highly recommend that you use Room instead of using the SQLite APIs directly.

Setup

To use Room in your app, add the following dependencies to your app’s build.gradle file:

Groovy

Kotlin

Primary components

There are three major components in Room:

  • The database class that holds the database and serves as the main access point for the underlying connection to your app’s persisted data.
  • Data entities that represent tables in your app’s database.
  • Data access objects (DAOs) that provide methods that your app can use to query, update, insert, and delete data in the database.
Читайте также:  Talisman android все открыто

The database class provides your app with instances of the DAOs associated with that database. In turn, the app can use the DAOs to retrieve data from the database as instances of the associated data entity objects. The app can also use the defined data entities to update rows from the corresponding tables, or to create new rows for insertion. Figure 1 illustrates the relationship between the different components of Room.

Figure 1. Diagram of Room library architecture.

Sample implementation

This section presents an example implementation of a Room database with a single data entity and a single DAO.

Data entity

The following code defines a User data entity. Each instance of User represents a row in a user table in the app’s database.

Kotlin

To learn more about data entities in Room, see Defining data using Room entities.

Data access object (DAO)

The following code defines a DAO called UserDao . UserDao provides the methods that the rest of the app uses to interact with data in the user table.

Kotlin

Database

The following code defines an AppDatabase class to hold the database. AppDatabase defines the database configuration and serves as the app’s main access point to the persisted data. The database class must satisfy the following conditions:

  • The class must be annotated with a @Database annotation that includes an entities array that lists all of the data entities associated with the database.
  • The class must be an abstract class that extends RoomDatabase .
  • For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.

Kotlin

Note: If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.

If your app runs in multiple processes, include enableMultiInstanceInvalidation() in your database builder invocation. That way, when you have an instance of AppDatabase in each process, you can invalidate the shared database file in one process, and this invalidation automatically propagates to the instances of AppDatabase within other processes.

Usage

After you have defined the data entity, the DAO, and the database object, you can use the following code to create an instance of the database:

Kotlin

You can then use the abstract methods from the AppDatabase to get an instance of the DAO. In turn, you can use the methods from the DAO instance to interact with the database:

Kotlin

Additional resources

To learn more about Room, see the following additional resources:

Sample

  • Android Sunflower, a gardening app that illustrates Android development best practices with Android Jetpack.
  • Tivi, a TV show tracking app that uses the latest libraries and tools.

Codelabs

Blogs

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Оцените статью