Monday, 12 August 2019

FCM Client App and the Server Sample which sends token to FCM which will PUSH to the Client


Following Dependencies in Gradle



implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.firebase:firebase-analytics:16.3.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.firebase:firebase-messaging:17.6.0'
implementation 'com.google.firebase:firebase-core:16.0.9'

Following service class

public class MyFirebaseInstanceIdService extends FirebaseMessagingService {





    @Override    
       public void onNewToken(String token) {
        super.onNewToken(token);
        Log.e("Refreshed token:",token);


        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preferences.edit().putString("fcmToken",token).apply();
    }


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

       //if the message contains data payload        
       //It is a map of custom keyvalues        //we can read it easily        
        if(remoteMessage.getData().size() > 0){
            //handle the data message here    }

        //getting the title and the body        
        String title = remoteMessage.getNotification().getTitle();
        String body = remoteMessage.getNotification().getBody();

        //then here we can use the title and body to build a notification    
    }
}

Manifest Add the following



<service    android:name=".service.MyFirebaseInstanceIdService"android:stopWithTask="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />


Run the App you should be able to see token in logcat


We can then send this token to the webservice using HttpURLConnection to the server


public class SendPostRequest extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {


        try{

            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
             
            //For Emulator testing we can use this IP if we are running our server in 8080
            URL url = new URL("http://10.0.2.2:8080/register/token");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         //   conn.setReadTimeout(15000 /* milliseconds */);           // conn.setConnectTimeout(15000 /* milliseconds */);            
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty( "charset", "utf-8");
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches (false);
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("content" ,  sp.getString("fcmToken"," "));            
            Log.e("params",postDataParams.toString());
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
            writer.write(postDataParams.toString());


            writer.flush();
            writer.close();
            os.close();
            conn.connect();

            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in=new BufferedReader(
                        new InputStreamReader(
                                conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override    
     protected void onPostExecute(String result) {

        Toast.makeText(getApplicationContext(), result,
                Toast.LENGTH_LONG).show();
    }
    }


    

Call this in onCreate() or on Button Click



App Server has now the token it will send this to FCM which will PUSH Notification to the Client App




public class ServerDemo {

 //This is the server key which we will get from Firebase console our App and the FCM Tab we should select
 public final static String AUTH_KEY_FCM = "key=AAMMM";
 public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; 
      //This is the token which client App receives from FCM
 public static String CLIENT_TOKEN = null;

 public static void main(String[] args) throws IOException {

  FileOutputStream fileOutputStream = null;
  BufferedReader bufferedReader = null;

  try { 
 //Here we are fetching the token which we received from FCM
   URL url = new URL("http://localhost:8080/register/alltoken");

   bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
   fileOutputStream = new FileOutputStream("C:\\Softwares\\Test.txt");
   String input;

   while ((input = bufferedReader.readLine()) != null) {
    CLIENT_TOKEN = input;
    System.out.println(input);
    fileOutputStream.write(input.getBytes());
   }

   bufferedReader.close();
   fileOutputStream.close();
   // System.out.println(results.get(0));

  } catch (MalformedURLException me) {
   me.printStackTrace();
  } catch (IOException ie) {
   ie.printStackTrace();
  }

  sendPOST();
 }

 private static void sendPOST() throws IOException {
  System.out.println("Inside post "+CLIENT_TOKEN);
  URL obj = new URL(API_URL_FCM);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();
  con.setRequestMethod("POST");
  // con.setRequestProperty("User-Agent", USER_AGENT);

  // For POST only - START
  con.setDoOutput(true);

  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  con.setRequestProperty("Content-Type", "application/json");

  con.setRequestProperty("Authorization", AUTH_KEY_FCM);

  String postJsonData = "{\r\n" + 
    "  \"notification\": \r\n" + 
    "  {\r\n" + 
    "    \"title\": \"Hello Client This is From Server\",\r\n" + 
    "    \"text\": \"Your Text\",\r\n" + 
    "    \"sound\": \"default\",\r\n" + 
    "    \"badge\": \"1\",\r\n" + 
    "    \r\n" + 
    "    \"color\": \"#990000\",\r\n" + 
    "      \r\n" + 
    "    \r\n" + 
    "  },\r\n" + 
    "  \"priority\" : \"high\",\r\n" + 
    "  \"registration_ids\" : \r\n" + 
    "   [\r\n" + "\""+ 
          CLIENT_TOKEN+ "\""+ "\r\n" + 
    "    ]\r\n" + 
    "}";

  

  OutputStream os = con.getOutputStream();
  os.write(postJsonData.getBytes());
  os.flush();
  os.close();
  // For POST only - END
  con.connect();
  int responseCode = con.getResponseCode();
  System.out.println("POST Response Code :: " + responseCode);

  if (responseCode == HttpURLConnection.HTTP_OK) { // success
   BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
   String inputLine;
   StringBuffer response = new StringBuffer();

   while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
   }
   in.close();

   // print result
   System.out.println(response.toString());
  } else {
   System.out.println("POST request not worked");
  }
 }
}




No comments:

Post a Comment

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...