Friday, December 16, 2016

Firebase Cloud Messaging in Android

Firebase Cloud Messeging.


Firebase Cloud Messaging is a powerful API that lets you deliver messages reliably and independent of the platform you are developing on. Using FCM, developers can notify the users that new data is available for sync and send notification messages. These are very useful for testing, sending marketing and engagement messages. It comes in with built-in targeting and analytics.

Below are step which you need to follow in the implementation.



1>First of all we have to open https://console.firebase.google.com/ and create project
2>then goto the setting and project setting option in ://console.firebase.google.com. and at bottom select android option
  (Add firebase to your android app)
3> Then add package name and SHA1 key then one "google-services.json" file will be automatically download.
4> We should to copy "google-services.json" file into our project like "typically app/" and project should be opne in
   "Project" in android studio.
5>Then we have to add google play services into our project.
6> Select project in android studio in "Project" and add below code in projects's build.gradle (not app's build.gradle).


buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'

        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong

        // in the individual module build.gradle files

    }
}

7> After that we have to add below code into our dependency in build.gradle (app's build.gradle)

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'    })
    compile 'com.android.support:appcompat-v7:25.0.1'

    testCompile 'junit:junit:4.12'

    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.google.firebase:firebase-core:10.0.1'
}

apply plugin: 'com.google.gms.google-services'

8> There after we have to add some internet permission and manifest and below is my Manifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    
package="example.com.firebasedemo">

    <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>


        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>


        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/myicon" 
         />
        <!-- 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" />


    </application>

</manifest>

Below is my activity_main.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ImageView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="16dp"
        android:src="@drawable/firebase_lockup_400" />


    <Button
        android:id="@+id/btnSubcribeTopic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:text="subscribe_to_news" />


    <TextView
        android:id="@+id/tvMessege"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        />
</LinearLayout>

And here is my MainActivity Code.

public class MainActivity extends AppCompatActivity {

    private Button btnSubcribeTopic;
    TextView tvMessege;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getId();
        getNotification();


        // to get token        String token = FirebaseInstanceId.getInstance().getToken();
        Log.e("Token is ","=====>"+ token);
        Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();

        btnSubcribeTopic.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {

                FirebaseMessaging.getInstance().subscribeToTopic("Alert");
                Log.e("You subsribe Alert topic", " >>>>>>>");
                Toast.makeText(MainActivity.this, "Alert Topic subcribe", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getNotification() {
        try {
            if (getIntent().getExtras() != null) {
                for (String key : getIntent().getExtras().keySet()) {

                    String value = getIntent().getExtras().getString(key);

                    tvMessege.setText(value);
                    Log.e("MainActivity ", "Key: " + key + " and MainActivity  Value: " + value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getId() {
        try {
            btnSubcribeTopic = (Button) findViewById(R.id.btnSubcribeTopic);
            tvMessege=(TextView)findViewById(R.id.tvMessege);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Then we have to initialized two class so first is given below.

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Token for server.        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {

        Log.e("Token is ", "====>" + token);

    }
}

and another class is also given below.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    public static String strNotification;

    @Override    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.e("Notification messege remoteMessage is ","====>"+remoteMessage);

        if (remoteMessage.getData().size() > 0) {
            Log.e("remoteMessage.getData() is ","====>"+remoteMessage.getData());
        }

        if (remoteMessage.getNotification() != null) {
            Log.e("remoteMessage.getNotification().getBody() is ","====>"+remoteMessage.getNotification().getBody());
            strNotification = remoteMessage.getNotification().getBody();
        }
        sendNotification(strNotification);
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);

        Log.e("sendNotification  ","messageBody????  "+messageBody);

        intent.putExtra("key", messageBody);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(getNotificationIcon())
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

    private int getNotificationIcon() {
        boolean whiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return whiteIcon ? R.drawable.myicon                : R.drawable.ic_launcher;

    }

    // below method is used to show custom icon when application is in background.

    @Override    public void zzm(Intent intent) {
        Intent launchIntent = new Intent(this, MainActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R    equest code */, launchIntent,
                PendingIntent.FLAG_ONE_SHOT);
//        bitmap rawbitmap = bitmapfactory.decoderesource(getresources(),//                R.mipmap.ic_launcher);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.myicon)
//                .setLargeIcon(rawBitmap)

                .setContentTitle(intent.getStringExtra("gcm.notification.title"))
                .setContentText(intent.getStringExtra("gcm.notification.body"))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}




No comments:

Post a Comment