Skip to content

Instantly share code, notes, and snippets.

@anandrex5
Last active July 28, 2022 20:52
Show Gist options
  • Save anandrex5/18a402e9d7a2df301a0e73972d1fd8b6 to your computer and use it in GitHub Desktop.
Save anandrex5/18a402e9d7a2df301a0e73972d1fd8b6 to your computer and use it in GitHub Desktop.
Notification_FireBase (Generate Notification through FireBase)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.notification_firebase">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Notification_FireBase"
tools:targetApi="31">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_launcher_foreground" />
<!-- 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/purple_700" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'com.google.gms.google-services'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.notification_firebase"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-messaging:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
package com.example.notification_firebase
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.notification)
}
}
package com.example.notification_firebase
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
const val channelId = "notification_channel"
const val channelName = "com.example.firebase_notification"
//extends from FirebaseMessaging Service
class MyFirebaseMessagingService : FirebaseMessagingService() {
//generate the notification
//attach the notification with the custom layout
//show the notification
//receive the notification having remoteView
override fun onMessageReceived(remoteMessage: RemoteMessage) {
//if it is not null it will call generateNotification
if(remoteMessage.getNotification() != null) {
generateNotification(remoteMessage.notification!!.title!!,remoteMessage.notification!!.body!!)
}
}
//RemoteView Creation and
fun getRemoteView(title: String, message: String): RemoteViews {
val remoteViews = RemoteViews("com.example.notification_firebase", R.layout.notification)
//and set Text and Title
remoteViews.setTextViewText(R.id.title, title)
remoteViews.setTextViewText(R.id.message, message)
remoteViews.setImageViewResource(R.id.app_logo, R.drawable.applogo)
return remoteViews
}
//create a method to generate notification which takes title and message
fun generateNotification(title: String, message: String) {
//create intent when user click on notification, he redirect on the app
val intent = Intent(this, MainActivity::class.java)
//clear all the activities and put this activity on top for this we need pendindIntent
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//create pending activity it call only once when user click on the notification after it will destroy
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
//build the notification
var builder: NotificationCompat.Builder =
NotificationCompat.Builder(applicationContext, channelId)
//set the properties of notification
.setSmallIcon(R.drawable.app_logo)
.setAutoCancel(true)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000))
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
//attach builder to remoteView so we need to build remoteView on top of the class
builder = builder.setContent(getRemoteView(title, message))
//build notification manager
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//check this version is greater than oreo or not
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//create notification channel
val notificationChannel =
NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(notificationChannel)
}
//then notifiy it
notificationManager.notify(0,builder.build())
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/app_logo"
android:layout_width="70dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_height="70dp"
android:src="@drawable/applogo"/>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:layout_toRightOf="@+id/app_logo"
android:hint="Title"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/title"
android:layout_marginTop="10dp"
android:layout_toRightOf="@+id/app_logo"
android:hint="This is a Message"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginLeft="10dp"
/>
</RelativeLayout>
</RelativeLayout>