Showing posts with label Android code sample: general info. Show all posts
Showing posts with label Android code sample: general info. Show all posts

Thursday, March 7, 2019

Get targetSdkVersion, minSdkVersion, versionName and versionCode at runtime

We can retrieve targetSdkVersion, minSdkVersion, versionName and versionCode from PackageInfo and ApplicationInfo.


Java code:
package com.blogspot.android_er.androidgetmodelinfo;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvInfo, tvSdkInfo;
        tvInfo = (TextView)findViewById(R.id.info);
        tvSdkInfo = (TextView)findViewById(R.id.sdkinfo);

        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        String release = Build.VERSION.RELEASE;;

        tvInfo.setText(
                manufacturer + "\n"
                + model + "\n"
                + "Android: " + release + "\n");

        PackageManager packageManager = getPackageManager();
        String packageName = getPackageName();
        int targetSdkVersion, minSdkVersion;
        int versionCode;
        String versionName;
        try {
            PackageInfo packageInfo =
                    packageManager.getPackageInfo(packageName, 0);

            /*
            versionCode was deprecated in API level 28.
            Use getLongVersionCode() instead, which includes both this
            and the additional versionCodeMajor attribute. The version
            number of this package, as specified by the <manifest>
            tag's versionCode attribute.
             */
            versionCode = packageInfo.versionCode;
            versionName = packageInfo.versionName;

            ApplicationInfo applicationInfo = packageInfo.applicationInfo;

            /*
            targetSdkVersion added in API level 4
            minSdkVersion added in API level 24
             */
            targetSdkVersion = applicationInfo.targetSdkVersion;
            minSdkVersion = applicationInfo.minSdkVersion;

            tvSdkInfo.setText("targetSdkVersion = " + targetSdkVersion + "\n"
                            + "minSdkVersion = " + minSdkVersion + "\n"
                            + "versionCode: " + versionCode + "\n"
                            + "versionName: " + versionName);


        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    "NameNotFoundException: " + e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }



    }
}



Layout XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/addr"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="android-er.blogspot.com"
        android:textSize="20dp"
        android:textStyle="italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get device Model info"
        android:textSize="24dp"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/addr" />
    <TextView
        android:id="@+id/info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24dp"
        android:textColor="#D00000"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/title"/>
    <TextView
        android:id="@+id/sdkinfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24dp"
        android:textColor="#0000D0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/info"/>

</android.support.constraint.ConstraintLayout>

Get manufacturer, model and OS version of your Android devices


android.os.Build provide various information about the current build the devices, extracted from system properties. here is a simple example to get the manufacturer and model of the device, and the version of the Android.

Java code:
package com.blogspot.android_er.androidgetmodelinfo;

import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvInfo;
        tvInfo = (TextView)findViewById(R.id.info);

        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        String release = Build.VERSION.RELEASE;;

        tvInfo.setText(
                manufacturer + "\n"
                + model + "\n"
                + "Android: " + release + "\n");

    }
}


layout XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/addr"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="android-er.blogspot.com"
        android:textSize="20dp"
        android:textStyle="italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get device Model info"
        android:textSize="24dp"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/addr" />
    <TextView
        android:id="@+id/info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24dp"
        android:textColor="#D00000"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/title"/>

</android.support.constraint.ConstraintLayout>

Tested on:
Samsung Galaxy A9, SM-A9000
Xiaomi's Redmi Note 4

Next:
Get targetSdkVersion, minSdkVersion, versionName and versionCode at runtime

Monday, February 13, 2017

Get the height of status bar

Example to get the height of status bar, in size of pixel.



package com.blogspot.android_er.androidgetstatusbarheight;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getStatusBarHeight();
    }

    private int getStatusBarHeight() {
        int height;

        Resources myResources = getResources();
        int idStatusBarHeight = myResources.getIdentifier(
                "status_bar_height", "dimen", "android");
        if (idStatusBarHeight > 0) {
            height = getResources().getDimensionPixelSize(idStatusBarHeight);
            Toast.makeText(this,
                    "Status Bar Height = " + height,
                    Toast.LENGTH_LONG).show();
        }else{
            height = 0;
            Toast.makeText(this,
                    "Resources NOT found",
                    Toast.LENGTH_LONG).show();
        }

        return height;
    }
}


Tuesday, September 1, 2015

RecyclerView + CardView example - list system properties using System.getProperties()

My former example show how to "Retrieve system properties using System.getProperties()", here we are going to list the Properties on RecyclerView + CardView, similar to another example "RecyclerView + CardView example with ImageView - list available Drawable".


To use RecyclerView + CardView, we have to "Add Support Libraries of RecyclerView, CardView to Android Studio Project".

layout/layout_cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="5sp"
    card_view:cardElevation="5sp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/item_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14dp" />

        <TextView
            android:id="@+id/item_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:textSize="16dp" />

    </LinearLayout>

</android.support.v7.widget.CardView>


com.blogspot.android_er.androidproperties.MyRecyclerViewAdapter.java
package com.blogspot.android_er.androidproperties;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MyRecyclerViewAdapter extends
        RecyclerView.Adapter<MyRecyclerViewAdapter.ItemHolder>{

    private List<String> itemsName;
    private List<String> itemsValue;
    private LayoutInflater layoutInflater;
    private Context context;

    public MyRecyclerViewAdapter(Context context){
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        itemsName = new ArrayList<String>();
        itemsValue = new ArrayList<String>();
    }

    @Override
    public ItemHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        CardView itemCardView =
                (CardView)layoutInflater.inflate(R.layout.layout_cardview, viewGroup, false);
        return new ItemHolder(itemCardView, this);
    }

    @Override
    public void onBindViewHolder(ItemHolder itemHolder, int i) {
        itemHolder.setItemName(itemsName.get(i));
        String value = itemsValue.get(i);
        itemHolder.setItemValue(String.valueOf(value));
    }

    @Override
    public int getItemCount() {
        return itemsName.size();
    }

    public void add(int location, String iName, String iValue){
        itemsName.add(location, iName);
        itemsValue.add(location, iValue);
        notifyItemInserted(location);
    }

    public void remove(int location){
        if(location >= itemsName.size())
            return;

        itemsName.remove(location);
        itemsValue.remove(location);
        notifyItemRemoved(location);
    }

    public static class ItemHolder extends RecyclerView.ViewHolder{

        private MyRecyclerViewAdapter parent;
        private CardView cardView;
        TextView textItemName;
        TextView textItemValue;

        public ItemHolder(CardView cView, MyRecyclerViewAdapter parent) {
            super(cView);
            cardView = cView;
            this.parent = parent;
            textItemName = (TextView) cardView.findViewById(R.id.item_name);
            textItemValue = (TextView) cardView.findViewById(R.id.item_value);
        }

        public void setItemName(CharSequence name){
            textItemName.setText(name);
        }

        public CharSequence getItemName(){
            return textItemName.getText();
        }

        public void setItemValue(CharSequence val){
            textItemValue.setText(val);
        }

        public CharSequence getItemValue(){
            return textItemValue.getText();
        }
    }
}


layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myrecyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


com.blogspot.android_er.androidproperties.MainActivity.java
package com.blogspot.android_er.androidproperties;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.Enumeration;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecyclerView;
    LinearLayoutManager linearLayoutManager;
    private MyRecyclerViewAdapter myRecyclerViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myRecyclerView = (RecyclerView)findViewById(R.id.myrecyclerview);

        linearLayoutManager =
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        myRecyclerViewAdapter = new MyRecyclerViewAdapter(this);
        myRecyclerView.setAdapter(myRecyclerViewAdapter);
        myRecyclerView.setLayoutManager(linearLayoutManager);

        prepareItems();
    }

    private void prepareItems(){

        Properties properties = System.getProperties();
        Enumeration<String> prop =
                (Enumeration<String>) properties.propertyNames();

        while(prop.hasMoreElements()){
            String propName = prop.nextElement();

            myRecyclerViewAdapter.add(
                    myRecyclerViewAdapter.getItemCount(),
                    propName,
                    System.getProperty(propName));
        }
    }
}


Tested on Nexus 7 running Android 5.1.1

Tested on Android Emulator running Android 6

