Sunday 14 May 2017

Implementation of firebase notification in android application

  No comments
In this post i will show you how to implement firebase notification in android application.Here is short summary what we'll do

In android part: we are generating the notification firebase token and then hit the rest api with that token and then stored the corresponding token into the database.

In Php part: By using the firesbase token we'd send the real time notification to the application.



When first time application open in real android device, we are showing a splash screen of application and also checking the internet, if internet available then we are sending the firebase token  
                          Android Part
splashscreen.java


package com.gangsofcoder;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;

/**
 * Created by suraj on 03-Oct-16.
 */
public class SplashScreen extends AppCompatActivity implements Animation.AnimationListener {

    Context ctx = SplashScreen.this;

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

        beginAnimation(ctx);


    }

    private void beginAnimation(Context ctx) {
        Animation animation = AnimationUtils.loadAnimation(ctx, R.anim.alpha);
        ImageView img = (ImageView) findViewById(R.id.gangsofcoder_logo);
        if (img != null) {
            img.setAnimation(animation);
        }
        animation.setAnimationListener(this);
    }

    private boolean checkConnectivity(Context ctx) {
        boolean STATUS = false;
        TelephonyManager tm = (TelephonyManager) ctx.getSystemService(ctx.TELEPHONY_SERVICE);
        if (tm != null) {
            if (tm.getDataState() == TelephonyManager.DATA_CONNECTED) {
                STATUS = true;
            } else {
                ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(ctx.CONNECTIVITY_SERVICE);
                if (cm != null) {
                    NetworkInfo networkInfo =        cm.getActiveNetworkInfo();
                    if (networkInfo != null) {
                        STATUS = networkInfo.isConnected();
                    }
                }
            }
        }

        return STATUS;
    }

    private void showErrorDialog(Context ctx) {

        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setTitle(getResources().getString(R.string.net_title));
        builder.setMessage(getResources().getString(R.string.net_message));
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setNegativeButton(getResources().getString(R.string.net_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton(getResources().getString(R.string.net_setting), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {

        if (checkConnectivity(ctx)) {

            FirebaseMessaging.getInstance().subscribeToTopic("gangsofcoder");
            FirebaseInstanceId.getInstance().getToken();

            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(intent);

        } else {
            showErrorDialog(ctx);
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }
}
MainActivity.java
package com.gangsofcoder;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView mWebView;
    private WebSettings mWebSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.wb_intizone);

        mWebSettings = mWebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);

        mWebView.setWebViewClient(new WebViewClient());
        mWebView.loadUrl("https://gangsofcoder.blogspot.in/");

        mWebView.setWebChromeClient(new WebChromeClient() {
            ProgressDialog pd = ProgressDialog.show(MainActivity.this, "Loading", "please wait...");

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress > 30) {
                    pd.dismiss();
                }
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    }else{
                        exitDialog(MainActivity.this);
                    }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exitDialog(Context ctx){

        AlertDialog.Builder builder=new AlertDialog.Builder(ctx);
        builder.setTitle(getResources().getString(R.string.alert_title));
        builder.setMessage(getResources().getString(R.string.alert_message));
        builder.setPositiveButton(getResources().getString(R.string.alert_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setNegativeButton(getResources().getString(R.string.alert_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog alertDialog=builder.create();
        alertDialog.show();
    }

}
MyFirebaseInstanceIdServices.java
package com.gangsofcoder;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by suraj on 04-Oct-16.
 */
public class MyFirebaseInstanceIdServices extends FirebaseInstanceIdService {

    String Token;

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        Token = FirebaseInstanceId.getInstance().getToken();

        registerToken(Token);
    }

    private void registerToken(String token) {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody mRequestBody = new FormBody.Builder()
                .add("TOKEN", token)
                .build();
        Request mRequest = new Request.Builder()
                .url("http://192.168.1.103/intizone_fcm/register.php")
                .post(mRequestBody)
                .build();

        try {
            okHttpClient.newCall(mRequest).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
MyFirebaseMessagingServices.java
package com.gangsofcoder;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by suraj on 04-Oct-16.
 */
public class MyFirebaseMessagingServices extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        String msg = remoteMessage.getData().get("message");
        if (msg != null) {
            showNotification(msg);
        }
    }

    private void showNotification(String message) {

        Intent i;
        i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle("gangofcoder")
                //.setContentText(message+"\n"+url)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setContentText(message)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Notification notification = builder.build();
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.ledARGB = 0xffffffff;
        notification.ledOnMS = 300;
        notification.ledOffMS = 1000;

        manager.notify(0, notification);
    }
}
                             Php Part
Code to insert the token into database
<?php
 
 if(isset($_POST["TOKEN"]))
 {
  
 $token = $_POST["TOKEN"];
 
 $conn = mysqli_connect("localhost","root","","gangsofcoder");
 
 $insert_query = "INSERT INTO gangsofcoder_register(register_token) VALUES('$token') ON  DUPLICATE KEY UPDATE register_token = '$token'";
 
 mysqli_query($conn,$insert_query);
 mysqli_close($conn);
  
 } 
?>
Code to send real time notification
<!DOCTYPE html>

<html>
 <head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="css/style.css" rel="stylesheet" type="text/css">

 <title>gangsofcoder push notification</title>
 
 </head>
 
 <style>
 
 div.check{
  width:100%;
  background-color:#1b1b1c;
  height:10%;
  padding-top: 15px;
 } 
 body{
  background-color:#1b1b1c;
 }
 #success{
  margin-top:50px;
  text-align:center;
 }
 button{
  
 }

 </style>
 
 <body>
 
 <div class="check">
 
 <div class="container"> 
 
      <div class="col-md-12" style="padding:10px;">
       <div class="col-md-4">
    <img src="img/logo_gangsofcoder.png" height="100" weight="100"/>
     </div>
 
      </div> </div>

 </div>
 
 <form method='post' action='gangs_send.php' style="text-align: center;
    margin-top: 2%;">
   
   <div class="container"> 
   
   <div class="col-md-12" style="text-align: center;margin: 10px;">
                <input type="text"  name="message" placeholder="Enter a message" style="border-radius: 10px; border: 1px solid #000000;  width: 100%; height: 70px; padding: 25px;color:#ED1468 ;font-size:300%" required>
   </div>
     
   <div class="col-md-4">
   </div>
    
   <div class="col-md-4">
    <button id="button" style="border-radius: 6px; border: 1px solid #ffffff; color: #ffffff; width: 60%; height: 60px; background-color: #1b1b1c;  color: #fff; margin-top:20px"  >Send Notification</button>
   </div>
   
   <div class="col-md-4">
   </div>
     
   </div>
  </form>
  
  <p id="success">
   
   <?php
    //if success request came displaying success message 
    if(isset($_REQUEST['success'])){
     echo "<font color=#FFFFFF><strong>Cool!</strong> Message sent successfully check your device...</font>";
    }
    //if failure request came displaying failure message 
    if(isset($_REQUEST['failure'])){
     echo "<font color=#FFFFFF;><strong>Oops!</strong> Could not send message check API Key and Token...</font>";
    }
   ?>
   
  </p>
  <!--
  <div>Total Views <br /><span><?php echo $count; ?></span></div>
  

  
 </body>
 
</html>
code of php end which help to send notification 
<?php


//Checking http request we are using post here 
if($_SERVER['REQUEST_METHOD']=='POST'){
 
 //Getting api key  
 $api_key = 'Your Api key here'; 
 
 //Getting registration token we have to make it as array 
 
 $conn = mysqli_connect("localhost", "root", "", "gangsofcoder");
 $sql = "SELECT register_token FROM gangsofcoder_register";
 $result = mysqli_query($conn, $sql);
 $tokens = array();
 //$ids = array();
 
 if(mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_assoc($result)){
   //$ids[] = $row["id"];
   $tokens[] = $row["register_token"];
  }
 }
 
 mysqli_close($conn);
 
 //$reg_token = array($_POST['regtoken']);
 
 //Getting the message 
 $message = $_POST['message'];
 
 //Creating a message array 
 $msg = array
 (
  'message'  => $message,
  'title'  => 'Message from FCM',
  'subtitle' => 'Android Push Notification using FCM Demo',
  'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
  'vibrate' => 1,
  'sound'  => 1,
  'largeIcon' => 'large_icon',
  'smallIcon' => 'small_icon'
 );
 
 //Creating a new array fileds and adding the msg array and registration token array here 
 $fields = array
 (
  //'registration_ids'  => $reg_token,
  'registration_ids'  => $tokens,
  'data'   => $msg
 );
 //Adding the api key in one more array header 
 $headers = array
 (
  'Authorization: key=' . $api_key,
  'Content-Type: application/json'
 ); 
 //Curl is used to make remote request
 
 $ch = curl_init();
 curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
 curl_setopt( $ch,CURLOPT_POST, true );
 curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
 curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
 curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
 curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode($fields ));
 
 //Getting the result 
 $result = curl_exec($ch );
 curl_close( $ch );
 
 //Decoding json from result 
 $res = json_decode($result);

 //Getting value from success 
 $flag = $res->success;
 //print_r ($flag);
 //exit();
 //if success is 1 means message is sent 
 //if($flag == 1){
 
 if($flag == count($tokens)){
  //Redirecting back to our form with a request success 
  header('Location: gangs_index.php?success');
 }else{
  //Redirecting back to our form with a request failure 
  header('Location: gangs.php?failure');
 }
 
}





No comments :

Post a Comment

Loading...