Android Development Posts

Android 11 Released: Top New Features

This is only part of what’s new, as there are over 100 features that serve app developers to further the entire Android experience. On Google's developer website, you can read about it all.

Media controls

While playing music, you can usually see a notification with music controls if you swipe down the notification drawer. However, now in Android 11, these controls are integrated into the Quick Settings menu. So, if you swipe to the top of the screen and with your Bluetooth and Wi-Fi tiles, you can see the music controls.

You can also choose which device will play music, which is accessible if you have Bluetooth earbuds or speakers connected. Drag the menu further down to see other options, such as the ability to select a song without opening the Music app.

Conversations and Bubbles

Google is finally unveiling its official implementation of the conversation bubbles. If you use Facebook Messenger on Android, you will already be familiar with this feature. This feature enables the conversation to stay in floating bubbles that can be moved around the screen and retrieved from within any application.

Google's own documentation says the section will be on "many phones," not all of them, so some manufacturers may choose to display it differently. In any case, apps will need to be updated to tell Android which notifications are conversations.

Screen recorder

Android finally has in-built screen recording. Screen recording in Android 11 is as easy as adding a quick setting tile and clicking it. Before you start recording, you can choose whether you need to record audio from your microphone or you can choose to show touch on the screen.

screen_recording_1

screen_recording_2

The new screen recorder can be accessed by tapping the 'Screen Record' tile in Quick Settings - if you don't see it on your device, press the Edit button in Quick Settings and drag the tile from the hidden options. Once you have it, just tap it to start recording.

Power button menu

Android 11 comes with a new power menu that enables you to quickly access all connected smart devices.

To reach the new menu just long-press the power button and control all connected devices like smart locks and thermostats with one click, without the need to open a lot of applications. This latest addition lets us feel like Google has finally brought smartphones to the smart home.

Notification history

Have you ever wondered which apps send the most push alerts to your phone? Did you accidentally clear the notification and aren't sure if you missed something important? If so, you'll love the new Android 11 Notification History page.

Do you ever refresh an instruction before you get a chance to read it? Right now, you don’t have to think that it was something important. Android 11 has launched Notification History which can be accessed by navigating to Settings> Apps & Notifications> Notifications> Notification History.

notification

Improved 5G Support

Android 11 includes enhanced developer support to help you reap the benefits of faster speeds and 5G networks. You can understand that when a user connects to a 5G network, they get an estimate of the connection bandwidth and check if the connection is metered.

September 21, 20213 minutesVivek BeladiyaVivek Beladiya
How to Change  App Language in Android Programmatically?

Android 7.0 (API Level 24) provides support for multilingual users, allowing users to select multiple locales in the setting. The locale object budget represents a specific geographic, political, or cultural area.

Operations that require this locale to perform a task are called locale-sensitive and use that locale to generate information for the user.

Step 1: Create A New Project & Create Resource Files

To create a new project in Android Studio.

In this step, we need to create a string resource file for the Gujarati language.Go to app > res > values > right-click > New > Value Resource File and name it as strings.

Now, we have to select the qualifier as a locale from the available list and select the language as Gujarati from the drop-down list. Below is a picture of the steps.

resource

language

Now, in this resource file, strings.xml(gu-rlN) add the code given below.

<resources>
    <string name="app_name">Change App Language</string>
    <string name="selected_language">ગુજરાતી</string>
    <string name="language">કેમ છો</string>
</resources>

And add this line to the string.xml file, which is the default for English.

<resources>
    <string name="app_name">Change App Language</string>
    <string name="selected_language">English</string>
    <string name="language">How are you</string>
</resources>

Step 2: Create The Layout File For The Application

In this step, we will create a layout for our application. Go to applications> res> Layout> activity_main.xml and add two text views, one for the message and one for the selected language, and an image view for the drop_down icon. Below is the code snippet for the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    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:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="48dp"
        android:text="Welcome To InfyOm"
        android:textAlignment="center" />

    <Button
        android:id="@+id/btnGujarati"
        android:layout_margin="16dp"
        android:background="@color/colorPrimary"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Gujarati"/>

    <Button
        android:id="@+id/btnEnglish"
        android:layout_margin="16dp"
        android:background="@color/colorPrimary"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="English"/>

</LinearLayout>

Step 3: Create LocaleHelper Class

Now, we will create a local helper class. This class has all the functions that will help to change the language at runtime. Go to app > java > package > right-click and create a new Java class and name it LocalHelper. Below is the code for the local helper class.

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

