Langsung ke konten utama

Firebase Cloud Messaging in Android

Firebase Cloud Messaging in Android

Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.

Firebase Cloud Messaging is very easy to integrate into your Application. Just like GCM, FCM is a cross-platform messaging solution that allows you to send messages. FCM is completely free and there are no limitations

Firebase Setup

The Feature and Settings up of Application in Application is Explained in Previous post. After this, follow the tutorial as in below. In This post, I am not explaining about any Layouts. Simply explains the Java code build to FCM Application.

Adding Firebase Messaging to Your Project

  • Now come back to your android project. Go to app folder and paste google-services.json file.
  • Now go to your root level build.gradle file and add the following code
// Add this line
classpath 'com.google.gms:google-services:3.0.0'
  • Inside app level build.gradle file make the following changes.
// Add this line
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.google.firebase:firebase-core:9.0.2'
compile 'com.google.firebase:firebase-messaging:9.0.2'
}
apply plugin: 'com.google.gms.google-services'

Implementing Firebase Cloud Messaging

Create a class named  FireBaseInstanceIDService.java and write the following code.
// Add this line
public class FireBaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = FireBaseInstanceIDService.class.getSimpleName();
public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
public static final String REGISTRATION_TOKEN = "token";

@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed_token: " + refreshedToken);

// Used to get Device token to store in database
Intent intent1 = new Intent(REGISTRATION_SUCCESS);
intent1.putExtra(REGISTRATION_TOKEN, refreshedToken);
sendBroadcast(intent1);
}

}
Create a class named  FireBaseMessagingService.java and write the following code.
// Add this line
private static final String TAG = FireBaseMessagingService.class.getSimpleName();

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.d(TAG, "remoteMessage: " + remoteMessage);
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody());
}

//This method is only generating push notification
//It is same as we did in earlier posts
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, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FireBase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
  • Now we have to define the above services in our AndroidManifest.xml file. Don't forget to add Internet Permission.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidmads.firebasecloudmessaging">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<!-- Defining Services -->
<service android:name=".FireBaseMessagingService" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".FireBaseInstanceIDService" >
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>

</manifest>

  • Thats all. Now run your app (Make sure your device is having google play service or else it won’t work). After running you will see the token in the logcat or in your Main Screen. Copy the token.

Sending Push Notification using Firebase Console :
  • Go to firebase console and select the app you created.
  • From the left menu select notification.
  • Click on new message.
  • Enter message, select single device and paste the token you copied and click on send

For more, Details Please download whole project source from Github.

Download From Github

If you find this post is useful, Please provide star in Github and Having any trouble or doubt while using this project leave your comment.

Komentar

Postingan populer dari blog ini

Android Tutorial: Use LeakCanary to detect memory leaks

Overview The memory leak can be a headache to detect and to resolve, small memory leaks can be hidden and may be seen after a long usage of the application and hunting memory leaks is not a simple task. In this tutorial we will create a leaked application and we will use the LeakCanary library to detect the memory leak. Step 1: add the LeakCanary dependency to the application Modify the app/build.gradle to add the LeakCanary dependency as follows: Step 2: Extend and configure the Application class We need to call LeakCanary.install in onCreate method: Step 3: Create a leaked activity For this we will create a singleton class that saves the context: Then, the main activity (leaked one), will use the singleton and then we'll go to a new activity: Then, in the new activity we'll call System.gc to force the garbage collector in order to accelerate the analysis. Step 4: Retrieve the analysis result A nice notification can be shown: The result can be retrieved from logcat: Source c...

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s...

How to Perform Rest API using Retrofit in Android (Part-1)

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley. This post is Split into Two Parts. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations. Second Part Contains how to perform Retrofit Operations in Android. Architecture of Retrofit Web Service We need 3 Things for Complete Retrofit Architecture. RestAdapter An Interface with all networking methods and parameters. Getter Setter Class to save data coming from server. Project Structure: Create MySQL DataBase and PHP Scripts. Following image shows my database structure. PHP Scripts: I created db_config.php which contains the script to connect DB. <?php /** * Database config variables */ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "retrofit_exampl...