Home Blog Page 84

How to make a Expandable Card in Flutter? ExpansionTile Widget Flutter

0
ExpansionTile Widget Flutter example

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to make a Expandable Card in Flutter using ExpansionTile Widget.

What is Expansion Tile Widget in Flutter ?

Expansion is Similar to Expandable CardView in android,Using this Expansion Tile Widget one can Tap on the card to Expands or just collapses the view of the children inside it.

In other words, Expansion Tile is a simple ListTile with a traling icon or image that works some thing like expands or collapses the tile to open the hidden children widget in it.

Video Tutorial

 

Snippet Code of ExpansionTile widget Flutter

ExpansionTile(
            leading: Icon(FontAwesomeIcons.sign),
            title: Text("Expansion Title"),
            subtitle: Text("  Sub Title's"),
            children: <Widget>[
              Text(
                "In Children use can use any flutter Widget",
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(
                height: 20,
              ),
              Center(
                child: Text(
                    "Children Widgets are expanded/ visible when Expansion Tile Widget is Clicked"),
              )
            ],
          ),

In above, snippet code of ExpansionTile i have included ExpansionTile properties such as title,subtitle,children, and a leading icon.

leading: Leading is the first properties of this widget, here you may include any widgets of your choice, In my case i have added an Icon

title: giving a title to the Expansion tile.

subtitle : giving a subtitle to Expansion tile.

children: <Widget>[] : define  widgets inside the Expansion Tile, this children widget will be visiable when user clicks on the expansion tile card.

When user click on the Tile, it expands(open) or collopses(closes).

Result of above snippet code.

after expanding expansiontile widget

Complete Source Code with Example of using Expansion Tile Widget

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterexpandablelibrary/ExpandableCardViewFlutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Expandable Card View Widget"),
      ),
      body: SingleChildScrollView(
          child:
              MyExpanableCardViewFlutter()), //Wrapped into SingleChildScrollView because when click on TextField  keyboard will open and you may get error on screen "bottom overflowed by pixels flutter"
    );
  }
}

Create a new dart file in lib directory and name it as “MyExpanableCardViewFlutter”

MyExpandableCardviewFlutter.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MyExpanableCardViewFlutter extends StatefulWidget {
  @override
  _MyExpanableCardViewFlutterState createState() =>
      _MyExpanableCardViewFlutterState();
}

class _MyExpanableCardViewFlutterState
    extends State<MyExpanableCardViewFlutter> {
  //controller for TextField
  final username_controller = TextEditingController();
  final password_controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Card(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              width: MediaQuery.of(context)
                  .size
                  .width, // container width depending on user device screen width
              height: 260.0,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      fit: BoxFit.fill,
                      image: NetworkImage(
                          "https://images.unsplash.com/photo-1558981852-426c6c22a060?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"))),
            ),
          ),
          ExpansionTile(
            title: Text("Harley-Davidson"),
            subtitle: Text("  Explore the world of H-D"),
            children: <Widget>[
              IconTheme(
                data: IconThemeData(
                  color: Colors.amber,
                  size: 32,
                ),
                child: StarDisplay(value: 3),
              ),
              Text("This image has 3 star rating ")
            ],
          ),
          ExpansionTile(
            title: Text("LOGIN FORM"),
            trailing: Icon(FontAwesomeIcons.signInAlt),
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: TextField(
                  controller: username_controller,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'username',
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: TextField(
                  controller: password_controller,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Password',
                  ),
                ),
              ),
              RaisedButton(
                textColor: Colors.white,
                color: Colors.blue,
                onPressed: () {
                  String username = username_controller.text;
                  String password = password_controller.text;

                  if (username != '' && password != '') {
                    print('Successfull');

                    print(" Value Entered in USERNAME " + username);
                    print("Password entered is : " + password);
                  }
                },
                child: Text("Log-In"),
              )
            ],
          ),
        ],
      ),
    ));
  }
}

class StarDisplay extends StatelessWidget {
  final int value;
  const StarDisplay({Key key, this.value = 0})
      : assert(value != null),
        super(key: key);
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(5, (index) {
        return Icon(
          index < value ? Icons.star : Icons.star_border,
        );
      }),
    );
  }
}

Note : I have made use of FontAwesomeIcon flutter library, So make sure you add it’s dependencies in pubspec.yaml file

dependencies:
  font_awesome_flutter: ^8.8.1   // this line

Result of above futter expension Tile Flutter Example

expension tile widget example

 

Flutter Push Notifications using flutter firebase messaging with example

0
Flutter Push Notifications using flutter firebase messaging with example
Flutter Push Notifications using flutter firebase messaging with example

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to implement firebase flutter push notifications service in flutter app.

Using which you can send Firebase Cloud messages to your flutter app user using firebase console that is flutter push notifications.

DEMO OUTPUT

flutter firebase push notification example
flutter firebase push notification example

Let’s start

Flutter Firebase Push Notification

Step 1: Adding Firebase Messaging dependencies

Using this Flutter Plugin we can use the Firebase Cloud Messaging  Service (FCM).

With the use of this plugin, your Flutter application will be ready to process and receive the push notification from the firebase console server as well as data messaging on android and iOS devices.

link to firebase messaging plugin here

Open pubspec.yaml file and under dependencies: line add this –

dependencies:
  firebase_messaging: ^6.0.13  // add this line

Step 2: Create a new project on firebase console

Open Firebase Console

1. Add / Create Project :

Give a name to your firebase project as “Firebase-Push-Notification”, Just fill all the common required details for creating the firebase project.

2. Add firebase to your android application

Then, After successful creating firebase project, you will see an Add app with list of platform where you can integrate firebase eg : android, iOS, web, unity3D.

Select Android playform

3. Register app with android package name

Came back to IDE (Android Studio)  Navigate towords Androidmanifest.xml file to get android package name

Flutter Project > Android > app > src > main > AndroidManifest.xml

Under this manifest file you will find package name copy it and paste it into firebase console as below screenshot.

Add Firebase to you flutter android app

adding firebase to your android app

Hit Next.

Add google-services.json Config file to your flutter android app

Download the firebase google-services.json file and paste it in your flutter project in android section.

download firebase project config json file

project > Android > app > (paste) google-services.json

adding google-services json

Add Firebase SDK

Open build-gradle ( project level )

futter project > Android > build-gradle(project level)

add this classpath:-

buildscript {
    repositories {
        google() // add this if not there
        jcenter()
    }

    dependencies {
       
        classpath 'com.google.gms:google-services:4.3.3' //add here line 
    }
}

as shown in the below screenshot

add firebase SDK build.gradle project level

Note: check if google() repositories is added, if not then add it

Then, open build-gradle(app level)

project > Android > app  > build-gradle

Add the google services apply plugin

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'   // add the plugin on top or at the bottom og build-gradle (app-level)

apply plugin google services

Step 3:  Add FLUTTER_NOTIFICATION_CLICK <intent-filter>

Open AndroidManifest.xml file and add the intent-filter

project > Android > app > main > AndroidManifest.xml
<intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>

add flutter notification click intent filter in <activity tag as show in screenshot below

flutter notification click intent filter

Step 4: Create a directory DataModel and create a  datamodel class file

(right click) on lib > New > Package

Name the package as DataModel  under the directory create a new dart file named “FirebaseMessage.dart”

Then add the below lined of code in it.

import 'package:flutter/cupertino.dart';

class FirebaseMessage {
  final String title;
  final String body;

  const FirebaseMessage({@required this.title, @required this.body});
}

This class will hold the value received firebase cloud messaging services.

Step 5: Copy below code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutterpushnotification/DataModel/FirebaseMessage.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final List<FirebaseMessage> messageList = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _firebaseMessaging.configure(
        onResume: (Map<String, dynamic> message) async {
      print("on Resume : $message");
    }, onLaunch: (Map<String, dynamic> message) async {
      print("on Launch  : $message");
      final notification = message['notification'];
      setState(() {
        messageList.add(FirebaseMessage(
            title: notification['title'], body: notification['body']));
      });
    }, onMessage: (Map<String, dynamic> message) async {
      print("on Message : $message");
      final notification = message['notification'];
      setState(() {
        messageList.add(FirebaseMessage(
            title: notification['title'], body: notification['body']));
      });
    });
    _firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Push Notification"),
      ),
      body: ListView(
        children: messageList.map(createListTile).toList(),
      ),
    );
  }
}

