Friday, December 11, 2020

Animated Gradient Background in Android

Android Gradient Drawables

Now we will create different gradient drawables with different color and file name. Here we create gradient_1.xml, gradient_2.xml and gradient_3.xml XML drawable files with gradient attributes android:angle, android:endColor and android:startColor. Following is the XML code of three drawable files.

res/drawable/gradient_1.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <gradient

        android:angle="225"

        android:endColor="#044fab"

        android:startColor="#21d6d3" />

</shape>

res/drawable/gradient_2.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <gradient

        android:angle="45"

        android:endColor="#933c94"

        android:startColor="#517f95" />

</shape>

res/drawable/gradient_3.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <gradient

        android:angle="135"

        android:endColor="#43b4ef"

        android:startColor="#d40845" />

</shape>

Now create a new XML drawable file android_gradient_list.xml and add the following code which contains the AnimationList, which is responsible to change the background color from one gradient to another. In the AnimationList tag, add 3 items and referring to the above 3 XML drawable files.

res/drawable/android_gradient_list.xml

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item

        android:drawable="@drawable/gradient_1"

        android:duration="4000" />


    <item

        android:drawable="@drawable/gradient_2"

        android:duration="4000" />


    <item

        android:drawable="@drawable/gradient_3"

        android:duration="4000" />

</animation-list>

XML Layout File

Open your app main XML layout file activity_main.xml and set background to the root layout (View or ViewGroup) of the activity where you want to add animated gradient background. Also give an id to that layout; we will need to refer in java activity file.

Animated Gradient Background in Android

res/layout/activity_main.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:id="@+id/root_layout"

    android:background="@drawable/android_gradient_list"

    tools:context="com.viralandroid.animatedgradientandroid.MainActivity">


    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:gravity="center"

        android:text="Android \nBackground \nAnimated Gradient"

        android:textColor="#ffffff"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />


</android.support.constraint.ConstraintLayout>

Sunday, December 6, 2020

Cute wallpaper for Android

Cute wallpaper is a collection of the most beautiful and quality categories with the best pictures, now you can choose your own categories to set wallpapers for your phone.

Cute Girl Wallpaper, it is incredibly beautiful and stylish wallpaper for your android device! Set yourself a Laurra Famous Girl Wallpaper and enjoy these powerful images to the fullest!.

Cute Boy Wallpapers

Cute Boy Wallpapers offers unlimited download of premium and Cute Boy wallpapers with HD qualities.Download this amazing Cute Boy Wallpapers Hd app! and make your phone or tablet look awesome with the coolest wallpapers.

Cute Girl Wallpaper

Cute animals wallpaper is a beautiful animated screensaver with set of cute HD photos with kittens, puppies, panda, fox, raccoon, with live water effect that simulates water drops, live rain effect and much more.

Feature:

  •  HD quality
  • Work offline
  • No internet connection required
  • Very easy to apply wallpapers on your home screen and / or lock screen
  • 400+ beautiful cute Bear wallpapers
  • Full screen wallpaper
  • You can use internet to download images to your storage for wallpaper setting
  • share with your friends via social media easily
  • Save energy and battery power, especially on amoled display.
  • Collection of many genres such as cute flowers wallpaper, cute wallpaper 4K and many other genres.

Friday, December 4, 2020

How to add Custom Spinner in android

How to add Custom Spinner in android

Spinner is a widget that is used to select an item from a list of items. When the user tap on a spinner a drop-down menu is visible to the user. In this article, we will learn how to add custom spinner in the app

Create a new file algorithm_spinner.xml 

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"> 

    <ImageView

        android:id="@+id/image_view"

        android:layout_width="100dp"

        android:layout_height="100dp"

        android:src="@drawable/gfg" /> 

    <TextView

        android:id="@+id/text_view"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBottom="@+id/image_view"

        android:layout_alignParentTop="true"

        android:layout_margin="20dp"

        android:layout_toEndOf="@+id/image_view"

        android:gravity="center"

        android:text="Quick Sort"

        android:textColor="@android:color/black"

        android:textSize="20sp" /> 

</RelativeLayout> 

Create a new file AlgorithmItem.java

public class AlgorithmItem { 

    private String algorithmName; 

  

    public AlgorithmItem(String countryName) 

    { 

        algorithmName = countryName; 

    } 

  

    public String getAlgorithmName() 

    { 

        return algorithmName; 

    } 

Create a new file AlgorithmAdapter.java

public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> { 

    public AlgorithmAdapter(Context context, 

                            ArrayList<AlgorithmItem> algorithmList) 

    { 

        super(context, 0, algorithmList); 

    } 

  

    @NonNull

    @Override

    public View getView(int position, @Nullable

                                      View convertView, @NonNull ViewGroup parent) 

    { 

        return initView(position, convertView, parent); 

    } 

  

    @Override

    public View getDropDownView(int position, @Nullable

                                              View convertView, @NonNull ViewGroup parent) 

    { 

        return initView(position, convertView, parent); 

    } 

  

    private View initView(int position, View convertView, 

                          ViewGroup parent) 

    { 

        // It is used to set our custom view. 

        if (convertView == null) { 

            convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false); 

        } 

  

        TextView textViewName = convertView.findViewById(R.id.text_view); 

        AlgorithmItem currentItem = getItem(position); 

  

        // It is used the name to the TextView when the 

        // current item is not null. 

        if (currentItem != null) { 

            textViewName.setText(currentItem.getAlgorithmName()); 

        } 

        return convertView; 

    } 

Add the following code in activity_main.xml file. Here we add our spinner on the layout. This will add a textview and a spinner.

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout

    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"

    tools:context=".MainActivity"> 

  

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Learn Algorithms"

        android:textStyle="bold"

        android:textSize="18sp"

        android:layout_above="@+id/spinner_algorithm"

        android:layout_marginStart="10dp"

        android:layout_marginBottom="25dp"

        /> 

  

    <Spinner

        android:layout_margin="5dp"

        android:id="@+id/spinner_algorithm"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:layout_marginTop="18dp" /> 

  

</RelativeLayout> 

Now add the following code in the MainActivity.java file

public class MainActivity extends AppCompatActivity { 

  

    ArrayList<AlgorithmItem> algorithmItems; 

    AlgorithmAdapter adapter; 

  

    @Override

    protected void onCreate(Bundle savedInstanceState) 

    { 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.activity_main); 

  

        initList(); 

        Spinner spinner = findViewById(R.id.spinner_algorithm); 

  

        // we pass our item list and context to our Adapter. 

        adapter = new AlgorithmAdapter(this, algorithmItems); 

        spinner.setAdapter(adapter); 

  

        spinner.setOnItemSelectedListener( 

            new AdapterView.OnItemSelectedListener() { 

                @Override

                public void onItemSelected(AdapterView<?> parent, 

                                           View view, int position, long id) 

                { 

  

                    // It returns the clicked item. 

                    AlgorithmItem clickedItem = (AlgorithmItem) 

                                                    parent.getItemAtPosition(position); 

                    String name = clickedItem.getAlgorithmName(); 

                    Toast.makeText(MainActivity.this, name + " selected", Toast.LENGTH_SHORT).show(); 

                } 

                @Override

                public void onNothingSelected(AdapterView<?> parent) 

                { 

                } 

            }); 

    } 

  

    // It is used to set the algorithm names to our array list. 

    private void initList() 

