Monday, 15 July 2019

Android Material Collapsing Toolbar Layout # Part 2



1) activity_main.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="exitUntilCollapsed|scroll"
            app:contentScrim="?attr/colorPrimary"
            app:title="Toolbar Title"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            android:background="@drawable/toolbar">


            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

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

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


    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

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


    </android.support.v4.widget.NestedScrollView>

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


2) Create card_layout.cml file on res/layout folder


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_layout"
    android:orientation="vertical">

    <!--Todo: CardView-->

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="12dp"
        app:cardElevation="6dp"
        app:cardMaxElevation="6dp"
        app:contentPadding="25dp"
        app:cardBackgroundColor="@android:color/white"
        android:layout_margin="10dp"
        >

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

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:id="@+id/card_img"
                android:padding="10dp"
                android:src="@drawable/home_icon"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:id="@+id/card_title"
                android:text="Category Name"
                android:textSize="18dp"
                android:textColor="@android:color/black"
                android:textStyle="bold"/>

        </LinearLayout>



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


3) Create Cards.java class file and past this code


public class Cards {

    Integer Img;
    String category;

    public Cards(Integer img, String category) {
        Img = img;
        this.category = category;
    }

    public Integer getImg() {
        return Img;
    }

    public String getCategory() {
        return category;
    }
}


4) Create CardsAdapter.java class file and past this code


/*Todo: Recyclerview Adapter*/
public class CardsAdapter extends RecyclerView.Adapter<CardsAdapter.ViewHolder>
{

    /*Todo: Recyclerview Adapter class*/
    List<Cards> list;
    Context context;

    public CardsAdapter(List<Cards> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);

        final ViewHolder viewHolder = new ViewHolder(view);

        /*Todo: adding Click Events Of Each Menu On Dashboard by title*/
        
        viewHolder.card_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(context, list.get(viewHolder.getAdapterPosition()).getCategory(), Toast.LENGTH_SHORT).show();
            }
        });

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Cards Cards = list.get(position);
        final int img = Cards.getImg();
        final String categiry = Cards.getCategory();

        holder.card_img.setImageResource(img);
        holder.card_title.setText(categiry);

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{

        ImageView card_img;
        TextView card_title;
        LinearLayout card_layout;
        public ViewHolder(View itemView) {
            super(itemView);

            card_img = (ImageView)itemView.findViewById(R.id.card_img);
            card_title = (TextView) itemView.findViewById(R.id.card_title);
            card_layout = (LinearLayout) itemView.findViewById(R.id.card_layout);

        }
    }
}

5) MainActivity.java


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

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

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private List<Cards> Cardss;
    private RecyclerView.LayoutManager mLayoutManager;

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

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        mLayoutManager = new GridLayoutManager(MainActivity.this,2);
        recyclerView.setLayoutManager(mLayoutManager);
        Cardss = new ArrayList<>();
        loaddata();

    }
    private void loaddata()
    {

        String[] nameArray = {
                "Home",
                "Taxi",
                "Boat",
                "Train",
                "Navigation",
                "Stop"
        };

        int[] drawableArray = {
                R.drawable.home_icon,
                R.drawable.taxi_icon,
                R.drawable.boat_icon,
                R.drawable.train_icon,
                R.drawable.navigation_icon,
                R.drawable.stop_icon
        };

        for (int i = 0; i < nameArray.length; i++) {
            Cardss.add(new Cards(
                    drawableArray[i],
                    nameArray[i]
            ));
        }

        adapter = new CardsAdapter(Cardss, MainActivity.this);
        recyclerView.setAdapter(adapter);
    }

Android Material Collapsing Toolbar Layout # Part 1



1) MainActivity.xml


I highlight the inportant attributes in xml file

<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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="exitUntilCollapsed|scroll"
            app:contentScrim="?attr/colorPrimary"
            app:title="Toolbar Title"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            android:background="@drawable/toolbar">


            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

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

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

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


2) No Need To Code In Java

Android Material Design BottomSheet Example


1) Add this dependency in your gradle file for material design 



    implementation 'com.android.support:design:28.0.0'


1) 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <Button
                android:id="@+id/btnBottomSheet"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Open Bottom Sheet"
                android:textStyle="bold"
                android:textSize="20dp"/>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>


    <include layout="@layout/bottom_layout" />

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


2) Create bottom_layout.xml in res/layout folder and past below code


<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/mainLayout"
    android:background="@android:color/holo_blue_bright"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
     app:behavior_hideable="true"
     app:behavior_peekHeight="58dp"
    android:padding="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Choose One"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="@android:color/white"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"/>

    <View
        android:layout_width="wrap_content"
        android:layout_height="5dp"
        android:background="@android:color/black"
        android:layout_marginRight="150dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dp">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/whatsapp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Whatsapp"
            android:padding="10dp"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dp">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/facebook"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Facebook"
            android:padding="10dp"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dp">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/twitter"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Twitter"
            android:padding="10dp"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dp">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/instagram"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Instagram"
            android:padding="10dp"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold"/>
    </LinearLayout>