public class LocaleHelper {
        private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

        // the method is used to set the language at runtime
        public static Context setLocale(Context context, String language) {
            persist(context, language);

            // updating the language for devices above android nougat
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return updateResources(context, language);
            }
            // for devices having lower version of android os
            return updateResourcesLegacy(context, language);
        }

        private static void persist(Context context, String language) {
            SharedPreferences preferences =                       PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(SELECTED_LANGUAGE, language);
            editor.apply();
        }

        // the method is used update the language of application by creating
        // object of inbuilt Locale class and passing language argument to it
        @TargetApi(Build.VERSION_CODES.N)
        private static Context updateResources(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);

            Configuration configuration = context.getResources().getConfiguration();
            configuration.setLocale(locale);
            configuration.setLayoutDirection(locale);

            return context.createConfigurationContext(configuration);
        }

        @SuppressWarnings("deprecation")
        private static Context updateResourcesLegacy(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);

            Resources resources = context.getResources();

            Configuration configuration = resources.getConfiguration();
            configuration.locale = locale;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale);
            }

            resources.updateConfiguration(configuration, resources.getDisplayMetrics());

            return context;
        }
    }

Step 4: Working With the MainActivity.java File

In this step, we will apply Java code to switch between string.xml files to use different languages. First, we will initialize all the views and set click behavior on an Alert dialog box to choose the desired language with the help of the LocalHelper class. Below is the code is given for the MainActivity.java class.

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView messageView;
    Button btnGujarati, btnEnglish;
    Context context;
    Resources resources;

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

        messageView = (TextView) findViewById(R.id.textView);
        btnGujarati = findViewById(R.id.btnGujarati);
        btnEnglish = findViewById(R.id.btnEnglish);

        btnEnglish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "en");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });

        btnGujarati.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "hi");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });

    }
}
August 26, 20213 minutesVivek BeladiyaVivek Beladiya
How to add project as a library to Android Studio

But if you want to add another project as a library in your application. For that, you need to add that library project to your application as a module dependency.

1. Open Your Project in Android Studio.

2. You will find the two main directory name samples and others.

3. Go to Android Studio and navigate to File -> New -> Import Module -> Select the library path -> Finish.

2021-07-24-60fbb0d6a0a7c

4. Import-Module from Directory.

2021-07-24-60fbb6e95102d

5. Then right-click on the App directory -> Open Module Settings -> Dependencies -> Click on + button inside Declared Dependencies -> Module Dependency -> Select your library -> Ok.

2021-07-24-60fbb90b68dec

2021-07-24-60fbb99dd54e3

Another way to add Module Dependency

  • Open build.gradle Of the main module
dependencies {

implementation project(":sample")

}

There can be a situation when we need to modify the library code according to our requirement then in that case we can follow this method.

July 25, 20212 minutesVivek BeladiyaVivek Beladiya
Room Database in android java

Hi everyone, in this post, we will discuss Room Database in android java.

Below are all steps covered in this blog

  • How to use the Room database
  • How to add Room Database in android studio
  • Insert,Update,Delete record
  • How to pass query in Database

What is a Room?

  • The Room strong library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.

  • Normally Room databases are fast created and have good performance like reading, updating and deleting records. Room Database makes everything easy and fast

  • Room Database more detail open this link: https://developer.android.com/training/data-storage/room/

Components of Room Here room have main 3 components

Entity:

  • Instead of creating the SQLite table, we will create the Entity. An entity is nothing but a model class annotated with @Entity. The variables of this class are our columns, and the class is our table.

Database:

  • It is an abstract class where we define all our entities.

DAO:

  • Stands for Data Access Objects. It is an interface that defines all the operations that we need to perform in our database.

Demo App Create

  • First, we create a new project in android studio.
  • Name of my project "Room DataBase"

Adding Dependencies

  • Add needed dependencies for the room database.
  • Android studio in this file add dependencies "build.gradle".
  • See the below image and add the latest version room database replace here "$room_version" add original version

First, we will create DAO class:

  • This DAO class-main work intermediary between the user and database. All performed operations are defined here.
  • Below create StudentDao class
@Dao
public interface StudentDao {

@Query("SELECT * FROM Student")
List<Student> getAll();

@Insert
void insert(Student student);

@Update
void updateTask(Student student);

@Delete
void deleteTask(Student student);
}

Nowhere explain all components of StudentDao Class

  • Compulsory add class upper "@Dao" keyword
  • Three methods create insert, update, delete
  • Most important thing here is "@Query"

