Skip to main content

FireBase Notification

Gradles
compile 'com.google.firebase:firebase-core:10.0.1'compile 'com.google.firebase:firebase-messaging:10.0.1'


manifest file
<!-- [START firebase_service] --><service android:name=".fcm.MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

<service android:name=".fcm.MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>


Create google-service.jason file from firebase console and add into your project.


MyFirebaseInstanceIDService
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.healthbanc.utility.HealthBancConstants;
import com.healthbanc.utility.Utils;


/** * Created by ziya on 24/6/16. */public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";
    SharedPreferences pref;

    /**     * 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);

        // TODO: Implement this method to send any registration to your app's servers.        storeToken(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 storeToken(String token) {
        // Add custom implementation, as needed.        pref = getSharedPreferences(HealthBancConstants.PREF_NAME, Context.MODE_PRIVATE);
        Utils.storeValueSharePref(pref, HealthBancConstants.PREF_DEVICETOKEN, token);
    }


    /*{        "Version": "2008-10-17",            "Statement": [        {            "Sid": "AllowPublicRead",                "Effect": "Allow",                "Principal": {            "AWS": "*"        },            "Action": "s3:GetObject",                "Resource": "arn:aws:s3:::healthbancweb*//*"        }        ]    }*/}




MyFirebaseMessagingService.java

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.healthbanc.R;
import com.healthbanc.activities.FacebookPostActivity;
import com.healthbanc.activities.MainActivity;
import com.healthbanc.models.PushNotificationModel;
import com.healthbanc.utility.ChatConstant;
import com.healthbanc.utility.HealthBancConstants;
import com.healthbanc.utility.Utils;
import com.healthbanc.utility.WebServiceParams;

import org.json.JSONObject;

import java.util.Map;

/** * Created by ziya on 24/6/16. */public classMyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";
    private String TYPE_LIKE = "like";
    private int CHECKIN = 1;
    private int SIGNUP = 2;
    private int SURVEYCOMPLETE = 3;
    private int SAVING = 4;  //Spend    private int REPOSTADS = 5;
    private int PROMOTION_APPROVED = 6;
    private int CHECKIN_APPROVED = 7;
    private int BOOKING_APPROVED = 8;
    private int BOOKING_CANCEL = 9;
    private int REFERRAL_APPROVED = 10;

    SharedPreferences pref;


    /**     * Called when message is received.     *     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.     */    // [START receive_message]    @Override    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO(developer): Handle FCM messages here.        // If the application is in the foreground handle both data and notification messages here.        // 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.

//        Bundle[{message = Tell your Friends about Healthbanc for 50 points for each referral//        and give the gift of better//        health, google.sent_time = 1492498898629, content - available = 0, sound = 1, vibrate = 1, params = {"notification_id"://        5366, "type":1, "fb_msg"://        "Hi I\u2019ve just checked in using the Healthbanc app saving me money on healthcare. Try downloading it..it\u2019s great."},//        badge = 7, from = 414684332221, google.message_id = 0:1492498898652886 % bc66deb2f9fd7ecd}]
        Map<String, String> data = remoteMessage.getData();
        pref = getSharedPreferences(HealthBancConstants.PREF_NAME, Context.MODE_PRIVATE);
        Log.d(TAG, "Notification Message  " + data.get("message"));

//        {//            "type":1, "fb_msg"://            "Hi I\u2019ve just checked in using the Healthbanc app saving me money on healthcare. Try downloading it..it\u2019s great."//        }        try {


//            }

            JSONObject object = new JSONObject(data.get("params"));
            Log.e(TAG, "onMessageReceived: " + data.get("params"));
            int type = object.getInt("type");

            String fb_msg = "";
            if (object.has("fb_msg")) {
                fb_msg = object.getString("fb_msg");
            }
            String generalMsg = data.get("message");


            /****             * fetch badge count             */