download filesDownload the files (Android Studio Format) .

~ More step-by-step examples of RecyclerView + CardView.

Sunday, August 30, 2015

Retrieve system properties using System.getProperties()

getProperties() method of java.lang.System returns the system properties. Here is a example to retrieve system properties using System.getProperties().


package com.blogspot.android_er.androidsystemproperties;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.Enumeration;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView info = (TextView)findViewById(R.id.info);

        Properties properties = System.getProperties();
        info.append(properties.toString());
        info.append("\n----------\n\n");

        Enumeration<String> prop =
                (Enumeration<String>) properties.propertyNames();

        while(prop.hasMoreElements()){
            String propName = prop.nextElement();
            info.append(propName + " : \n" +
                    System.getProperty(propName) + "\n\n");

        }
    }

}


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>


Wednesday, August 19, 2015

List all available drawable and its value

Example to list all available Drawable and its value:


package com.example.androidlistdrawable;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.lang.reflect.Field;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView info = (TextView)findViewById(R.id.info);

        Field[] fieldDrawables = android.R.drawable.class.getFields();
        for(int i=0; i<fieldDrawables.length; i++){
            Field field = fieldDrawables[i];
            info.append("R.drawable." + field.getName() + " :\n");
            info.append(field.toString() + "\n");

            try {
                int value = (int) field.get(fieldDrawables);
                info.append("value = " + value + "\n");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            info.append("\n");

        }
    }

}


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <TextView
            android:id="@+id/info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>



Next:
- RecyclerView + CardView example - list available Drawable

Thursday, February 13, 2014

cat /system/etc/permissions/handheld_core_hardware.xml on your Android device

This example simple display the file /system/etc/permissions/handheld_core_hardware.xml on my Android device.

handheld_core_hardware.xml of HTC One X
For what:
In my old post "List attached USB devices in USB Host mode", Anonymous commented have to check the xml file "/system/etc/permissions/handheld_core_hardware.xml" for < feature name="android.hardware.usb.host" />. Coincidentally I have a post to "Run Linux command with ProcessBuilder", so I modify it to display the content of "/system/etc/permissions/handheld_core_hardware.xml" using Linux command "cat".

package com.example.androidruncommand;