What is a Query?

  • Using query to get database existing record.
  • @Query("SELECT * FROM Student") this query gets all student records.
  • But the user wants to get only the standard "5" student record and only get how to pass a query?
    @Query("SELECT * FROM STUDENT where std = :std")

    List<Student> dataCheck(String std);
  • Here "std" id table field name
  • Call this method "data check(String std)" pass a string in "5" and database in getting only 5 stander student record
  • So this concept use the query parameter

Second steps create student model class

@Entity(tableName = "student")
public class Student implements Serializable {

@PrimaryKey(autoGenerate  = true)
private int id;

@ColumnInfo(name = "std")
private int std;

@ColumnInfo(name = "name")
private String name;

public int getId() {
    return id;
  }

public void setId(int id) {
    this.id = id;
  }

public int getStd() {
    return std;
  }

public void setStd(int std) {
    this.std = std;
  }

public String getName() {
    return name;
  }

public void setName(String name) {
    this.name = name;
  }
}
  • PrimaryKey: auto increment values
  • tableName : user wants to set the table name
  • ColumnInfo: give the table in columns name

Third steps Create Database class:

@Database(entities = {Student.class}, version = 1)
public abstract class AppDatabase extends     RoomDatabase {
public abstract Student studentDao();
}
  • User wants to add multiple tables how can add like that:

@Database(entities = {Student.class,Abc.class,Xyz.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract Student studentDao(); }

  • To create a new model class like Abc.class and Xyz.class etc same method.

Fourth step inserts, update and delete records create separate method:

 public class InsertUpdateDeletRecord {

    private String DB_NAME = "db_task";

    private Student Student;
    public studentRepository(Context context) {
        Student = Room.databaseBuilder(context, Student.class, DB_NAME).build();
    }

    public void insertTask(String std,String name) {

        insertTask(std, name);
    }

    public void insertTask(String std,String name) {
        Student student = new Student();
        student.setstd(std);
        student.setname(name);

        insertTask(student);
    }

    public void insertTask(final Student student) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().insertTask(student);
                return null;
            }
        }.execute();
    }

    public void updateTask(final Student student) {
        student.setModifiedAt(AppUtils.getCurrentDateTime());

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().updateTask(student);
                return null;
            }
        }.execute();
    }

    public void deleteTask(final int id) {
        final LiveData<student> task = getTask(id);
        if(task != null) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    Student.daoAccess().deleteTask(task.getValue());
                    return null;
                }
            }.execute();
        }
    }

    public void deleteTask(final student student) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Student.daoAccess().deleteTask(student);
                return null;
            }
        }.execute();
    }

 }

Sample Implementation of basic CRUD operations using ROOM

Insert:

 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext( ));
 String std = "5";
 String name = Android";
 insertUpdateDeletRecord.insertTask(title, 
 description);

Update:

 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext( ));
 Student student = 
 insertUpdateDeletRecord.getTask(2);
 student.setName("Java");
 student.setStd("6");
 insertUpdateDeletRecord.updateTask(student);

Update:

 InsertUpdateDeletRecord 
 insertUpdateDeletRecord = new 
 InsertUpdateDeletRecord(getApplicationContext());
 insertUpdateDeletRecord.deleteTask(3);
July 25, 20214 minutesPankaj ValaniPankaj Valani
How to integration google ad in android app. Part - 1

Dear, Friend in this blog we discussion google ad integration. Many companies work in client base & product base. Product based company in very very important ad integration in the app. Multiple types of AD are available like a Facebook ad, start-up ad, google ad, etc. Today we learning google ad integration.

Type of Google AD:

  • Banner AD
  • Interstitial Ad
  • Rewarded Video Ad
  • Native Ad

1.Banner Ad

Banner Ads occupy only a portion of the screen depending on the ad size that is created. It comes in multiple sizes Standard, Medium, Large, Full-Size, Leaderboard, and Smart Banner. Smart banners are very useful when you target multiple device sizes and fit the same ad depending on the screen size.

2.Interstitial Ads

Interstitial ads occupy the full screen of the app. Basically, they will show on a timely basis, between screen transition or when the user is done with a task.

3.Rewarded Video Ad

This ad shows a video-type ad.

4.Native Ad

In this app in full description ad showing.

Create a new project

Create a new project in Android Studio from File ⇒ New Project.

Open build. Gradle and add play services dependency as AdMob requires it.

compile ‘com.google.android.gms:play-services-ads:11.8.0’