    { 

        algorithmItems = new ArrayList<>(); 

        algorithmItems.add(new AlgorithmItem("Quick Sort")); 

        algorithmItems.add(new AlgorithmItem("Merge Sort")); 

        algorithmItems.add(new AlgorithmItem("Heap Sort")); 

        algorithmItems.add(new AlgorithmItem("Prims Algorithm")); 

        algorithmItems.add(new AlgorithmItem("Kruskal Algorithm")); 

        algorithmItems.add(new AlgorithmItem("Rabin Karp")); 

        algorithmItems.add(new AlgorithmItem("Binary Search")); 

    } 

Sreen output:

How to add Custom Spinner in android

How to add a custom styled Toast in Android

How to add a custom styled Toast in Android

This article explains how to create Custom Toast messages, which has custom background, image, icon, etc, which are not provided by the original Toast library.

Add the support Library in your root build.gradle file 

allprojects { 

    repositories { 

        maven { 

            url "https://jitpack.io"  

        } 

    } 

Add the support Library in your module’s build.gradl

dependencies { 

         implementation 'com.github.GrenderG:Toasty:1.4.2' 

Now add the following code in the activity_main.xml file. This code adds five buttons in the activity. Each button is used to call differnt style of toasts.

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout

    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"

    tools:context=".MainActivity"> 

  

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:layout_gravity="center"

        android:orientation="vertical"> 

  

        <Button

            android:layout_margin="10dp"

            android:id="@+id/button_warning"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:onClick="showToast"

            android:text="show warning toast" /> 

  

        <Button

            android:layout_margin="10dp"

            android:id="@+id/button_info"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:onClick="showToast"

            android:text="show info toast" /> 

  

        <Button

            android:layout_margin="10dp"

            android:id="@+id/button_success"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:onClick="showToast"

            android:text="show success toast" /> 

  

        <Button

            android:layout_margin="10dp"

            android:id="@+id/button_error"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:onClick="showToast"

            android:text="show error toast" /> 

  

        <Button

            android:layout_margin="10dp"

            android:id="@+id/button_normal"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:onClick="showToast"

            android:text="show normal toast with an icon" /> 

    </LinearLayout> 

</RelativeLayout> 

Now add the following code in the MainActivity.java file. Now on clicking any button the showToast() function is started and corresponding Toast is displayed

public class MainActivity 

    extends AppCompatActivity { 

  

    @Override

    protected void onCreate( 

        Bundle savedInstanceState) 

    { 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.activity_main); 

    } 

  

    // We assign this method 

    // on OnClick() method 

    // in activity_main.xml file. 

    public void showToast(View v) 

    { 

        switch (v.getId()) { 

  

        // For Error type Toast 

        case R.id.button_error: 

            Toasty.error(this, 

                         "This is an error Toast", 

                         Toast.LENGTH_SHORT) 

                .show(); 

            break; 

  

        // For Success type Toast 

        case R.id.button_success: 

            Toasty.success(this, 

                           "This is a success Toast", 

                           Toast.LENGTH_SHORT) 

                .show(); 

            break; 

  

        // For Info type Toast 

        case R.id.button_info: 

            Toasty.info(this, 

                        "This is an info Toast", 

                        Toast.LENGTH_SHORT) 

                .show(); 

            break; 

  

        // For Warning type Toast 

        case R.id.button_warning: 

            Toasty.warning(this, 

                           "This is a warning Toast", 

                           Toast.LENGTH_SHORT) 

                .show(); 

            break; 

  

        // For Norma type Toast 

        // with an icon 

        case R.id.button_normal: 

            Toasty.normal( 

                      this, 

                      "This is a normal Toast", 

                      Toast.LENGTH_SHORT, 

                      ContextCompat 

                          .getDrawable( 

                              this, 

                              R.drawable.ic_android_black_24dp)) 

                .show(); 

            break; 

        } 

    } 

Screen output:

How to add a custom styled Toast in Android

How to Create a Dark Mode for a Custom Android App in Kotlin

 How to Create a Dark Mode for a Custom Android App in Kotlin

A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. 

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Changes made to styles.xml file

<resources> 

    <!-- Base application theme. -->

    <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar"> 

        <!-- Customize your theme here. -->

        <item name="colorPrimary">@color/colorPrimary</item> 

        <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 

        <item name="colorAccent">@color/colorAccent</item> 

    </style> 

  

</resources>

Step 3: Working with the activity_main.xml file

Now go to the activity_main.xml file which represents the UI of the application, and create a Switch. This switch shall toggle between the dark mode and normal mode. Below is the code for the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout 

    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"

    tools:context=".MainActivity"> 

  

    <!--Create a switch-->

    <Switch

        android:id="@+id/switch1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:text="Enable dark mode"

        tools:ignore="UseSwitchCompatOrMaterialXml" /> 

  

</RelativeLayout>

Step 4: Working with the MainActivity.kt file

class MainActivity : AppCompatActivity() { 

    override fun onCreate(savedInstanceState: Bundle?) { 

        super.onCreate(savedInstanceState) 

        setContentView(R.layout.activity_main) 

        val btn = findViewById<Switch>(R.id.switch1) 

  

        // set the switch to listen on checked change 

        btn.setOnCheckedChangeListener { _, isChecked -> 

            if (btn.isChecked) { 

                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) 

                btn.text = "Disable dark mode"

            } else { 

                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) 

                btn.text = "Enable dark mode"

            } 

        } 

    } 

}

Screen output:

How to Create a Dark Mode for a Custom Android App in Kotlin

How to Create AlertDialog Box Using SweetAlert Dialog Library?

How to Create AlertDialog Box Using SweetAlert Dialog Library?

Custom Alert Dialog in an app using SweetAlert Dialog Library. It is a pop-up box which appears in response to any action of the user.AlertBox is very useful when it comes to validation, it can be used to display confirmation messages.

Step 1: Add the support Library in build.gradle file and add dependency in the dependencies section. This library has inbuilt alert dialog which can be directly used.

dependencies {          

        implementation 'com.github.f0ris.sweetalert:library:1.5.1'          

Step 2: Now add the following code in activity_main.xml file. This code adds five buttons in the activity. Each button is used to call differnt style of Alert Dialog Box.

<?xml version="1.0" encoding="utf-8"?> 

<androidx.constraintlayout.widget.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"

    tools:context=".MainActivity"> 

  

    <Button

        android:onClick="showDialog"

        android:id="@+id/basic_dialog"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Basic Dialog"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="0.452"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.124" /> 

  

    <Button

        android:onClick="showDialog"

        android:id="@+id/error_dialog"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Error Dialog"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="0.452"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.284" /> 

  

    <Button

        android:onClick="showDialog"

        android:id="@+id/warning_dialog"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Warning Dialog"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="0.452"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.45" /> 

  

    <Button

        android:onClick="showDialog"

        android:id="@+id/success_dialog"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="256dp"

        android:text="Success Dialog"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="0.47"

        app:layout_constraintStart_toStartOf="parent" /> 

  

    <Button

        android:onClick="showDialog"

        android:id="@+id/custom_dialog"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="156dp"

        android:text="Custom Dialog"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="0.464"

        app:layout_constraintStart_toStartOf="parent" /> 

</androidx.constraintlayout.widget.ConstraintLayout> 

Step 3: Add the following code in MainActivity.java file

public class MainActivity extends AppCompatActivity { 

  

    @Override

    protected void onCreate(Bundle savedInstanceState) { 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.activity_main); 

    } 

  

    public void showDialog(View view){ 

        switch (view.getId()){ 

            case R.id.basic_dialog: 

                new SweetAlertDialog(this) 

                        .setTitleText("Here's a message!") 

                        .setContentText("This is Basic Dialog") 

                        .show(); 

                break; 

            case R.id.error_dialog: 

                new SweetAlertDialog( 

                         this, SweetAlertDialog.ERROR_TYPE) 

                        .setTitleText("Oops...") 

                        .setContentText("Something went wrong!") 

                        .show(); 

                break; 

            case R.id.warning_dialog: 

                new SweetAlertDialog( 

                         this, SweetAlertDialog.WARNING_TYPE) 

                        .setTitleText("Are you sure?") 

                        .setContentText("Won't be able 

                          to recover this file!") 

                        .setConfirmText("Yes, delete it!") 

                        .show(); 

                break; 

            case R.id.success_dialog: 

                new SweetAlertDialog( 

                         this, SweetAlertDialog.SUCCESS_TYPE) 

                        .setTitleText("Great!") 

                        .setContentText("You completed this task.") 

                        .show(); 

                break; 

            case R.id.custom_dialog: 

                new SweetAlertDialog( 

                         this, SweetAlertDialog.CUSTOM_IMAGE_TYPE) 

                        .setTitleText("Android") 

                        .setContentText("Thi is custom dialog") 

                        .setCustomImage(R.drawable.ic_android_black) 

                        .show(); 

                break; 

        } 

    } 

Screen output:

How to Create AlertDialog Box

How to create a custom AlertDialog in Android

How to create a custom AlertDialog in Android

AlertDialog A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout.

How to create a custom AlertDialog in Android

Step 1: Create a XML file: custom_layout.xml. Add the below code in custom_layout.xml. This code defines the alertdialog box dimensions and add a edittext in it.

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout 

  xmlns:android="http://schemas.android.com/apk/res/android" 

  android:orientation="vertical" 

  android:paddingLeft="20dp" 

  android:paddingRight="20dp" 

  android:layout_width="match_parent" 

  android:layout_height="match_parent"> 

  

  <EditText 

    android:id="@+id/editText" 

    android:layout_width="match_parent" 

    android:layout_height="wrap_content"/> 

</LinearLayout> 

Step 2: Add a button in activity_main.xml. The button when clicked will show the AlertDialog box.

<?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:gravity="center"

    android:id="@+id/root"

    android:orientation="vertical"

    tools:context=".MainActivity"> 

  

    <Button

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:onClick="showAlertDialogButtonClicked"

        android:text="Show Dialog"

     /> 

</LinearLayout> 

Step 3:

Add custom_layout.xml in that activity in which you want to show custom alert dialog here it is added in MainActivity.java.

public class MainActivity 

    extends AppCompatActivity { 

  

    @Override

    protected void onCreate( 

        Bundle savedInstanceState) 

    { 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.activity_main); 

    } 

  

    public void showAlertDialogButtonClicked(View view) 

    { 

  

        // Create an alert builder 

        AlertDialog.Builder builder 

            = new AlertDialog.Builder(this); 

        builder.setTitle("Name"); 

  

        // set the custom layout 

        final View customLayout 

            = getLayoutInflater() 

                  .inflate( 

                      R.layout.custom_layout, 

                      null); 

        builder.setView(customLayout); 

  

        // add a button 

        builder 

            .setPositiveButton( 

                "OK", 

                new DialogInterface.OnClickListener() { 

  

                    @Override

                    public void onClick( 

                        DialogInterface dialog, 

                        int which) 

                    { 

  

                        // send data from the 

                        // AlertDialog to the Activity 

                        EditText editText 

                            = customLayout 

                                  .findViewById( 

                                      R.id.editText); 

                        sendDialogDataToActivity( 

                            editText 

                                .getText() 

                                .toString()); 

                    } 

                }); 

  

        // create and show 

        // the alert dialog 

        AlertDialog dialog 

            = builder.create(); 

        dialog.show(); 

    } 

  

    // Do something with the data 

    // coming from the AlertDialog 

    private void sendDialogDataToActivity(String data) 

    { 

        Toast.makeText(this, 

                       data, 

                       Toast.LENGTH_SHORT) 

            .show(); 

    } 

Screen output:

How to detect slow network connection?

 I have a problem about how to detect internet connection , i want if the internet connection has slowly there is show alert dialog or notice about the connection internet slowly.

you can use the below mentioned Connectivity utility class to check if internet connected or speed of the internet connection,

public class Connectivity {


    /**

     * Get the network info

     *

     * @param context

     * @return

     */

    public static NetworkInfo getNetworkInfo(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        return cm.getActiveNetworkInfo();

    }


    /**

     * Check if there is any connectivity

     *

     * @param context

     * @return

     */

    public static boolean isConnected(Context context) {

        NetworkInfo info = Connectivity.getNetworkInfo(context);

        return (info != null && info.isConnected());

    }



    public static boolean isConnectedWifi(Context context) {

        NetworkInfo info = Connectivity.getNetworkInfo(context);

        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);

    }


    public static boolean isConnectedMobile(Context context) {

        NetworkInfo info = Connectivity.getNetworkInfo(context);

        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);

    }


    /**

     * Check if there is fast connectivity

     *

     * @param context

     * @return

     */

    public static boolean isConnectedFast(Context context) {

        NetworkInfo info = Connectivity.getNetworkInfo(context);

        return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(), info.getSubtype()));

    }


    /**

     * Check if the connection is fast

     *

     * @param type

     * @param subType

     * @return

     */

    public static boolean isConnectionFast(int type, int subType) {

        if (type == ConnectivityManager.TYPE_WIFI) {

            return true;

        } else if (type == ConnectivityManager.TYPE_MOBILE) {

            switch (subType) {

                case TelephonyManager.NETWORK_TYPE_1xRTT:

                    return true; // ~ 50-100 kbps

                case TelephonyManager.NETWORK_TYPE_CDMA:

                    return true; // ~ 14-64 kbps

                case TelephonyManager.NETWORK_TYPE_EDGE:

                    return true; // ~ 50-100 kbps

                case TelephonyManager.NETWORK_TYPE_EVDO_0:

                    return true; // ~ 400-1000 kbps

                case TelephonyManager.NETWORK_TYPE_EVDO_A:

                    return true; // ~ 600-1400 kbps

                case TelephonyManager.NETWORK_TYPE_GPRS:

                    return true; // ~ 100 kbps

                case TelephonyManager.NETWORK_TYPE_HSDPA:

                    return true; // ~ 2-14 Mbps

                case TelephonyManager.NETWORK_TYPE_HSPA:

                    return true; // ~ 700-1700 kbps

                case TelephonyManager.NETWORK_TYPE_HSUPA:

                    return true; // ~ 1-23 Mbps

                case TelephonyManager.NETWORK_TYPE_UMTS:

                    return true; // ~ 400-7000 kbps

            /*

             * Above API level 7, make sure to set android:targetSdkVersion

             * to appropriate level to use these

             */

                case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11

                    return true; // ~ 1-2 Mbps

                case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9

                    return true; // ~ 5 Mbps

                case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13

                    return true; // ~ 10-20 Mbps

                case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8

                    return false; // ~25 kbps

                case TelephonyManager.NETWORK_TYPE_LTE: // API level 11

                    return true; // ~ 10+ Mbps

                // Unknown

                case TelephonyManager.NETWORK_TYPE_UNKNOWN:

                default:

                    return false;

            }

        } else {

            return false;

        }

    }


    public static String getConnectionStrength(Context context) {

        NetworkInfo info = Connectivity.getNetworkInfo(context);

        if (info != null && info.isConnected()) {

            return Connectivity.getInternetStrength(info.getType(), info.getSubtype(), context);

        } else {

            return "Not Connected";

        }

    }



    public static String getInternetStrength(int type, int subType, Context context) {

        if (type == ConnectivityManager.TYPE_WIFI) {

            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            int numberOfLevels = 5;

            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);

            return "" + level/* + " out of 5"*/;

        } else if (type == ConnectivityManager.TYPE_MOBILE) {

            switch (subType) {

                case TelephonyManager.NETWORK_TYPE_CDMA:

                    return "" + 1; //Poor

                case TelephonyManager.NETWORK_TYPE_1xRTT:

                case TelephonyManager.NETWORK_TYPE_EDGE:

                case TelephonyManager.NETWORK_TYPE_GPRS:

                    return "" + 3; //Fair

                case TelephonyManager.NETWORK_TYPE_EVDO_A:

                case TelephonyManager.NETWORK_TYPE_EVDO_0:

                case TelephonyManager.NETWORK_TYPE_HSDPA:

                case TelephonyManager.NETWORK_TYPE_HSPA:

                case TelephonyManager.NETWORK_TYPE_HSUPA:

                case TelephonyManager.NETWORK_TYPE_UMTS:

                case TelephonyManager.NETWORK_TYPE_EHRPD:

                case TelephonyManager.NETWORK_TYPE_EVDO_B:

                case TelephonyManager.NETWORK_TYPE_HSPAP:

                case TelephonyManager.NETWORK_TYPE_IDEN:

                case TelephonyManager.NETWORK_TYPE_LTE:

                    return "" + 5; //Good

                case TelephonyManager.NETWORK_TYPE_UNKNOWN:

                    return "" + 0; //No Connection

                default:

                    return "" + 0;

            }

        } else {

            return "Not Connected";

        }

    }


    /***

     * Get Device Connection Status

     * @param context Calling Context.

     * @return Connectivity signal status value which is based on Network Info

     */

    public static String getConnectionStatus(Context context) {

        NetworkInfo info = Connectivity.getNetworkInfo(context);

        if (info == null || !info.isConnected()) {

            return Constants.ConnectionSignalStatus.NO_CONNECTIVITY;

        } else if (Connectivity.getInternetStatus(info.getType(), info.getSubtype(), context) == 3

                && Utils.getBatteryPercentageDouble(context) > 20) {

            return Constants.ConnectionSignalStatus.GOOD_STRENGTH;

        } else if (Connectivity.getInternetStatus(info.getType(), info.getSubtype(), context) >= 2

                && Utils.getBatteryPercentageDouble(context) > 20) {

            return Constants.ConnectionSignalStatus.FAIR_STRENGTH;

        } else if (Connectivity.getInternetStatus(info.getType(), info.getSubtype(), context) >= 2

                && Utils.getBatteryPercentageDouble(context) <= 20) {

            return Constants.ConnectionSignalStatus.BATTERY_LOW;

        } else {

            return Constants.ConnectionSignalStatus.POOR_STRENGTH;

        }

    }


    public static int getInternetStatus(int type, int subType, Context context) {

        if (type == ConnectivityManager.TYPE_WIFI) {

            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            int numberOfLevels = 5;

            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);

            if (level < 2) {

                return 2; //Fair

            } else {

                return 3; //Good

            }

        } else if (type == ConnectivityManager.TYPE_MOBILE) {

            switch (subType) {

                case TelephonyManager.NETWORK_TYPE_CDMA:

                    return 1; //Poor

                case TelephonyManager.NETWORK_TYPE_1xRTT:

                case TelephonyManager.NETWORK_TYPE_EDGE:

                case TelephonyManager.NETWORK_TYPE_GPRS:

                    return 1; //Fair

                case TelephonyManager.NETWORK_TYPE_EVDO_A:

                case TelephonyManager.NETWORK_TYPE_EVDO_0:

                case TelephonyManager.NETWORK_TYPE_HSDPA:

                case TelephonyManager.NETWORK_TYPE_HSPA:

                case TelephonyManager.NETWORK_TYPE_HSUPA:

                case TelephonyManager.NETWORK_TYPE_UMTS:

                case TelephonyManager.NETWORK_TYPE_EHRPD:

                case TelephonyManager.NETWORK_TYPE_EVDO_B:

                case TelephonyManager.NETWORK_TYPE_HSPAP:

                case TelephonyManager.NETWORK_TYPE_IDEN:

                case TelephonyManager.NETWORK_TYPE_LTE:

                    return 3; //Good

                case TelephonyManager.NETWORK_TYPE_UNKNOWN:

                    return 0; //No Connection

                default:

                    return 0;

            }

        } else {

            return 0;

        }

    }


    /**

     * Return the availability of cellular data access in background.

     *

     * @param context Application or Activity context.

     *

     * @return Availability of cellular data access in background.

     */

    public static boolean isBackgroundDataAccessAvailable(Context context) {


        boolean isBackgroundDataAccessAvailable = true;


        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connMgr != null) {

            // Checks if the device is on a metered network

            if (connMgr.isActiveNetworkMetered()) {


                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {


                    // Checks user’s Data Saver settings.

                    switch (connMgr.getRestrictBackgroundStatus()) {


                        case RESTRICT_BACKGROUND_STATUS_DISABLED:

                            // Data Saver is disabled. Since the device is connected to a

                            // metered network, the app should use less data wherever possible.

                            isBackgroundDataAccessAvailable = true;

                            break;


                        case RESTRICT_BACKGROUND_STATUS_WHITELISTED:

                            // The app is whitelisted. Wherever possible,

                            // the app should use less data in the foreground and background.

                            isBackgroundDataAccessAvailable = true;

                            break;


                        case RESTRICT_BACKGROUND_STATUS_ENABLED:

                            // Background data usage is blocked for this app. Wherever possible,

                            // the app should also use less data in the foreground.

                            isBackgroundDataAccessAvailable = false;

                            break;

                    }

                } else {

                    NetworkInfo.State state = connMgr.getActiveNetworkInfo().getState();

                    isBackgroundDataAccessAvailable = state != NetworkInfo.State.DISCONNECTED;

                }


            } else {

                // The device is not on a metered network.

                // Use data as required to perform syncs, downloads, and updates.

                isBackgroundDataAccessAvailable = true;

            }

        } else {

            isBackgroundDataAccessAvailable = true;

        }


        return isBackgroundDataAccessAvailable;

    }


}

Use

 boolean isFastConnection = Connectivity.isConnectedFast(ctx);