</LinearLayout>


3) MainActivity.java


import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    LinearLayout mainLayout;
    BottomSheetBehavior bottomSheetBehavior;
    Button btnBottomSheet;

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

        mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
        btnBottomSheet = (Button) findViewById(R.id.btnBottomSheet);

        //Todo: Add A Layout For BottomSheetBehavior
        bottomSheetBehavior = BottomSheetBehavior.from(mainLayout);

        //Todo: The bottom sheet is hidden.
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

        //Todo: The bottom sheet is expanded.
        //bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);

        //Todo: The bottom sheet is collapsed.
        //bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);

        //Todo: The bottom sheet is dragging.
        //bottomSheetBehavior.setState(BottomSheetBehavior.STATE_DRAGGING);

        //Todo: The bottom sheet is settling.
        //bottomSheetBehavior.setState(BottomSheetBehavior.STATE_SETTLING);

        btnBottomSheet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });

    }
}

Wednesday, 29 May 2019

Modern Dashboard UI Design Android Studio (2019)






1) Add This Two Dependency In Your build.gradle File:

    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'



2) Hide Toolbar From Manifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.miajs.dashboardui">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>

3) Cards_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_layout"
    android:orientation="vertical">

    <!--Todo: CardView-->

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="12dp"
        app:cardElevation="6dp"
        app:cardMaxElevation="6dp"
        app:contentPadding="25dp"
        app:cardBackgroundColor="@android:color/white"
        android:layout_margin="10dp"
        >

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

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:id="@+id/card_img"
                android:padding="10dp"
                android:src="@drawable/alarm"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:id="@+id/card_title"
                android:text="Category Name"
                android:textSize="18dp"
                android:textColor="@android:color/black"
                android:textStyle="bold"/>

        </LinearLayout>



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

4) Download The Drawable Resource File From Here

https://drive.google.com/open?id=1MBpcgppAWvpr0O32yFWGSTt_ga3mQD9M

5) MainActivity.xml


<?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:orientation="vertical"
    android:layout_height="match_parent"
    android:background="@drawable/bg1"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_margin="20dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/arrow_back"/>

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

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Mijas Siklodi"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2:00 pm"/>

            </LinearLayout>


    </LinearLayout>

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

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

</LinearLayout>

6) List_pojo.java

public class List_pojo {

    /*Todo: Pojo class*/

    Integer Img;
    String category;


    public List_pojo(Integer img, String category ) {

        Img = img;
        this.category = category;
    }



    public String getCategory() {
        return category;
    }

    public int getImg() {
        return Img;
    }

}

7) ListAdapter.java

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder>
{

    /*Todo: Recyclerview Adapter class*/
    List<List_pojo> list;
    Context context;

    public ListAdapter(List<List_pojo> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cards_layout, parent, false);

        final ViewHolder viewHolder = new ViewHolder(view);

        /*Todo: adding Click Events Of Each Menu On Dashboard by title*/
        viewHolder.card_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (viewHolder.card_title.getText().toString().toLowerCase()){
                    case "alarm":
                        Toast.makeText(context, "Alarm Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "dollar":
                        Toast.makeText(context, "Dollar Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "location":
                        Toast.makeText(context, "location Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "photo":
                        Toast.makeText(context, "photo Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "train":
                        Toast.makeText(context, "Train Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "video":
                        Toast.makeText(context, "Video Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "watch":
                        Toast.makeText(context, "Watch Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "game":
                        Toast.makeText(context, "Game Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "store":
                        Toast.makeText(context, "Store Is click", Toast.LENGTH_SHORT).show();
                        break;
                    case "love":
                        Toast.makeText(context, "Love Is click", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        List_pojo Cards = list.get(position);
        final int img = Cards.getImg();
        final String categiry = Cards.getCategory();

        holder.card_img.setImageResource(img);
        holder.card_title.setText(categiry);

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{

        ImageView card_img;
        TextView card_title;
        LinearLayout card_layout;
        public ViewHolder(View itemView) {
            super(itemView);

            card_img = (ImageView)itemView.findViewById(R.id.card_img);
            card_title = (TextView) itemView.findViewById(R.id.card_title);
            card_layout = (LinearLayout) itemView.findViewById(R.id.card_layout);

        }
    }
}

8) MyData.java
public class MyData {

    /*Todo: Data To Load In Recyclerview*/
    static String[] nameArray = {
        "Alarm",
        "Dollar",
        "Location",
        "Photo",
        "Train",
        "Video",
        "Watch",
        "Game",
        "Store",
        "Love"
        };

    static Integer[] drawableArray = {
            R.drawable.alarm,
            R.drawable.dollar,
            R.drawable.location,
            R.drawable.photo,
            R.drawable.train,
            R.drawable.video,
            R.drawable.watch,
            R.drawable.game,
            R.drawable.store,
            R.drawable.love};
}

9) MainActivity.java

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

import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private List<List_pojo> Cardss;
    private RecyclerView.LayoutManager mLayoutManager;

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

        recyclerView = (RecyclerView) findViewById(R.id.list);
        recyclerView.setHasFixedSize(true);
        mLayoutManager = new GridLayoutManager(MainActivity.this,2);
        recyclerView.setLayoutManager(mLayoutManager);
        Cardss = new ArrayList<>();
        loaddata();
    }

    private void loaddata()
    {
        for (int i = 0; i < MyData.nameArray.length; i++) {
            Cardss.add(new List_pojo(
                    MyData.drawableArray[i],
                    MyData.nameArray[i]
            ));
        }

        adapter = new ListAdapter(Cardss, MainActivity.this);
        recyclerView.setAdapter(adapter);
    }
}

Friday, 19 April 2019

Android Start a Foreground With Notification Channels

1) MyForeGroundService.class

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MyForeGroundService extends Service {

    private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";

    public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";

    public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";

    public static final String ACTION_STOP = "ACTION_STOP";

    public static final String ACTION_START = "ACTION_START";

    public MyForeGroundService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        //Todo: Foreground Service onCreate()
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null)
        {
            String action = intent.getAction();

            switch (action)
            {
                case ACTION_START_FOREGROUND_SERVICE:
                    startForegroundService();
                    Toast.makeText(getApplicationContext(), "Foreground service is started.", Toast.LENGTH_LONG).show();
                    break;
                case ACTION_STOP_FOREGROUND_SERVICE:
                    stopForegroundService();
                    Toast.makeText(getApplicationContext(), "Foreground service is stopped.", Toast.LENGTH_LONG).show();
                    break;
                case ACTION_START:
                    Toast.makeText(getApplicationContext(), "You click Start button.", Toast.LENGTH_LONG).show();
                    break;
                case ACTION_STOP:
                    Toast.makeText(getApplicationContext(), "You click Stop button.", Toast.LENGTH_LONG).show();
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /* Used to build and start foreground service. */
    private void startForegroundService()
    {
        Log.d(TAG_FOREGROUND_SERVICE, "Start foreground service.");

        // Create notification default intent.
        Intent intent = new Intent();
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Create notification builder.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        // Make notification show big text.
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.setBigContentTitle("Foreground Service.");
        bigTextStyle.bigText("Android foreground service");
        // Set big text style.
        builder.setStyle(bigTextStyle);

        builder.setWhen(System.currentTimeMillis());
        builder.setSmallIcon(R.mipmap.ic_launcher);
        Bitmap largeIconBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round);
        builder.setLargeIcon(largeIconBitmap);
        // Make the notification max priority.
        builder.setPriority(Notification.PRIORITY_MAX);
        // Make head-up notification.
        builder.setFullScreenIntent(pendingIntent, true);

        // Add Play button intent in notification.
        Intent playIntent = new Intent(this, MainActivity.class);
        playIntent.setAction(ACTION_START);
        PendingIntent pendingPlayIntent = PendingIntent.getService(this, 0, playIntent, 0);
        NotificationCompat.Action playAction = new NotificationCompat.Action(android.R.drawable.ic_media_play, "Open", pendingPlayIntent);
        builder.addAction(playAction);

        // Add Pause button intent in notification.
        Intent pauseIntent = new Intent(this, MainActivity.class);
        pauseIntent.setAction(ACTION_STOP);
        PendingIntent pendingPrevIntent = PendingIntent.getService(this, 0, pauseIntent, 0);
        NotificationCompat.Action prevAction = new NotificationCompat.Action(android.R.drawable.ic_media_pause, "Close", pendingPrevIntent);
        builder.addAction(prevAction);

        // Build the notification.
        Notification notification = builder.build();

        // Start foreground service.
        startForeground(1, notification);
    }

    private void stopForegroundService()
    {
        Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");

        // Stop foreground service and remove the notification.
        stopForeground(true);

        // Stop the foreground service.
        stopSelf();
    }
}


2) MainActivity.xml

<?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"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start"
        android:id="@+id/btnStart"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop"
        android:id="@+id/btnStop"/>


</LinearLayout>

3) MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button btnStart, btnStop;

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

        btnStart = (Button) findViewById(R.id.btnStart);
        btnStop = (Button) findViewById(R.id.btnStop);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyForeGroundService.class);
                intent.setAction(MyForeGroundService.ACTION_START_FOREGROUND_SERVICE);
                startService(intent);
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyForeGroundService.class);
                intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
                startService(intent);
            }
        });
    }
}

Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file     implementation 'com.google.android.gms:play-services-location:18.0.0' 2. Add this p...