build.gradle
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'

    compile 'ccom.google.android.gms:play-services-ads:11.8.0'
}

Add the App ID and Ad unit IDs to your strings.xml.

    AdMob
    Interstitial
    Welcome to Admob. Click on the below button to launch the Interstitial ad.
    Show Interstitial Ad
    Show Rewarded Video Ad

    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX

Create a class named MyApplication.java and extend the class from Application. In this application class, we have to globally initialize the AdMob App Id. Here we use MobileAds.initialize()

MyApplication.java

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
         MobileAds.initialize(this, getString(R.string.admob_app_id));
    }
}

Open AndroidManifest.xml and add MyApplication to tag.

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-3940256099942544/6300978111"/>
January 13, 20212 minutesPankaj ValaniPankaj Valani
How to add Shadow and Text on ImageView in Android

Basically, it works like a stack where each view is stacked on top of the other.

Create a drawable file for shadow view and assign the name image_shadow and add the below code in this file.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    <gradient
    android:angle="270"
    android:centerX="300%"
    android:endColor="#99000000"
    android:startColor="#00000000"
    android:type="linear" />
    <size
    android:width="270dp"
    android:height="60dp" />
    <stroke
    android:width="1dp"
    android:color="#878787" />
</shape>

Now, open the XML file and add the below code into it, and set this drawable file as view background.

<androidx.appcompat.widget.LinearLayoutCompat
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/imageView"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:scaleType="centerCrop"
        android:src="@drawable/shopping_image"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>
    <View android:id="@+id/view"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:background="@drawable/image_shadow"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>
    <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="@android:color/white"
        android:text="Write your text here"
        android:textSize="25sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="@+id/view"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.LinearLayoutCompat>

That's it. You should be ready to go.

December 31, 20201 minuteVivek BeladiyaVivek Beladiya
How can I run my app on my phone without USB connection with my pc

We will learn to run the app without connecting a USB cable in this blog. The main purpose of this blog is to let users run apps without any restriction. Sometimes if the cable is connected with the device and if the device cable gets disturbed then the app does not run properly.

Let's see how we can run the app without cable.

Step 1: Click File Menu => Settings

2021-01-08-5ff84742652f6

Step 2: Click Plugins

2021-01-08-5ff8475b600ed

Step 3: Install ADB Wi-Fi Plugin

2021-01-08-5ff8476c3d0f6

Notes:

  • In the third image, I already installed the plugin in my android studio. But in your case, you may need to install it.
  • Then your android studio restarts.

After the restart, your android studio will show the "ADB Wifi" option showing as per the following image

2021-01-08-5ff847ae6fa6b

Click ADB Wifi and the below screen will be displayed.

2021-01-08-5ff847f31608f

  • Click to connect
  • Make sure your device and pc are connected to the same wifi. Otherwise, it will not get connected.
  • You will need to connect one time when the android studio is opened for the first time.
November 21, 20201 minutePankaj ValaniPankaj Valani
How to Customize Snackbar in Android

Snackbars are fairly common in the Android app. Almost every app uses a snack bar to display some information about what's going on in the app. You can consider Snackbar as an alternative or the best version of Toasts in Android.

Step 1: Using a normal Snackbar

To use Snackbar in your app, you just have to have the material design dependency in your app. Add Material design dependency to your build.Gradle app-level.

dependencies {
    implementation "com.google.android.material:$latest_version"
}

And then you can use the snack bar just like toast. For example:

Snackbar.make(view, "Show some message here", Snackbar.LENGTH_SHORT).show()

Step 2: Working with the MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.application.snackbarapp.MainActivity">

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

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="show snackbar" />

    </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

Step 3: Creating a custom layout for a snack bar

Under Layout, the folder creates a layout for the snack bar that must be inflated when creating a snack bar under the mainactivity.java file.

import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private CoordinatorLayout coordinatorLayout;
    private Button button;

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

        coordinatorLayout = findViewById(R.id.coordinatorLayout);
        button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSnackbar();
            }
        });
    }

    public void showSnackbar() {
        Snackbar snackbar = Snackbar.make(coordinatorLayout, "Marked as Read", Snackbar.LENGTH_INDEFINITE)
                .setAction("UNDO", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "Undo successful", Snackbar.LENGTH_SHORT);
                        snackbar1.show();
                    }
                })
                .setActionTextColor(Color.RED);

        snackbar.show();
    }
}
November 30, 20201 minuteVivek BeladiyaVivek Beladiya