import java.io.IOException;
import java.io.InputStream;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView textCommand, textReturn;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textCommand = (TextView) findViewById(R.id.textcommand);
  textReturn = (TextView) findViewById(R.id.textreturn);

  String[] command = { "cat", "/system/etc/permissions/handheld_core_hardware.xml" };
  StringBuilder cmdReturn = new StringBuilder();
  
  String stringCommand = "$ ";
  for(int i=0; i<command.length; i++){
   stringCommand += command[i] + " ";
  }
  textCommand.setText(stringCommand);

  try {
   ProcessBuilder processBuilder = new ProcessBuilder(command);
   Process process = processBuilder.start();

   InputStream inputStream = process.getInputStream();
   int c;
   while ((c = inputStream.read()) != -1) {
    cmdReturn.append((char) c);
   }

   textReturn.setText(cmdReturn.toString());

  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textcommand"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textreturn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>

Or, you can pull the file from your device using DDMS of Android Development Tools.

/system/etc/permissions/handheld_core_hardware.xml in HTC One X
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- These are the hardware components that all handheld devices
     must include. Devices with optional hardware must also include extra
     hardware files, per the comments below.

     Handheld devices include phones, mobile Internet devices (MIDs),
     Personal Media Players (PMPs), small tablets (7" or less), and similar
     devices.
-->
<permissions>
    <feature name="android.hardware.camera" />
    <feature name="android.hardware.location" />
    <feature name="android.hardware.location.network" />
    <feature name="android.hardware.sensor.compass" />
    <feature name="android.hardware.sensor.accelerometer" />
    <feature name="android.hardware.bluetooth" />
    <feature name="android.hardware.touchscreen" />
    <feature name="android.hardware.microphone" />
    <feature name="android.hardware.screen.portrait" />
    <feature name="android.hardware.screen.landscape" />
    <!-- devices with GPS must include android.hardware.location.gps.xml -->
    <!-- devices with an autofocus camera and/or flash must include either
         android.hardware.camera.autofocus.xml or 
         android.hardware.camera.autofocus-flash.xml -->
    <!-- devices with a front facing camera must include
         android.hardware.camera.front.xml -->
    <!-- devices with WiFi must also include android.hardware.wifi.xml -->
    <!-- devices that support multitouch must include the most appropriate one
         of these files:

         If only partial (non-independent) pointers are supported:
         android.hardware.touchscreen.multitouch.xml

         If up to 4 independently tracked pointers are supported:
         include android.hardware.touchscreen.multitouch.distinct.xml

         If 5 or more independently tracked pointers are supported:
         include android.hardware.touchscreen.multitouch.jazzhand.xml

         ONLY ONE of the above should be included. -->
    <!-- devices with an ambient light sensor must also include
         android.hardware.sensor.light.xml -->
    <!-- devices with a proximity sensor must also include
         android.hardware.sensor.proximity.xml -->
    <!-- GSM phones must also include android.hardware.telephony.gsm.xml -->
    <!-- CDMA phones must also include android.hardware.telephony.cdma.xml -->
    <!-- Devices that have low-latency audio stacks suitable for apps like
         VoIP may include android.hardware.audio.low_latency.xml. ONLY apps
         that meet the requirements specified in the CDD may include this. -->
</permissions>

But...I can't find < feature name="android.hardware.usb.host" /> in my handheld_core_hardware.xml. But it support USB Host mode actually.

Monday, December 30, 2013

Get the Android version of device

The static final int Build.VERSION.SDK_INT store user-visible SDK version of the framework; its possible values are defined in Build.VERSION_CODES.

This exercise use Android's SparseArrays to store SDK_INT-Build.VERSION_CODES pairs. SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping.


Get the Android version of device
Get the Android version of device

package com.example.androidversion;

import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.SparseArray;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

 static SparseArray<String> arrayVC = new SparseArray<String>();
    static {
        arrayVC.append(VERSION_CODES.BASE, "The original, first, version of Android.");
        arrayVC.append(VERSION_CODES.BASE_1_1, "First Android update, officially called 1.1");
        arrayVC.append(VERSION_CODES.CUPCAKE, "Android 1.5");
        arrayVC.append(VERSION_CODES.CUR_DEVELOPMENT, "Magic version number...");
        arrayVC.append(VERSION_CODES.DONUT, "Android 1.6");
        arrayVC.append(VERSION_CODES.ECLAIR, "Android 2.0");
        arrayVC.append(VERSION_CODES.ECLAIR_0_1, "Android 2.0.1");
        arrayVC.append(VERSION_CODES.ECLAIR_MR1, "Android 2.1");
        arrayVC.append(VERSION_CODES.FROYO, "Android 2.2");
        arrayVC.append(VERSION_CODES.GINGERBREAD,"Android 2.3");
        arrayVC.append(VERSION_CODES.GINGERBREAD_MR1, "Android 2.3.3");
        arrayVC.append(VERSION_CODES.HONEYCOMB, "Android 3.0");
        arrayVC.append(VERSION_CODES.HONEYCOMB_MR1, "Android 3.1");
        arrayVC.append(VERSION_CODES.HONEYCOMB_MR2, "Android 3.2");
        arrayVC.append(VERSION_CODES.ICE_CREAM_SANDWICH,"Android 4.0");
        arrayVC.append(VERSION_CODES.ICE_CREAM_SANDWICH_MR1,"Android 4.0.3");
        arrayVC.append(VERSION_CODES.JELLY_BEAN, "Android 4.1");
        arrayVC.append(VERSION_CODES.JELLY_BEAN_MR1, "Android 4.2");
        arrayVC.append(VERSION_CODES.JELLY_BEAN_MR2, "Android 4.3");
        arrayVC.append(VERSION_CODES.KITKAT, "Android 4.4");
    }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  
  TextView textView = new TextView(this);
  setContentView(textView);
  
  int version = Build.VERSION.SDK_INT;
  String BuildVersion = arrayVC.get(version, "unknown");
  
  textView.setText(BuildVersion);
 }

}