//            if (data.containsValue("badge")) {            String badge = data.get("badge");
            /**send broadcast to mainactivity to update chat counter in chat tab*/            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(WebServiceParams.UPDATE_BADGE_COUNT);
            broadcastIntent.putExtra(HealthBancConstants.EXTRA_BADGE_COUNT, Integer.parseInt(badge));

            /**reload points tabs**/            if (type == CHECKIN_APPROVED || type == SAVING || type == REFERRAL_APPROVED) {
                broadcastIntent.putExtra(HealthBancConstants.EXTRA_RELOAD_POINTS_TAB, true);
            }
            /**reload notification tab**/            else if (type == PROMOTION_APPROVED) {
                broadcastIntent.putExtra(HealthBancConstants.EXTRA_RELOAD_NOTIFICATION_TAB, true);
            }
            sendBroadcast(broadcastIntent);
            Utils.storeIntegerValueSharePref(pref, HealthBancConstants.PREF_BADGE_COUNT, Integer.parseInt(badge));

            if (type == PROMOTION_APPROVED) {
                sendNotification(generalMsg, fb_msg, type, object);
            } else {
                sendNotification(generalMsg, fb_msg, type, object);
            }


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

    }
    // [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, String fbMsg, int type, JSONObject object) {
        Log.e(TAG, "sendNotification: new notification" + messageBody);
        Intent intent;
        if (type == CHECKIN || type == SIGNUP || type == SAVING || type == REPOSTADS) {
            intent = new Intent(this, FacebookPostActivity.class);
            intent.putExtra(HealthBancConstants.EXTRA_MESSAGE, fbMsg);
            intent.putExtra(HealthBancConstants.EXTRA_NOTIFICATION_DETAIL, notificationDetails(object));
        } else if (type == BOOKING_APPROVED || type == BOOKING_CANCEL) {
            intent = new Intent(this, MainActivity.class);
            intent.putExtra(HealthBancConstants.EXTRA_NOTIFICATION_TYPE, ChatConstant.TYPE_NOTIFICATION_TAB);
        } else if (type == PROMOTION_APPROVED) {
            intent = new Intent(this, MainActivity.class);
            intent.putExtra(HealthBancConstants.EXTRA_NOTIFICATION_TYPE, ChatConstant.TYPE_PROMOTIONAL);
            intent.putExtra(HealthBancConstants.EXTRA_NOTIFICATION_DETAIL, notificationDetails(object));
        } else {
            intent = new Intent(this, MainActivity.class);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody)) // Makes it expandable to show the message                .build();


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


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


    private PushNotificationModel notificationDetails(JSONObject object) {
        try {
            if (object == null) {
                return null;
            }

            PushNotificationModel model = new PushNotificationModel();
            if (object.has("notification_id")) {
                model.notificationId = object.getString("notification_id");
            }

            if (object.has("doctor_id")) {
                model.doctorId = object.getString("doctor_id");
            }
            if (object.has("promotion_description")) {
                model.promotionalDesc = object.getString("promotion_description");
            }

            if (object.has("promotion_title")) {
                model.promotionalTitle = object.getString("promotion_title");
            }

            if (object.has("clinic_image")) {
                model.clinicImage = object.getString("clinic_image");
            }

            if (object.has("clinic_phone")) {
                model.clinicPhone = object.getString("clinic_phone");
            }

            if (object.has("clinic_name")) {
                model.clinicName = object.getString("clinic_name");
            }

            if (object.has("promotion_id")) {
                model.promotionalId = object.getString("promotion_id");
            }
            if (object.has("doctor_name")) {
                model.doctorName = object.getString("doctor_name");
            }

            if (object.has("type")) {
                model.type = object.getString("type");
            }

            if (object.has("clinic_id")) {
                model.clinicId = object.getString("clinic_id");
            }
            return model;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}



Dproject access link
https://drive.google.com/open?id=0B9QgU9aPC1LvMlpDVzhQMl9EYlE

Comments

Popular posts from this blog

Getview Method Wierd in Listview

Its common issue in android and most of newbee faced. To understand why its happening, you have to read about behavior of Getview method of listivew, its your home work, let continue with tutorial. Below tutorial will explain that how to maintain the position of button  which is in row file using settag and gettag. main.xml ( its contain listview which will hold row data) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:descendantFocusability="blocksDescendants">  <ListView         android:id="@+id/listView"         android:layout_width="fill_parent"         android:layout_height="fill_parent"/> </LinearLayout> ...

Amazon S3 Configuration

Gradles //amazon s3 compile 'com.amazonaws:aws-android-sdk-core:2.2.+' compile 'com.amazonaws:aws-android-sdk-s3:2.2.+' Declare in manefiest file <!--AMAZON S3--> < service android :name= "com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android :enabled= "true" /> AmazonUtils.java import android.content.Context; import android.net.Uri; import com.amazonaws.auth.CognitoCachingCredentialsProvider; import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver; import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3Client; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.UUID; /* * Handles basic helper functions used throughout the app. */ public class AmazonUtil { // We only n...
Update Progress in notification: public class NetworkService extends IntentService {     public static final String FILE_PATH = "file_path";     public static final String _FILE_PATH = "_path";     public static final String PERCENT_EXTRA = "percent";     public static final String FILE_NAME_EXTRA = "FileName";     public static final String STATE_EXTRA = "state";     public static final String IS_ALBUM_UPLAODING = "IsAlbumUplaoding";     public static final String XML = "xml";     public static final String TOKEN = "token";     public static final String MESSAGE = "mesasge";     public static final String POST_DATE = "postdate";     public static final String USERID = "userid";     public static final String GROUPID = "groupid";     public static final String PATH = "path"; ...