├── AndroidFirebaseNotification ├── app │ ├── .gitignore │ ├── src │ │ ├── main │ │ │ ├── res │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── drawable │ │ │ │ │ ├── image_placeholder.png │ │ │ │ │ └── ic_launcher_background.xml │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ ├── ic_launcher.png │ │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── values │ │ │ │ │ ├── colors.xml │ │ │ │ │ ├── styles.xml │ │ │ │ │ └── strings.xml │ │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ │ ├── ic_launcher.xml │ │ │ │ │ └── ic_launcher_round.xml │ │ │ │ ├── layout │ │ │ │ │ ├── activity_main.xml │ │ │ │ │ └── activity_message_show.xml │ │ │ │ └── drawable-v24 │ │ │ │ │ └── ic_launcher_foreground.xml │ │ │ ├── java │ │ │ │ └── com │ │ │ │ │ └── hellohasan │ │ │ │ │ └── android_firebase_notification │ │ │ │ │ ├── notification │ │ │ │ │ ├── Configuration.kt │ │ │ │ │ ├── MyFirebaseMessagingService.kt │ │ │ │ │ └── NotificationUtils.kt │ │ │ │ │ ├── utils │ │ │ │ │ └── Preferences.kt │ │ │ │ │ └── activity │ │ │ │ │ ├── MainActivity.kt │ │ │ │ │ └── MessageShowActivity.kt │ │ │ └── AndroidManifest.xml │ │ ├── test │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── hellohasan │ │ │ │ └── android_firebase_notification │ │ │ │ └── ExampleUnitTest.kt │ │ └── androidTest │ │ │ └── java │ │ │ └── com │ │ │ └── hellohasan │ │ │ └── android_firebase_notification │ │ │ └── ExampleInstrumentedTest.kt │ ├── proguard-rules.pro │ ├── google-services.json │ └── build.gradle ├── settings.gradle ├── .gitignore ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── build.gradle ├── gradle.properties ├── gradlew.bat └── gradlew ├── data ├── screen1.png ├── screen2.png └── admin_panel.png ├── AndroidPushNotification-PHP-Backend ├── logout.php ├── config.php ├── push.php ├── firebase.php ├── index.php └── dashboard.php └── README.md /AndroidFirebaseNotification/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | rootProject.name='Android Firebase Notification' 3 | -------------------------------------------------------------------------------- /data/screen1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/data/screen1.png -------------------------------------------------------------------------------- /data/screen2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/data/screen2.png -------------------------------------------------------------------------------- /data/admin_panel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/data/admin_panel.png -------------------------------------------------------------------------------- /AndroidPushNotification-PHP-Backend/logout.php: -------------------------------------------------------------------------------- 1 | window.location='index.php'"; 5 | ?> -------------------------------------------------------------------------------- /AndroidPushNotification-PHP-Backend/config.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/drawable/image_placeholder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/drawable/image_placeholder.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/HEAD/AndroidFirebaseNotification/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Oct 16 15:09:16 BDT 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/test/java/com/hellohasan/android_firebase_notification/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/java/com/hellohasan/android_firebase_notification/notification/Configuration.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification.notification 2 | 3 | class Configuration { 4 | 5 | companion object { 6 | // global topic to receive app wide push notifications 7 | val TOPIC_GLOBAL = "global" 8 | 9 | // broadcast receiver intent filters 10 | val REGISTRATION_COMPLETE = "registrationComplete" 11 | val PUSH_NOTIFICATION = "pushNotification" 12 | 13 | // id to handle the notification in the notification tray 14 | const val NOTIFICATION_ID = 100 15 | const val NOTIFICATION_ID_BIG_IMAGE = 101 16 | 17 | val SHARED_PREF = "ah_firebase" 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.3.50' 5 | repositories { 6 | google() 7 | jcenter() 8 | 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.5.1' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | classpath 'com.google.gms:google-services:4.3.2' 14 | // NOTE: Do not place your application dependencies here; they belong 15 | // in the individual module build.gradle files 16 | } 17 | } 18 | 19 | allprojects { 20 | repositories { 21 | google() 22 | jcenter() 23 | 24 | } 25 | } 26 | 27 | task clean(type: Delete) { 28 | delete rootProject.buildDir 29 | } 30 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/androidTest/java/com/hellohasan/android_firebase_notification/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.hellohasan.android_firebase_notification", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/google-services.json: -------------------------------------------------------------------------------- 1 | { 2 | "project_info": { 3 | "project_number": "your project number", 4 | "firebase_url": "Your firebase url", 5 | "project_id": "your project ID", 6 | "storage_bucket": "your_bucket" 7 | }, 8 | "client": [ 9 | { 10 | "client_info": { 11 | "mobilesdk_app_id": "YOUR_APP_ID", 12 | "android_client_info": { 13 | "package_name": "com.hellohasan.android_firebase_notification" 14 | } 15 | }, 16 | "oauth_client": [ 17 | { 18 | "client_id": "YOUR_CLIENT_ID", 19 | "client_type": 3 20 | } 21 | ], 22 | "api_key": [ 23 | { 24 | "current_key": "YOUR_OWN_CURRENT_KEY" 25 | } 26 | ], 27 | "services": { 28 | "appinvite_service": { 29 | "other_platform_oauth_client": [ 30 | { 31 | "client_id": "YOUR_CLIENT_ID", 32 | "client_type": 3 33 | } 34 | ] 35 | } 36 | } 37 | } 38 | ], 39 | "configuration_version": "1" 40 | } -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 21 | 22 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/java/com/hellohasan/android_firebase_notification/utils/Preferences.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification.utils 2 | 3 | import android.content.Context 4 | import android.content.SharedPreferences 5 | 6 | 7 | class Preferences private constructor() { 8 | 9 | 10 | var versionCode: Long 11 | get() = sharedPreferences!!.getLong(VERSION_CODE, -1) 12 | set(versionCode) { 13 | editor?.putLong(VERSION_CODE, versionCode) 14 | editor?.apply() 15 | editor?.commit() 16 | } 17 | 18 | companion object { 19 | 20 | val VERSION_CODE = "version_code" 21 | 22 | private var sharedPreferences: SharedPreferences? = null 23 | private var editor: SharedPreferences.Editor? = null 24 | 25 | private val preferences = Preferences() 26 | 27 | 28 | fun getInstance(context: Context): Preferences { 29 | sharedPreferences = 30 | context.getSharedPreferences("sharedPreferences_data", Context.MODE_PRIVATE) 31 | editor = sharedPreferences?.edit() 32 | return preferences 33 | } 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /AndroidFirebaseNotification/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Firebase Push Notification with PHP Backend 2 | 3 | This is a practice project of Android Firebase push notification with PHP backend. 4 | I followed [Ravi Tamada's tutorial and source codes](http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/) to develop this project. 5 | 6 | **Web admin panel Screenshot**
7 | 8 | 9 | **Android App Screenshot**
10 | 11 | 12 | ## Instructions 13 | - You have to modify ***config.php*** file with your own Firebase Server Key. This key you'll get from Firebase official website. 14 | - You have to add your own ***google-services.json*** file from your Firebase console. Otherwise the project don't run properly. 15 | 16 | ### Quick Links: 17 | - [Android Java Code](https://github.com/hasancse91/Android-Firebase-Notification-With-PHP-Backend/tree/master/AndroidFirebaseNotification) 18 | - [PHP Source Code](https://github.com/hasancse91/Android-Firebase-Notification/tree/master/AndroidPushNotification-PHP-Backend) 19 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/java/com/hellohasan/android_firebase_notification/activity/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification.activity 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | import android.util.Log 6 | import com.google.firebase.iid.FirebaseInstanceId 7 | import com.google.firebase.messaging.FirebaseMessaging 8 | import com.hellohasan.android_firebase_notification.R 9 | import com.hellohasan.android_firebase_notification.notification.Configuration.Companion.TOPIC_GLOBAL 10 | import kotlinx.android.synthetic.main.activity_main.* 11 | 12 | class MainActivity : AppCompatActivity() { 13 | 14 | private val TAG = "MainActivity" 15 | 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | setContentView(R.layout.activity_main) 19 | 20 | FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener { 21 | firebaseId.append(it.token) 22 | } 23 | 24 | FirebaseMessaging.getInstance().subscribeToTopic(TOPIC_GLOBAL) 25 | .addOnCompleteListener { task -> 26 | 27 | if (task.isSuccessful) 28 | Log.d(TAG, "Global topic subscription successful") 29 | else 30 | Log.e(TAG, "Global topic subscription failed. Error: " + task.exception?.localizedMessage) 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /AndroidPushNotification-PHP-Backend/push.php: -------------------------------------------------------------------------------- 1 | title = $title; 23 | } 24 | 25 | public function setMessage($message) { 26 | $this->message = $message; 27 | } 28 | 29 | public function setImage($imageUrl) { 30 | $this->image = $imageUrl; 31 | } 32 | 33 | public function setPayload($data) { 34 | $this->data = $data; 35 | } 36 | 37 | public function setIsBackground($is_background) { 38 | $this->is_background = $is_background; 39 | } 40 | 41 | public function getPush() { 42 | $res = array(); 43 | $res['data']['title'] = $this->title; 44 | $res['data']['is_background'] = $this->is_background; 45 | $res['data']['message'] = $this->message; 46 | $res['data']['image'] = $this->image; 47 | $res['data']['payload'] = $this->data; 48 | $res['data']['timestamp'] = date('Y-m-d G:i:s'); 49 | return $res; 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | apply plugin: 'com.google.gms.google-services' 5 | 6 | android { 7 | compileSdkVersion 28 8 | defaultConfig { 9 | applicationId "com.hellohasan.android_firebase_notification" 10 | minSdkVersion 21 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | implementation fileTree(dir: 'libs', include: ['*.jar']) 26 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 27 | implementation 'androidx.appcompat:appcompat:1.1.0' 28 | implementation 'androidx.core:core-ktx:1.1.0' 29 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 30 | testImplementation 'junit:junit:4.12' 31 | androidTestImplementation 'androidx.test.ext:junit:1.1.1' 32 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 33 | 34 | // firebase notification 35 | implementation 'com.google.firebase:firebase-messaging:20.0.0' 36 | 37 | // image loading and caching 38 | implementation 'com.squareup.picasso:picasso:2.71828' 39 | } 40 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Android Firebase Notification 3 | notification_id_101 4 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\nSed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? 5 | 6 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/java/com/hellohasan/android_firebase_notification/activity/MessageShowActivity.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification.activity 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | import android.view.MenuItem 6 | import androidx.core.app.NavUtils 7 | 8 | import com.hellohasan.android_firebase_notification.R 9 | import com.squareup.picasso.Picasso 10 | import kotlinx.android.synthetic.main.activity_message_show.* 11 | 12 | 13 | class MessageShowActivity : AppCompatActivity() { 14 | 15 | override fun onCreate(savedInstanceState: Bundle?) { 16 | super.onCreate(savedInstanceState) 17 | setContentView(R.layout.activity_message_show) 18 | supportActionBar?.setDisplayHomeAsUpEnabled(true) 19 | 20 | //receive data from MyFirebaseMessagingService class 21 | val title = intent.getStringExtra("title") 22 | val timeStampString = intent.getStringExtra("timestamp") 23 | val articleString = intent.getStringExtra("article_data") 24 | val imageUrl = intent.getStringExtra("image") 25 | 26 | //Set data on UI 27 | Picasso.get() 28 | .load(imageUrl) 29 | .placeholder(R.drawable.image_placeholder) 30 | .error(R.drawable.image_placeholder) 31 | .into(featureGraphics) 32 | 33 | header.text = title 34 | timeStamp.text = timeStampString 35 | article.text = articleString 36 | } 37 | 38 | override fun onOptionsItemSelected(item: MenuItem?): Boolean { 39 | 40 | if (item?.itemId == android.R.id.home) 41 | onBackPressed() 42 | 43 | return super.onOptionsItemSelected(item) 44 | } 45 | 46 | override fun onBackPressed() { 47 | super.onBackPressed() 48 | 49 | val intent = NavUtils.getParentActivityIntent(this) 50 | startActivity(intent) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /AndroidPushNotification-PHP-Backend/firebase.php: -------------------------------------------------------------------------------- 1 | $to, 10 | 'data' => $message, 11 | ); 12 | return $this->sendPushNotification($fields); 13 | } 14 | 15 | // Sending message to a topic by topic name 16 | public function sendToTopic($to, $message) { 17 | $fields = array( 18 | 'to' => '/topics/' . $to, 19 | 'data' => $message, 20 | ); 21 | return $this->sendPushNotification($fields); 22 | } 23 | 24 | // sending push message to multiple users by firebase registration ids 25 | public function sendMultiple($registration_ids, $message) { 26 | $fields = array( 27 | 'to' => $registration_ids, 28 | 'data' => $message, 29 | ); 30 | 31 | return $this->sendPushNotification($fields); 32 | } 33 | 34 | // function makes curl request to firebase servers 35 | private function sendPushNotification($fields) { 36 | 37 | require_once __DIR__ . '/config.php'; 38 | 39 | // Set POST variables 40 | $url = 'https://fcm.googleapis.com/fcm/send'; 41 | 42 | $headers = array( 43 | 'Authorization: key=' . FIREBASE_API_KEY, 44 | 'Content-Type: application/json' 45 | ); 46 | // Open connection 47 | $ch = curl_init(); 48 | 49 | // Set the url, number of POST vars, POST data 50 | curl_setopt($ch, CURLOPT_URL, $url); 51 | 52 | curl_setopt($ch, CURLOPT_POST, true); 53 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 54 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 55 | 56 | // Disabling SSL Certificate support temporarly 57 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 58 | 59 | curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); 60 | 61 | // Execute post 62 | $result = curl_exec($ch); 63 | if ($result === FALSE) { 64 | die('Curl failed: ' . curl_error($ch)); 65 | } 66 | 67 | // Close connection 68 | curl_close($ch); 69 | 70 | return $result; 71 | } 72 | } 73 | ?> -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/layout/activity_message_show.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 12 | 13 | 21 | 22 | 32 | 33 | 42 | 43 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /AndroidPushNotification-PHP-Backend/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Firebase Push Notification System on Android 5 | 6 | 7 | 8 | 9 | 10 | 52 | 53 | 54 | 55 | window.location='dashboard.php'"; 60 | } 61 | 62 | 63 | ?> 64 | 65 | 66 |
67 |
68 |
Firebase
69 |
70 | 71 | 72 |
73 |
74 |
75 | 76 |
77 | 78 | 79 |
80 |
81 |
82 | 83 | 84 |
85 | 86 | 87 |
88 |
89 | Firebase Push Notification System on Android 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 |

98 | 99 | 100 | 101 |
102 |
103 |
104 | 105 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/java/com/hellohasan/android_firebase_notification/notification/MyFirebaseMessagingService.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification.notification 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import com.google.firebase.messaging.FirebaseMessagingService 6 | import com.google.firebase.messaging.RemoteMessage 7 | import org.json.JSONObject 8 | import org.json.JSONException 9 | import android.text.TextUtils 10 | import com.hellohasan.android_firebase_notification.activity.MessageShowActivity 11 | import android.content.Intent 12 | 13 | class MyFirebaseMessagingService : FirebaseMessagingService() { 14 | 15 | val TAG = "MessagingService" 16 | private var notificationUtils: NotificationUtils? = null 17 | 18 | override fun onNewToken(token: String) { 19 | super.onNewToken(token) 20 | 21 | Log.e("FCM Token", token) 22 | } 23 | 24 | override fun onMessageReceived(remoteMessage: RemoteMessage) { 25 | super.onMessageReceived(remoteMessage) 26 | 27 | Log.e(TAG, "From: " + remoteMessage.from) 28 | 29 | // Check if message contains a data payload. 30 | if (remoteMessage.data.isNotEmpty()) { 31 | Log.e(TAG, "Data Payload: " + remoteMessage.data.toString()) 32 | 33 | try { 34 | val json = JSONObject(remoteMessage.data.toString()) 35 | handleDataMessage(json) 36 | } catch (e: Exception) { 37 | Log.e(TAG, "Exception: " + e.message) 38 | } 39 | 40 | } 41 | } 42 | 43 | private fun handleDataMessage(json: JSONObject) { 44 | Log.e(TAG, "push json: $json") 45 | 46 | try { 47 | val data = json.getJSONObject("data") 48 | 49 | val title = data.getString("title") 50 | val message = data.getString("message") 51 | val imageUrl = data.getString("image") 52 | val timestamp = data.getString("timestamp") 53 | val payload = data.getJSONObject("payload") 54 | 55 | val articleData = payload.getString("article_data") 56 | 57 | //Send notification data to MessageShowActivity class for showing 58 | val resultIntent = Intent(applicationContext, MessageShowActivity::class.java) 59 | resultIntent.putExtra("title", title) 60 | resultIntent.putExtra("timestamp", timestamp) 61 | resultIntent.putExtra("article_data", articleData) 62 | resultIntent.putExtra("image", imageUrl) 63 | 64 | // check for image attachment 65 | if (TextUtils.isEmpty(imageUrl)) { 66 | showNotificationMessage(applicationContext, title, message, timestamp, resultIntent) 67 | } else { 68 | // image is present, show notification with image 69 | showNotificationMessageWithBigImage( 70 | applicationContext, 71 | title, 72 | message, 73 | timestamp, 74 | resultIntent, 75 | imageUrl 76 | ) 77 | } 78 | 79 | } catch (e: JSONException) { 80 | Log.e(TAG, "Json Exception: " + e.message) 81 | } catch (e: Exception) { 82 | Log.e(TAG, "Exception: " + e.message) 83 | } 84 | 85 | } 86 | 87 | /** 88 | * Showing notification with text only 89 | */ 90 | private fun showNotificationMessage( 91 | context: Context, 92 | title: String, 93 | message: String, 94 | timeStamp: String, 95 | intent: Intent 96 | ) { 97 | notificationUtils = NotificationUtils(context) 98 | intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK 99 | notificationUtils?.showNotificationMessage(title, message, timeStamp, intent) 100 | } 101 | 102 | /** 103 | * Showing notification with text and image 104 | */ 105 | private fun showNotificationMessageWithBigImage( 106 | context: Context, 107 | title: String, 108 | message: String, 109 | timeStamp: String, 110 | intent: Intent, 111 | imageUrl: String 112 | ) { 113 | notificationUtils = NotificationUtils(context) 114 | intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK 115 | notificationUtils?.showNotificationMessage(title, message, timeStamp, intent, imageUrl) 116 | } 117 | } -------------------------------------------------------------------------------- /AndroidFirebaseNotification/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /AndroidPushNotification-PHP-Backend/dashboard.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Firebase Push Notification System on Android 6 | 7 | 8 | 9 | 10 | 11 | 53 | 54 | 55 | setTitle($title); 92 | $push->setMessage($message); 93 | $push->setImage($image_url); 94 | $push->setIsBackground(FALSE); 95 | $push->setPayload($payload); 96 | 97 | 98 | $json = ''; 99 | $response = ''; 100 | 101 | if ($push_type == 'topic') { 102 | $json = $push->getPush(); 103 | $response = $firebase->sendToTopic('global', $json); 104 | } else if ($push_type == 'individual') { 105 | $json = $push->getPush(); 106 | //$regId = isset($_GET['regId']) ? $_GET['regId'] : ''; 107 | $regId = "PUT YOUR DEVICE ID HERE"; 108 | $response = $firebase->send($regId, $json); 109 | } 110 | ?> 111 |
112 |
113 |
Firebase
114 |
115 | 116 | 117 |
118 |
119 |
120 | 121 |
122 | 123 | 124 |
125 |
126 |
127 | 128 | 129 |
130 | 131 | 132 |
133 |
134 | Firebase Push Notification System on Android 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 |
151 |
152 | 153 | Reset - Logout 154 |

155 |
156 | 157 | 158 | 159 | Login Page"; 163 | } 164 | ?> 165 | 166 | -------------------------------------------------------------------------------- /AndroidFirebaseNotification/app/src/main/java/com/hellohasan/android_firebase_notification/notification/NotificationUtils.kt: -------------------------------------------------------------------------------- 1 | package com.hellohasan.android_firebase_notification.notification 2 | 3 | import android.app.* 4 | import android.content.ComponentName 5 | import android.content.ContentResolver 6 | import android.content.Context 7 | import android.content.Intent 8 | import android.graphics.Bitmap 9 | import android.graphics.BitmapFactory 10 | import android.media.Ringtone 11 | import android.media.RingtoneManager 12 | import android.net.Uri 13 | import android.os.Build 14 | import android.text.Html 15 | import android.text.TextUtils 16 | import android.util.Patterns 17 | 18 | 19 | import androidx.core.app.NotificationCompat 20 | 21 | import com.hellohasan.android_firebase_notification.R 22 | 23 | import java.io.IOException 24 | import java.io.InputStream 25 | import java.net.HttpURLConnection 26 | import java.net.URL 27 | import java.text.ParseException 28 | import java.text.SimpleDateFormat 29 | import java.util.Date 30 | 31 | import com.hellohasan.android_firebase_notification.notification.Configuration.Companion.NOTIFICATION_ID 32 | 33 | 34 | class NotificationUtils(private val mContext: Context) { 35 | 36 | private val channelId = mContext.getString(R.string.default_notification_channel_id) 37 | 38 | @JvmOverloads 39 | fun showNotificationMessage( 40 | title: String, 41 | message: String, 42 | timeStamp: String, 43 | intent: Intent, 44 | imageUrl: String? = null) { 45 | 46 | // Check for empty push message 47 | if (TextUtils.isEmpty(message)) 48 | return 49 | 50 | 51 | // notification icon 52 | val icon = R.mipmap.ic_launcher 53 | 54 | intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP 55 | val resultPendingIntent = PendingIntent.getActivity( 56 | mContext, 57 | 0, 58 | intent, 59 | PendingIntent.FLAG_CANCEL_CURRENT 60 | ) 61 | 62 | val mBuilder = NotificationCompat.Builder( 63 | mContext, 64 | channelId 65 | ) 66 | 67 | val alarmSound = Uri.parse( 68 | ContentResolver.SCHEME_ANDROID_RESOURCE 69 | + "://" + mContext.packageName + "/raw/notification" 70 | ) 71 | 72 | if (!TextUtils.isEmpty(imageUrl)) { 73 | 74 | if (imageUrl != null && imageUrl.length > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) { 75 | 76 | val bitmap = getBitmapFromURL(imageUrl) 77 | 78 | if (bitmap != null) { 79 | showBigNotification( 80 | bitmap, 81 | mBuilder, 82 | icon, 83 | title, 84 | message, 85 | timeStamp, 86 | resultPendingIntent, 87 | alarmSound 88 | ) 89 | } else { 90 | showSmallNotification( 91 | mBuilder, 92 | icon, 93 | title, 94 | message, 95 | timeStamp, 96 | resultPendingIntent, 97 | alarmSound 98 | ) 99 | } 100 | } 101 | } else { 102 | showSmallNotification( 103 | mBuilder, 104 | icon, 105 | title, 106 | message, 107 | timeStamp, 108 | resultPendingIntent, 109 | alarmSound 110 | ) 111 | playNotificationSound() 112 | } 113 | } 114 | 115 | 116 | private fun showSmallNotification( 117 | mBuilder: NotificationCompat.Builder, 118 | icon: Int, 119 | title: String, 120 | message: String, 121 | timeStamp: String, 122 | resultPendingIntent: PendingIntent, 123 | alarmSound: Uri 124 | ) { 125 | 126 | val inboxStyle = NotificationCompat.InboxStyle() 127 | 128 | inboxStyle.addLine(message) 129 | 130 | val notification: Notification 131 | notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0) 132 | .setAutoCancel(true) 133 | .setContentTitle(title) 134 | .setContentIntent(resultPendingIntent) 135 | .setSound(alarmSound) 136 | .setStyle(inboxStyle) 137 | .setWhen(getTimeMilliSec(timeStamp)) 138 | .setSmallIcon(R.mipmap.ic_launcher) 139 | .setLargeIcon(BitmapFactory.decodeResource(mContext.resources, icon)) 140 | .setContentText(message) 141 | .build() 142 | 143 | val notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 144 | 145 | // Since android Oreo notification channel is needed. 146 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 147 | val channel = NotificationChannel(channelId, 148 | "Firebase Notification channel for sample app", 149 | NotificationManager.IMPORTANCE_DEFAULT) 150 | notificationManager.createNotificationChannel(channel) 151 | } 152 | 153 | notificationManager.notify(Configuration.NOTIFICATION_ID, notification) 154 | } 155 | 156 | private fun showBigNotification( 157 | bitmap: Bitmap, 158 | mBuilder: NotificationCompat.Builder, 159 | icon: Int, 160 | title: String, 161 | message: String, 162 | timeStamp: String, 163 | resultPendingIntent: PendingIntent, 164 | alarmSound: Uri 165 | ) { 166 | val bigPictureStyle = NotificationCompat.BigPictureStyle() 167 | bigPictureStyle.setBigContentTitle(title) 168 | bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()) 169 | bigPictureStyle.bigPicture(bitmap) 170 | val notification: Notification 171 | notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0) 172 | .setAutoCancel(true) 173 | .setContentTitle(title) 174 | .setContentIntent(resultPendingIntent) 175 | .setSound(alarmSound) 176 | .setStyle(bigPictureStyle) 177 | .setWhen(getTimeMilliSec(timeStamp)) 178 | .setSmallIcon(R.mipmap.ic_launcher) 179 | .setLargeIcon(BitmapFactory.decodeResource(mContext.resources, icon)) 180 | .setContentText(message) 181 | .build() 182 | 183 | val notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 184 | 185 | // Since android Oreo notification channel is needed. 186 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 187 | val channel = NotificationChannel(channelId, "Firebase Notification channel for sample app", NotificationManager.IMPORTANCE_DEFAULT) 188 | notificationManager.createNotificationChannel(channel) 189 | } 190 | 191 | notificationManager.notify(Configuration.NOTIFICATION_ID_BIG_IMAGE, notification) 192 | } 193 | 194 | /** 195 | * Downloading push notification image before displaying it in 196 | * the notification tray 197 | */ 198 | fun getBitmapFromURL(strURL: String): Bitmap? { 199 | try { 200 | val url = URL(strURL) 201 | val connection = url.openConnection() as HttpURLConnection 202 | connection.doInput = true 203 | connection.connect() 204 | val input = connection.inputStream 205 | return BitmapFactory.decodeStream(input) 206 | } catch (e: IOException) { 207 | e.printStackTrace() 208 | return null 209 | } 210 | 211 | } 212 | 213 | // Playing notification sound 214 | fun playNotificationSound() { 215 | try { 216 | val alarmSound = Uri.parse( 217 | ContentResolver.SCHEME_ANDROID_RESOURCE 218 | + "://" + mContext.packageName + "/raw/notification" 219 | ) 220 | val r = RingtoneManager.getRingtone(mContext, alarmSound) 221 | r.play() 222 | } catch (e: Exception) { 223 | e.printStackTrace() 224 | } 225 | 226 | } 227 | 228 | companion object { 229 | 230 | fun getTimeMilliSec(timeStamp: String): Long { 231 | val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 232 | try { 233 | val date = format.parse(timeStamp) 234 | return date.time 235 | } catch (e: ParseException) { 236 | e.printStackTrace() 237 | } 238 | 239 | return 0 240 | } 241 | } 242 | } 243 | --------------------------------------------------------------------------------