Widget createListTile(FirebaseMessage message) => ListTile(
      title: Text(message.title),
      subtitle: Text(message.body),
    );

There you go, our flutter app all is ready to receive message from firebase cloud messaging server.

Step 6 : Sending Push notification from firebase Console to your flutter project

Goto firebase console  to send push notification to your flutter project application.

On the left navigation bar Grow > Cloud Messaging

Click on send your first message

 

sending push notification flutter target

Do you remember? we have added <intent-filter> in our flutter AndroidManifest.xml

their we have have initial intent filter action as FLUTTER_NOTIFICATION_CLICK 

custom-data

key= click_action and value = FLUTTER_NOTIFICATION_CLICK

sending push notification additional optional

Then Click on Publish Button, then Firebase will send the push notifications to your flutter application as show in the above mobile screenshot.

Flutter VelocityX Library–How to use velocity x Card on any Flutter Widgets

2
Flutter VelocityX Library–How to use VelocityX Card on any Flutter Widgets

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna introduce you with a latest product called VELOCITY X” Library developed using Flutter SDK by Pawan Kumar.

Installation of this Velocity X library is defined here

Brief Introduction to the Library

What is Flutter Velocity X?

The Velocity X library in flutter development is a minimalist flutter framework that helps you in building custom Application design Rapidly.

Velocity X comes with various properties that we can apply to our flutter widget such as Color, Padding, Text , Box, Card, SizedBox and many more.

So in this Flutter tutorial, we will look into How to use VelocityX Card on any Flutter Widgets

How to use VelocityX Card on any Flutter Widgets

Note: when you are done with card properties then just use .make() to complete like of code as widget.

Velocity x Card

You can use card properties on any of the flutter widgets & wrap it to a card widget.

Eg:-

Text("Hello World")
                      .text
                      .center
                      .makeCentered()
                      .card
                      .white
                      .make()
                      .wh(150, 50),

This will result card widget on top of Text, as you can see in below picture.

Padding to the VelocityX card

Eg:-

Text("Giving Padding to Card").card.py16.make(),

This will set a Padding to the card with padding size of 16 px vertically.

velocityx card padding

Color to the velocityX card

Color to the velocityX card can be set using color methods.

Eg:-

Text("Color to the card").card.red600.make(), //red color card

then this code will fill the card with color properties as red.

Setting Color using Hex Code

you can even set the card color using Hex Color Code properties.

Text("Hex Code to set VelocityX Card Color")
                      .card
                      .hexColor('#FFF00d')
                      .make(),

this will set the flutter card color to Yellow.

velocityx card coloring using hex color code

Applying VelocityX Card to Image.network widget

Image.network(
                          "https://i.ytimg.com/vi/65hpqxG8k3E/maxresdefault.jpg")
                      .card
                      .py12
                      .roundedLg //this will set card border radius to 30
                      .make(),

Here, i have used Image.network Flutter widget, that will simply load a image from the url alloted and wrap the whole image widget into card widget with some Border Radius properties.

Result:

velocityx card border radius

Rounding(Border radius) Velocity X

This library offers you many predefined rounded radius properties for card widget.

Here are some predefined properties that you can use:

  • roundedNone – 0
  • roundedSM – 7.5
  • rounded – 15
  • roundedLg – 30

Eg:- Text(‘Velocityx’).card.roundedLg.make(); // sets the radius size as 15.

Converting String into TextWidget the Wrapping it to Card Widget using VelocityX

"Changing String to Text Widget with Velocity X text Properties and then change card color"
                      .text
                      .white
                      .center
                      .make()
                      .card
                      .blue700
                      .py12
                      .make(),
string to text in velocity ex

Using All Together

"All Together"
                      .text
                      .xl3
                      .blue700
                      .semiBold
                      .makeCentered()
                      .card
                      .roundedLg
                      .make()
                      .wh(180, 180),

Then, Here wh(width,height) defines width and height of the card widget.

Installation of Flutter VelocityX Library – and How to use it in Text Widget.

2
Installation of Flutter VelocityX Library - and How to use it in Text Widget

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna introduce you with a latest product called VELOCITY XLibrary developed using Flutter SDK by Pawan Kumar.

What is Flutter Velocity X?

The Velocity X  library in flutter development is a minimalist flutter framework that helps you in building custom Application design Rapidly.

Velocity X comes with various properties that we can apply to our flutter widget such as Color, Padding, Text , Box, Card, SizedBox and many more.

Installation of Velocity X in Flutter Project

Step 1: Adding Dependencies

Add the following dependencies in your pubspec.yaml file.

dependencies:
  velocity_x: ^0.2.0  // add this line

Step 2: Importing the VelocityX package

Once you have added the velocityx dependencies, Now you can use them in your dart code (main.dart), just by importing the package / component that are required for application development.

Eg: In my case i have imported it in main.dart file

import 'package:velocity_x/velocity_x.dart' ;

Then, it’s all set your flutter project is ready to make use of velocityx librarys.

Tutorial on Applying VelocityX to Text / How to use Velocity X in Text Widget.

This Library gives super power to Text

Note : When are are done with applying velocityx properties to widget or string end it with .make() to make it back to flutter widget.

Converting String Variable to Text Widget

'Demo On Flutter Velocity X'
                      .text
                      .size(30)
                      .bold
                      .make(),

output

velocityx string to text make

the above code will change the normal String text into text widget, when you define it with .text and at the end convert it to Text widget using .make().

FontStyle

Applying font Style italic

Text('You have pushed the button this many times:',)
.text
.red600   //text color to red
.italic   //stlying italic
.make(),   // make it as widget

velocity x text to fontstyle italic

Font Scale / Font Size in flutter using velocityx

"Font Scale Size".text
                 .sm   //font size pre-defined
                 .make(),

velocity x fontsize

fontSize predefined properties

  • xs – Extra Small (scaleFactor 0.75)
  • sm – Small (scaleFactor 0.875)
  • base – Normal (scaleFactor 1)
  • lg – Large (scaleFactor 1.125)
  • xl – Extra Large (scaleFactor 1.25)
  • xl2 – 2 Extra Large (scaleFactor 1.5)
  • xl3 – 3 Extra Large (scaleFactor 1.875)
  • xl4 – 4 Extra Large (scaleFactor 2.25)
  • xl5 – 5 Extra Large (scaleFactor 3)
  • xl6 – 6 Extra Large (scaleFactor 4)

Font Weight 

Giving thickness to text font.

"Font Weight".text
             .extraBold
              .make(), // applying font weight with pre deined size

Output

Velocity x font weight

 

Text Font Weight properties

  • hairLine – Font Weight 100
  • thin – Font Weight 200
  • light – Font Weight 300
  • normal – Font Weight 400
  • medium – Font Weight 500
  • semiBold – Font Weight 600
  • bold – Font Weight 700
  • extraBold – Font Weight 800
  • extraBlack – Font Weight 900

Letter Spacing

You can give spacing between each letter on text by using velocityx properties.

"Letter Spacing ".text.widest.make(),

letter spacing in flutter velocity x

Spacing between text this are pre-defined parameters

  • tightest – Letter Spacing -3.0
  • tighter – Letter Spacing -2.0
  • tight – Letter Spacing -1.0
  • wide – Letter Spacing 1.0
  • wider – Letter Spacing 2.0
  • widest – Letter Spacing 3.0

Decoration to Text

Text can be decorated with underline, overline, lineThrough

"Text Decoration".text.underline.heightRelaxed.make().

Flutter text decoration with underline using velocityX

Decoration velocityX properties

  • underline – TextDecoration.underline
  • lineThrough – TextDecoration.lineThrough
  • overline – TextDecoration.overline

Text Utilities

Applying text utilities with UPPERCASE, lowercase, Capitalize and hidePartial

"Text Utilities".text.uppercase.make(), //change the font text to upper case

text to uppercase using velocity

  • uppercase – WELCOME TO PROTO CODERS POINT
  • lowercase – welcome to velocityx
  • capitalize – Welcome To Velocityx

Hiding Text

you can even hide some text from a long string, Hidden text will be shown in *****

"Text Utilities hidden".text.hidePartial.make(), //this will hide some text from start

hide partially

  • hidePartial – ***** To Velocityx

 

All properties Together

Text("Velocity_X text property all together")
                      .text
                      .orange400 // text color orange
                      .xl        // text font extra large
                      .bold      // make text bold
                      .center    //align to center
                      .heightLoose
                      .underline // under line to text
                      .wide    // space between text
                      .uppercase  //make text to UPPERCASE
                      .make(),   //convert it back to a widget

Output

velocity properties apply to text

 

 

Firebase Cloud Messaging (FCM) Send Push Notification using php script

0
Firebase Cloud Messaging (FCM) Send Push Notification using php script
Firebase Cloud Messaging (FCM) Send Push Notification using php script

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will send firebase push notification using php function/php script.

In other words, The FCM notification will be sent to particular user who are subscribed to a topic in Firebase Cloud Messaging Service.

DEMO

ui design example on how to send push notification to android app using php code

android php push notification screenshot

So let’s begin implementing this Android FCM project.

Step 1: Create a new Android Project

As usual create a new android project in your android studio

File > New > New Project

Give a name to your project say Firebase push notification service.

Step 2: Connect new Project to firebase using firebase android studio assistant

Step 1: Add Firebase Analytic

tools > firebase > select analytics

1. Connect to firebase

Hit that connect to firebase Button under assistant, This will open default browser with a firebase url to add your android project to your firebase console.

Just agree all the steps on your browser, if you face any problem to connect to firebase console check out the above video

2. Add Analytics to your app

just click on the button suggested by assistant “add analytic to your app”  this will add all the required dependencies & classes.

3. Add analytic code

open MainActivity.java basically you loading or first screen of your android app.

private FirebaseAnalytics mFirebaseAnalytics;

//inside of onCreate 
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

Step 2: Add Cloud Messaging dependencies through assistant

under the android firebase assistant search for cloud messaging under that hit “Add FCM to your app”

This will add the FCM dependencies to your android project.

android project connected to firebase console

 

Step 3: Create a new Service class for FCM Services

Create a service java (Right Click) > New > Service > service  and name it a anything your wish in my case i have named it as FirebaseCloudMessagingService.java

creating FCM service in android studio

Then, Add the below links of notification service codes.

FirebaseCloudMessagingService.java

package com.protocoderspoint.sendingpushnotificationusingphpcode;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FirebaseCloudMessagingServices extends FirebaseMessagingService {
    public FirebaseCloudMessagingServices() {
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        if (remoteMessage.getNotification() != null) {
            String title = remoteMessage.getNotification().getTitle(); // will hold FCM Title
            String message = remoteMessage.getNotification().getBody(); //will hold FCM message body
            sendNotification(title,message);
        }
    }

    private void sendNotification(String title, String message) {

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "admin_channel_1";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
            // Configure the notification channel.
            notificationChannel.setDescription("Sample Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        
        notificationBuilder.setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //.setPriority(Notification.PRIORITY_MAX)
                .setContentTitle(title)
                .setContentText(message);
        notificationManager.notify(1, notificationBuilder.build());
    }
}

Step 4: Add Volley Library

As we gonna make a call to our php script to send notification in am making use of Volley library to make a call to my service side php code

open build.gradle(app level)  and all the following volley dependencies.

implementation 'com.android.volley:volley:1.1.0'

Step 5: Register/ Subscribe to Topic in java code

This is how we make the user to register or subscribe to particular topic so that we can  send notification to selected topic or subscriber using the topic that user are registered too.

Snippet code to make user subscribe to a topic in FCM.

FirebaseMessaging.getInstance().subscribeToTopic("Gadgets");

 

Now, open strings.xml and add the following array strings

strings.xml

<resources>
    <string name="app_name">Sending PushNotification using php code</string>

    <string name="topic_selection">Choose a category: </string>

    <string-array name="product_topics">
        <item>PC</item>
        <item>Laptop</item>
        <item>Gadgets</item>
    </string-array>

</resources>

ok Then, Let’s design the UI of the app

acitivity_main.xml

<?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:id="@+id/subscribe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subscribe on Topic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.269" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="409dp"
        android:layout_height="80dp"
        android:layout_marginTop="64dp"
        android:entries="@array/product_topics"
        android:gravity="center"
        android:prompt="@string/topic_selection"
        app:layout_constraintBottom_toTopOf="@+id/subscribe"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.685" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="22dp"
        android:text="You will get notified on selected topic only"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/subscribe" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select a Firebase topic to get subscribed on particular topic only"
        app:layout_constraintBottom_toTopOf="@+id/spinner"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/getnotified"
        android:layout_width="247dp"
        android:layout_height="51dp"
        android:layout_marginTop="276dp"
        android:text="Notify Me"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Below button will call the php code that sends notification \n to Cloud messaging service topic you are subscribed to"
        app:layout_constraintBottom_toTopOf="@+id/getnotified"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.84" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.protocoderspoint.sendingpushnotificationusingphpcode;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessaging;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private FirebaseAnalytics mFirebaseAnalytics;

    Spinner spinnerTopic;
    Button subscribe,send_Pushnotification;
    // this link is my server where my php script for push notification exist
    String  URL_NOTI="https://protocoderspoint.com/php/push_notification.php";
    String topic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        spinnerTopic = (Spinner)findViewById(R.id.spinner);
        subscribe=(Button)findViewById(R.id.subscribe);
        send_Pushnotification=(Button)findViewById(R.id.getnotified);


        subscribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                topic = spinnerTopic.getSelectedItem().toString();
                System.out.println(topic);

                //subscribing yourself to topic you have selected from spinner

                FirebaseMessaging.getInstance().subscribeToTopic(topic);

                Toast.makeText(MainActivity.this,"Subscribed successfully to:  "+topic,Toast.LENGTH_SHORT).show();

                Toast.makeText(MainActivity.this,"Now just Hit Notify me Button "+topic,Toast.LENGTH_SHORT).show();
            }
        });

        send_Pushnotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Send_Notification(topic);
            }
        });
    }

    private void Send_Notification(final String topic)
    {


        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_NOTI,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("farmerorderdataresponse",response);
                        try{




                        } catch (Exception e) {
                            e.printStackTrace();

                            Toast.makeText(getApplicationContext(),"Login Error !1"+e,Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(),"Login Error !2"+error,Toast.LENGTH_LONG).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() {
                Map<String,String> params = new HashMap<>();

                params.put("title","Order Received");
                params.put("body","This is a notification");
                params.put("topic",topic);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

    }
}

Step 5: network configuration for android version 9

then you need to add a network configuration xml file where you define the network that you will be using…Usually the domain

res (right click) > New > Directory

give new diretory name as “xml”

Then, right click “xml directory” > New > xml resource file and name it as network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">

        //replace the domain name with your server domain name
        <domain includeSubdomains="true">protocoderspoint.com</domain>

    </domain-config>
</network-security-config>

Step 6: PHP script to send FCM push notification

<?php
    $user= $_POST['topic'];
    $title = $_POST['title'];
    $body = $_POST['body'];
    $url = "https://fcm.googleapis.com/fcm/send";

    $topic = "/topics/$user";

    //replace serverkey with your firebase console project server key
    $serverKey = "AAAADmPIVdUXXXXXXEbfiR9c5LyXRKgq1LAWhT6a-byFe7lPXXXXXXXTjJfhHTTIo7Q997PL-89KrKagTQz26FUmyhRmhmsxQXXXXXXXWBmOuJ4-wtY_uL1-si8l3hyr5zJ-2P";

    //$body = '$_POST['body']';
  //  $intent_filter=$action;
    $notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
    $arrayToSend = array('to' => $topic, 'notification' => $notification,'priority'=>'high');
    $json = json_encode($arrayToSend);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key='. $serverKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
    //Send the request
    $response = curl_exec($ch);
    //Close request
    if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
?>

How to get serverkey of FCM service ?

how to get server key of firebase cloud messaging

Then, where you go your app is ready to subscribe to selected topic using Spinner and will be able to recieve push notification on particular topic the app user is subscribed too firebase cloud messaging service.