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.

class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String 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
public void 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.
 */
private void sendRegistrationToServer(final String 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-

class FcmNotificationBuilder {
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private static final String TAG = "FcmNotificationBuilder";
private static final String SERVER_API_KEY = "YOUR SERVER API KEY";
private static final String CONTENT_TYPE = "Content-Type";
private static final String APPLICATION_JSON = "application/json";
private static final String AUTHORIZATION = "Authorization";
private static final String AUTH_KEY = "key=" + SERVER_API_KEY;
private static final String FCM_URL = "https://fcm.googleapis.com/fcm/send";
// json related keys
private static final String KEY_TO = "to";
private static final String KEY_NOTIFICATION = "notification";
private static final String KEY_TITLE = "title";
private static final String KEY_TEXT = "text";
private static final String KEY_DATA = "data";
private static final String KEY_USERNAME = "username";
private static final String KEY_UID = "uid";
private static final String KEY_FCM_TOKEN = "fcm_token";

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

private FcmNotificationBuilder() {

}

public static FcmNotificationBuilder initialize() {
    return new FcmNotificationBuilder();
}

public FcmNotificationBuilder title(String title) {
    mTitle = title;
    return this;
}

public FcmNotificationBuilder message(String message) {
    mMessage = message;
    return this;
}

public FcmNotificationBuilder username(String username) {
    mUsername = username;
    return this;
}

public FcmNotificationBuilder uid(String uid) {
    mUid = uid;
    return this;
}

public FcmNotificationBuilder firebaseToken(String firebaseToken) {
    mFirebaseToken = firebaseToken;
    return this;
}

public FcmNotificationBuilder receiverFirebaseToken(String receiverFirebaseToken) {
    mReceiverFirebaseToken = receiverFirebaseToken;
    return this;
}

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

    Request request = new Request.Builder()
            .addHeader(CONTENT_TYPE, APPLICATION_JSON)
            .addHeader(AUTHORIZATION, AUTH_KEY)
            .url(FCM_URL)
            .post(requestBody)
            .build();

    Call call = new OkHttpClient().newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "onGetAllUsersFailure: " + e.getMessage());
        }

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

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

    JSONObject jsonObjectData = new JSONObject();
    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

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

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

            URL url = new URL("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 = new DataOutputStream(connection.getOutputStream());
            dStream.writeBytes(mainObj.toString());
            dStream.flush();
            dStream.close();

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

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

 public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/**
 * Called when message is received.
 *
 * remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(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.
 */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

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

    NotificationManager notificationManager =
            (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?"