Skip to content

Instantly share code, notes, and snippets.

@Muhaiminur
Last active April 2, 2020 08:27
Show Gist options
  • Save Muhaiminur/f0d05f53fb2b0f5a6f3419c6514f0ca5 to your computer and use it in GitHub Desktop.
Save Muhaiminur/f0d05f53fb2b0f5a6f3419c6514f0ca5 to your computer and use it in GitHub Desktop.
Notification activity
package com.gtech.fishbangla.FIREBASE;
import android.app.Notification;
import android.app.NotificationChannel;
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.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.gtech.fishbangla.Activity.Cart_Activity;
import com.gtech.fishbangla.Activity.Home_Page;
import com.gtech.fishbangla.Library.KeyWord;
import com.gtech.fishbangla.Library.Utility;
import com.gtech.fishbangla.R;
import java.net.URL;
import java.util.Map;
public class FISHBANGLA_FIREBASE extends FirebaseMessagingService {
private static final String TAG = "FISHBANGLA";
Utility utility = new Utility(this);
NotificationManager notificationManager;
/**
* 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) {
// [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. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> data = remoteMessage.getData();
String title = data.get("title");
String body = data.get("body");
String image_url = data.get("image_url");
String big_text = data.get("big_text");
String metadataBrowse = data.get("metadataBrowse");
String metadata = data.get("metadata");
Log.d(TAG, "From: " + remoteMessage.getFrom());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//sendNotification(title, msg, value1, value2);
//createNotification(title);
SHOW_NOTIFICATION(title, body, image_url, big_text, metadataBrowse, metadata);
}
// 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.
//sendNotification("FISHBANGLA");
//sendNotification(title, msg, value1, value2);
}
// [END receive_message]
// [START on_new_token]
/**
* 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.
*/
@Override
public void onNewToken(String token) {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
// 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(token);
}
});
Log.d(TAG, "Refreshed token: " + token);
}
// [END on_new_token]
private void sendRegistrationToServer(String token) {
utility.setFirebaseToken(token);
}
public void SHOW_NOTIFICATION(String title, String body, String image_url, String big_text, String metadataBrowse, String metadata) {
try {
createNotificationChannel();
int notifyId = (int) System.currentTimeMillis();
Intent intent = new Intent(this, Home_Page.class);
if (metadataBrowse != null && !TextUtils.isEmpty(metadataBrowse) && metadata != null && !TextUtils.isEmpty(metadata)) {
utility.logger("paisi");
intent.putExtra("NOTIFICATION", "yes");
intent.putExtra("metadataBrowse", metadataBrowse);
intent.putExtra("metadata", metadata);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notifyId, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, KeyWord.NOTIFICATION_CHANNEL_NAME)
.setContentTitle(title)
.setSmallIcon(R.drawable.ribbon)
.setContentText(body)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(title)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ribbon))
/*.setStyle(new NotificationCompat.BigTextStyle()
.bigText(body))*/
/*.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(*//*BitmapFactory.decodeResource(getResources(), R.drawable.ribbon)*//*Glide
.with(this)
.asBitmap()
.load("http://116.212.109.34:9090/content/resources/images/banner/3/20200318_9.jpg")
.submit()
.get())
.bigLargeIcon(null))*/
.setPriority(Notification.PRIORITY_MAX);
if (image_url != null && !TextUtils.isEmpty(image_url)) {
builder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(Glide.with(this).asBitmap().load(image_url).submit().get()));
} else if (big_text != null && !TextUtils.isEmpty(big_text) && big_text.equalsIgnoreCase(KeyWord.YES)) {
builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText(body));
}
notificationManager.notify(notifyId, builder.build());
} catch (Exception e) {
Log.d("Error Line Number", Log.getStackTraceString(e));
}
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(KeyWord.NOTIFICATION_CHANNEL_NAME, name, importance);
channel.setDescription(description);
channel.enableVibration(true);
channel.setLightColor(getColor(R.color.app_red));
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
notificationManager.createNotificationChannel(channel);
}
}
}
{
"to" : "eI-vpsNjS2qWbvOzXrwSh_:APA91bGb9tUm8x6eyXbi5HOH2PK0nDje3L3oKx87L7ff0vecIO-JlJDmv7IZzwiZi7y1LGP5JTBw78UqWrBR6qIa7ej1xAmMU2DNErQrx6mp9OjQOQEwJhg6CXCoVo-H78OgOXPs9tsE",
"priority": "high",
"data" : {
"body" : "এ নিয়ে এই ভাইরাসে আক্রান্ত হয়ে দেশে ছয়জনের মৃত্যু হ স্বাস্থ্যমন্ত্রী।",
"title": "করোনাভাইরাসে দেশে আরও একজনের মৃত্যু: স্বাস্থ্যমন্ত্রী",
"image_url" : "http://www.gentertainmentbd.club/wp-content/uploads/2019/10/cropped-gtech-2-232x77.png",
"big_text" : "",
"metadataBrowse": "EXTERNAL",
"metadata" : "http://www.fishbangla.com/",
"icon_path" : "http://www.radiogbd.com/images/logo.png"
}
},
//for custom notification on both background and forground remove notification payloads
"notification" : {
"click_action" : "com.gtech.fishbangla.FCM_NOTIFICATION",
"body" : "First Notification backgraound",
"title" : "new Symulti update !",
"icon" : "",
"image": ""
}
}
Head:
Authorization:key=AAAA6tmssT4:APA91bF82FT31AbDt9Mk33_NEUuDULlclyTiyuQOJWjAZR3f9AKrvRZjrxUN_tBNWnzw7qSf4pqcpx_906x8QA5pgrgpTzeU0v1YLBVIz99BsGjIQU1Wd1fSWYi_2ZGeUI_qJgEKKCr7
Content-Type:application/json
Link:https://fcm.googleapis.com/fcm/send
package com.heizolscout.itclanbd.heizolscout;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* 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) {
// [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. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> data = remoteMessage.getData();
String value1 = data.get("key_1");
String value2 = data.get("key_2");
String title=data.get("title");
String msg=data.get("body");
Log.d("Backgraound", value1);
Log.d(TAG, "From: " + remoteMessage.getFrom());
sendNotification("Heizolscout");
}
// 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.
sendNotification("Heizolscout");
sendNotification(title,msg,value1,value2);
}
// [END receive_message]
// [START on_new_token]
/**
* 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.
*/
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
// 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(token);
}
// [END on_new_token]
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
/**
* 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);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo_white_small)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
private void sendNotification(String title,String messageBody, String val1,String val2) {
try {
Intent intent = new Intent(this, Notification_activity.class);
//Bundle bundle = getApplicationContext().getExtras();
Bundle basket = new Bundle();
basket.putString("key_1", val1);
basket.putString("key_2", val2);
intent.putExtras(basket);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.spacebar_round)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setColor( getResources().getColor(R.color.colorPrimary))
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.mipmap.ic_launcher));
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}catch (Exception e){
}
}
}
//Manifest File
<activity
android:name=".Activity.Home_Page"
android:label="@string/title_activity_home__page"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="com.gtech.fishbangla.FCM_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Activity.Landing_Page"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".FIREBASE.FISHBANGLA_FIREBASE"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_red_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment