Skip to content Skip to sidebar Skip to footer

How To Send Notifucation Using Firebase By Android Side Coding?

I am try to send notification using firebase using android side code. please suggest me how can I do. Please help me. Thanks in advance

Solution 1:

First of all make sure you have an firebase project, if no than create one. After that store the device id(firebase token) while registering the device using this code.

classMyFirebaseInstanceIDServiceextendsFirebaseInstanceIdService{
privatestaticfinalString TAG = "MyFirebaseIIDService";

/**
 * Called if InstanceID token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the InstanceID token
 * is initially generated so this is where you would retrieve the token.
 */// [START refresh_token]
@Override
publicvoid onTokenRefresh() {
    // Get updated InstanceID token.String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // If you want to send messages to this application instance or// manage this apps subscriptions on the server side, send the// Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]/**
 * Persist token to third-party servers.
 * <p>
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */privatevoid sendRegistrationToServer(finalString token) {
    new SharedPrefUtil(getApplicationContext()).saveString(Constants.ARG_FIREBASE_TOKEN, token);

    if (FirebaseAuth.getInstance().getCurrentUser() != null) {
        FirebaseDatabase.getInstance()
                .getReference()
                .child(Constants.ARG_USERS)
                .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .child(Constants.ARG_FIREBASE_TOKEN)
                .setValue(token);
    }
}}

after that send notification to the user you want using following code-

 void sendPushNotificationToReceiver(String username,
                                            String message,
                                            String uid,
                                            String firebaseToken,
                                            String receiverFirebaseToken) {
  Log.d(":asdfasd",username+"  "+message);
    FcmNotificationBuilder.initialize()
            .title(username)
            .message(message)
            .username(username)
            .uid(uid)
            .firebaseToken(firebaseToken)
            .receiverFirebaseToken(receiverFirebaseToken)
            .send();
}

here is the FCMNotificationBuilder class-

classFcmNotificationBuilder {
publicstaticfinalMediaTypeMEDIA_TYPE_JSON= MediaType.parse("application/json; charset=utf-8");
privatestaticfinalStringTAG="FcmNotificationBuilder";
privatestaticfinalStringSERVER_API_KEY="YOUR SERVER API KEY";
privatestaticfinalStringCONTENT_TYPE="Content-Type";
privatestaticfinalStringAPPLICATION_JSON="application/json";
privatestaticfinalStringAUTHORIZATION="Authorization";
privatestaticfinalStringAUTH_KEY="key=" + SERVER_API_KEY;
privatestaticfinalStringFCM_URL="https://fcm.googleapis.com/fcm/send";
// json related keysprivatestaticfinalStringKEY_TO="to";
privatestaticfinalStringKEY_NOTIFICATION="notification";
privatestaticfinalStringKEY_TITLE="title";
privatestaticfinalStringKEY_TEXT="text";
privatestaticfinalStringKEY_DATA="data";
privatestaticfinalStringKEY_USERNAME="username";
privatestaticfinalStringKEY_UID="uid";
privatestaticfinalStringKEY_FCM_TOKEN="fcm_token";

private String mTitle;
private String mMessage;
private String mUsername;
private String mUid;
private String mFirebaseToken;
private String mReceiverFirebaseToken;

privateFcmNotificationBuilder() {

}

publicstatic FcmNotificationBuilder initialize() {
    returnnewFcmNotificationBuilder();
}

public FcmNotificationBuilder title(String title) {
    mTitle = title;
    returnthis;
}

public FcmNotificationBuilder message(String message) {
    mMessage = message;
    returnthis;
}

public FcmNotificationBuilder username(String username) {
    mUsername = username;
    returnthis;
}

public FcmNotificationBuilder uid(String uid) {
    mUid = uid;
    returnthis;
}

public FcmNotificationBuilder firebaseToken(String firebaseToken) {
    mFirebaseToken = firebaseToken;
    returnthis;
}

public FcmNotificationBuilder receiverFirebaseToken(String receiverFirebaseToken) {
    mReceiverFirebaseToken = receiverFirebaseToken;
    returnthis;
}

publicvoidsend() {
    RequestBodyrequestBody=null;
    try {
        requestBody = RequestBody.create(MEDIA_TYPE_JSON, getValidJsonBody().toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    Requestrequest=newRequest.Builder()
            .addHeader(CONTENT_TYPE, APPLICATION_JSON)
            .addHeader(AUTHORIZATION, AUTH_KEY)
            .url(FCM_URL)
            .post(requestBody)
            .build();

    Callcall=newOkHttpClient().newCall(request);
    call.enqueue(newCallback() {
        @OverridepublicvoidonFailure(Call call, IOException e) {
            Log.e(TAG, "onGetAllUsersFailure: " + e.getMessage());
        }

        @OverridepublicvoidonResponse(Call call, Response response)throws IOException {
            Log.e(TAG, "onResponse: " + response.body().string());
        }
    });
}

private JSONObject getValidJsonBody()throws JSONException {
    JSONObjectjsonObjectBody=newJSONObject();
    jsonObjectBody.put(KEY_TO, mReceiverFirebaseToken);

    JSONObjectjsonObjectData=newJSONObject();
    jsonObjectData.put(KEY_TITLE, mTitle);
    jsonObjectData.put(KEY_TEXT, mMessage);
    jsonObjectData.put(KEY_USERNAME, mUsername);
    jsonObjectData.put(KEY_UID, mUid);
    jsonObjectData.put(KEY_FCM_TOKEN, mFirebaseToken);
    jsonObjectBody.put(KEY_DATA, jsonObjectData);

    return jsonObjectBody;
}}

and receive notifications as normally we do using services. This is working for me in my chat application , hope it will help you also.

Solution 2:

First thing is to get the Token of the user you want to send the notification to. Then I use this code in an AsyncTask

protectedStringdoInBackground(String... strings) {
        try{
            JSONObject jo = newJSONObject();
            jo.put("message", "<Message>"));
            jo.put("title", "<Message Title>");

            JSONObject mainObj = newJSONObject();
            mainObj.put("to",<TOKEN_OF_DEVICE>);
            mainObj.put("data", jo);

            URL url = newURL("https://android.googleapis.com/gcm/send");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "key=<API_KEY>");
            connection.setDoOutput(true);

            //Log.e("sent",mainObj.toString());DataOutputStream dStream = newDataOutputStream(connection.getOutputStream());
            dStream.writeBytes(mainObj.toString());
            dStream.flush();
            dStream.close();

            String line;
            int responseCode = connection.getResponseCode();
            //Log.e("code", responseCode+" hi");BufferedReader br = newBufferedReader(newInputStreamReader(connection.getInputStream()));
            StringBuilder responseOutput = newStringBuilder();
            while((line = br.readLine()) != null ){
                responseOutput.append(line);
            }
            br.close();
            //Log.e("output", responseOutput.toString());
        }
        catch (Exception e){
            e.printStackTrace();
        }
        returnnull;
    }

Solution 3:

First of all connect Firebase to your project from Android Studio. Generate token Follow the link Firebase Notification

Also sample github code link isGithub code

publicclassMyFirebaseMessagingServiceextendsFirebaseMessagingService {

privatestaticfinalStringTAG="MyFirebaseMsgService";

/**
 * Called when message is received.
 *
 * remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */// [START receive_message]@OverridepublicvoidonMessageReceived(RemoteMessage remoteMessage) {
    // [START_EXCLUDE]// There are two types of messages data messages and notification messages. Data messages are handled// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app// is in the foreground. When the app is in the background an automatically generated notification is displayed.// When the user taps on the notification they are returned to the app. Messages containing both notification// and data payloads are treated as notification messages. The Firebase console always sends notification// messages. // [END_EXCLUDE]// TODO(developer): Handle FCM messages here.// Not getting messages here?  // Log.d(TAG, "From: " + remoteMessage.getFrom());
    sendNotification(remoteMessage.getNotification().getBody());

    // Check if message contains a data payload.if (remoteMessage.getData().size() > 0) {
     //   Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.if (remoteMessage.getNotification() != null) {
       // Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */privatevoidsendNotification(String messageBody) {
    Intentintent=newIntent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntentpendingIntent= PendingIntent.getActivity(this, 0/* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.BuildernotificationBuilder=newNotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Title")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManagernotificationManager=
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0/* ID of notification */, notificationBuilder.build());
}

}

Post a Comment for "How To Send Notifucation Using Firebase By Android Side Coding?"