Skip to content

Instantly share code, notes, and snippets.

@prasad091
Last active March 24, 2017 10:37
Show Gist options
  • Save prasad091/3cba9d6c50d607a157aab2ba49dee467 to your computer and use it in GitHub Desktop.
Save prasad091/3cba9d6c50d607a157aab2ba49dee467 to your computer and use it in GitHub Desktop.
package com.kgisl.messenger.data.fcm;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
/**
* Created by Prasad Thangavel on 12-12-2016.
*/
public class ChatFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "ChatFirebaseIIDService";
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
storeToken(refreshedToken);
}
private void storeToken(String token) {
//saving the token on shared preferences
SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
}
}
package com.kgisl.messenger.data.fcm;
import android.app.NotificationManager;
import android.content.Intent;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.kgisl.messenger.ui.ChatingActivity;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Prasad Thangavel on 12-12-2016.
*/
public class ChatFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "ChatFirebaseMsgService";
private NotificationManager mNotificationManager;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
sendPushNotification(json);
EventBus.getDefault().post(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
//this method will display the notification
//We are passing the JSONObject that is received from
//firebase cloud messaging
private void sendPushNotification(JSONObject json) {
//optionally we can display the json into log
Log.e(TAG, "Notification JSON " + json.toString());
try {
//getting the json data
JSONObject data = json.getJSONObject("data");
//parsing json data
String title = data.getString("title");
String message = data.getString("message");
String type = data.getString("type");
String imageUrl = data.getString("url");
//creating MyNotificationManager object
ChatNotificationManager mNotificationManager = new ChatNotificationManager(getApplicationContext());
//creating an intent for the notification
Intent intent = new Intent(getApplicationContext(), ChatingActivity.class);
//if there is no image
if(type.equals("null")){
//displaying small notification
mNotificationManager.showSmallNotification(title, message, intent);
}else if(type.equals("image")){
//if there is an image
//displaying a big notification
mNotificationManager.showBigNotification(title, message, type,imageUrl, intent);
} else if(type.equals("voice")){
mNotificationManager.showSmallNotification("Voice Message", type, intent);
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
package com.kgisl.messenger.data.fcm;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import com.kgisl.messenger.R;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Prasad Thangavel on 12-12-2016.
*/
public class ChatNotificationManager {
public static final int ID_BIG_NOTIFICATION = 234;
public static final int ID_SMALL_NOTIFICATION = 235;
final static String GROUP_KEY_EMAILS = "group_key_emails";
private Context mCtx;
public ChatNotificationManager(Context mCtx) {
this.mCtx = mCtx;
}
//the method will show a big notification with an image
//parameters are title for message title, message for message text, url of the big image and an intent that will open
//when you will tap on the notification
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void showBigNotification(String title, String message, String type,String url, Intent intent) {
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mCtx,
ID_BIG_NOTIFICATION,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
/* NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(getBitmapFromURL(url));*/
Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
inboxStyle.setBigContentTitle(title);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx);
Notification notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.setContentTitle("2 messages")
.setStyle(new NotificationCompat.InboxStyle()
.addLine(title)
.addLine(message)
.setBigContentTitle(title)
.setSummaryText(message))
.setGroup(GROUP_KEY_EMAILS)
.setGroupSummary(true)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ID_BIG_NOTIFICATION, notification);
}
//the method will show a small notification
//parameters are title for message title, message for message text and an intent that will open
//when you will tap on the notification
public void showSmallNotification(String title, String message, Intent intent) {
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mCtx,
ID_SMALL_NOTIFICATION,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
int numMessages = 0;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx);
Notification notification;
notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher))
.setContentText(message).setNumber(++numMessages)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ID_SMALL_NOTIFICATION, notification);
}
//The method will return Bitmap from an image URL
private Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
//first paste
@FormUrlEncoded
@POST("chats/v1/rest/textMessage.php")
Call<ResponseBody> sendChat(@Field("regId") String regId,
@Field("title") String title,
@Field("message") String message,
@Field("area") String area,
@Field("adharnumber") String adharnumber);
// second paste
public void sendChatMessage(){
String title = "Push message";
String messages = "Hello How r u"
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit build = new Retrofit.Builder()
.baseUrl(Config.EMULATOR_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ApiService api = build.create(ApiService.class);
Call<ResponseBody> responseBodyCall = api.sendChat(getRegId(),title,messages,"saravanampatti","454545");
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Log.v("Response",response.body().toString());
System.out.println("url:"+response.raw().request().url());
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
package com.kgisl.messenger.data.fcm;
import android.os.Bundle;
/**
* Created by admin on 13-12-2016.
*/
public final class RemoteNotification {
public static final int TYPE_STACK = -1000;
protected Bundle mExtrasBundle;
protected int mUserNotificationId = -1;
protected RemoteNotification() {}
public RemoteNotification(Bundle bundle) {
mExtrasBundle = bundle;
mUserNotificationId = (int)(System.currentTimeMillis() / 1000);
}
public Bundle getBundle() {
if (mExtrasBundle == null) {
mExtrasBundle = new Bundle();
}
return mExtrasBundle;
}
public String getAppName() {
return getBundle().getString("app_name");
}
public String getErrorName() {
return getBundle().getString("title");
}
public String getActivityText() {
return getBundle().getString("activity_text");
}
public String getUrl() {
return getBundle().getString("url");
}
public String getUserNotificationGroup() {
// error URLs are unique, and can be used to group
// related activities in the notification drawer
return getUrl();
}
public int getUserNotificationId() {
return mUserNotificationId;
}
}
package com.kgisl.messenger.data.fcm;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
/**
* Created by Prasad Thangavel on 12-12-2016.
*/
public class SharedPrefManager {
private static final String SHARED_PREF_NAME = "FCMSharedPref";
private static final String TAG_TOKEN = "tagtoken";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//this method will save the device token to shared preferences
public boolean saveDeviceToken(String token){
Log.v("token",token);
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TAG_TOKEN, token);
editor.commit();
return true;
}
//this method will fetch the device token from shared preferences
public String getDeviceToken(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(TAG_TOKEN, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment