Showing posts with label Firebase. Show all posts
Showing posts with label Firebase. Show all posts

Sunday, 27 August 2023

Unveiling AES-256 Encryption: Safeguarding Data with Advanced Security.

 In the realm of modern cryptography, ensuring the security of sensitive data is paramount. Advanced Encryption Standard (AES) has emerged as one of the most widely used encryption algorithms, trusted by governments, corporations, and individuals alike. Among its variants, AES-256 stands out as the strongest and most robust encryption option. In this blog, we'll delve into the workings of the AES-256 algorithm, its significance, and how it maintains data confidentiality.

Understanding AES Encryption

AES, also known as Rijndael, was established as a U.S. federal government standard in 2001. It was designed to replace its predecessor, the Data Encryption Standard (DES), which was deemed inadequate against modern threats due to its relatively short key length and algorithmic vulnerabilities.

AES operates as a symmetric encryption algorithm, meaning it employs the same key for both encryption and decryption processes. However, the security lies in the complexity of the algorithm itself, making it practically impossible for unauthorized parties to deduce the original data from the encrypted version, even with knowledge of the algorithm.

AES Key Lengths

AES comes in three standard key lengths: 128 bits, 192 bits, and 256 bits. The numbers correspond to the length of the cryptographic key used in the algorithm. AES-256, the focus of this blog, utilizes a 256-bit key length, providing an immense number of possible key combinations. This large key space contributes significantly to the algorithm's security, as it becomes computationally infeasible to launch brute-force attacks.

AES-256 Encryption Process

Key Expansion: The initial 256-bit encryption key is expanded into a set of round keys. Each round key is used in subsequent rounds of the encryption process.

Initial Round: The data is divided into blocks, typically 128 bits each. In the initial round, each byte of the block is combined with the corresponding byte of the round key through a process called "AddRoundKey."

Main Rounds: The number of main rounds depends on the key length. For AES-256, there are 14 main rounds. Each main round consists of four operations: SubBytes, ShiftRows, MixColumns, and AddRoundKey. These operations introduce confusion and diffusion, making the relationship between the key and the ciphertext highly complex.

  • SubBytes: Non-linear substitution of each byte in the block using a predefined substitution table (S-box).
  • ShiftRows: Byte rows are shifted by varying offsets to introduce diffusion.
  • MixColumns: Columns are mixed through a mathematical transformation, enhancing the algorithm's security.
  • AddRoundKey: The round key is XORed with the block's state, adding a layer of confusion.

Final Round: The final round is similar to the main rounds but lacks the MixColumns operation.

Output: After the final round, the transformed block is the encrypted ciphertext, which can be transmitted or stored securely.

Security and Strengths

AES-256's strength lies in its combination of substitution, permutation, and mixing operations, making it highly resistant to cryptanalysis. The large key size and the multiple rounds of transformation contribute to its robustness against various attacks, including brute force, differential, and linear attacks. The security of AES-256 is also underpinned by its ability to effectively dissipate statistical patterns, ensuring that even small changes in input data result in significant changes in the ciphertext.

Decryption Process

The decryption process is essentially the reverse of encryption, involving the application of inverse operations to retrieve the original plaintext from the ciphertext. The same round keys used in encryption are applied in reverse order.

Conclusion

The AES-256 algorithm represents the pinnacle of data security through its robust encryption process and utilization of a 256-bit key length. Its widespread adoption in critical applications demonstrates its effectiveness against modern cryptographic threats. Understanding the complexities of AES-256 not only underscores the importance of data protection but also highlights the intricate beauty of cryptography in the digital age.

Tuesday, 22 August 2023

Exploring the Power of Dynamic Links in Firebase: Seamless User Experiences.

 In today's digital landscape, user engagement and seamless experiences are paramount for the success of any online platform. Whether you're a mobile app developer, a website owner, or an e-commerce business, the ability to guide users to specific content or features within your app or website can make a significant difference. This is where Firebase Dynamic Links comes into play. In this blog post, we'll delve into the world of Dynamic Links, understand what they are, and explore how they can enhance user experiences across different platforms.

Understanding Dynamic Links

Dynamic Links are a feature of Firebase, a comprehensive app development platform by Google. They provide a powerful solution for seamlessly navigating users to specific content within a mobile app or a website, regardless of whether the app is already installed or not. Dynamic Links essentially act as smart URLs that can intelligently redirect users to the right location based on the context and user's device.

Key Features and Benefits

Cross-Platform Compatibility: Dynamic Links work across different platforms, including iOS, Android, and the web. This cross-platform compatibility ensures a consistent experience for users, regardless of the device they are using.

Deep Linking: Deep linking allows you to direct users to specific content within your app, such as a particular page, screen, or feature. This is crucial for enhancing user engagement and making it easier for users to access relevant content directly.

Personalization: Dynamic Links can be customized to include specific parameters, enabling you to personalize the user experience. For instance, you can create links that provide discounts for specific users or take users to personalized content based on their preferences.

App Installation Handling: If the user doesn't have your app installed, the Dynamic Link can lead them to the appropriate app store for installation. Once the app is installed, the Dynamic Link will still route them to the intended content, providing a seamless transition.

Measurement and Analytics: Firebase provides insights into the performance of your Dynamic Links, helping you track user engagement, conversion rates, and other important metrics. This data can guide your optimization strategies.

Implementing Dynamic Links

Setting up Dynamic Links involves a few key steps:

  • Integrate Firebase: To get started, you need to integrate Firebase into your app or website. This involves adding the necessary SDKs and configuring your project.
  • Create Dynamic Links: Within the Firebase console, you can create Dynamic Links and customize their behavior. You can set the link URL, specify the behavior for when the app is not installed, and add any necessary parameters.
  • Generate Links: Firebase provides APIs that allow you to generate Dynamic Links programmatically. This is useful for scenarios where you want to generate links dynamically based on user actions.
  • Implement Deep Linking: Within your app or website, you need to handle the deep link routing. When a user clicks on a Dynamic Link, your app should recognize the link and direct the user to the appropriate content.

Use Cases

E-Commerce: Dynamic Links can be used to lead users to specific product pages, promotions, or even their shopping carts directly from a marketing email or social media post.

Content Sharing: If you have a content-based app, Dynamic Links can be used to share articles, videos, or specific pieces of content with users, even if they haven't installed your app yet.

Onboarding and Referral Programs: Use Dynamic Links to simplify user onboarding by directing new users to a personalized welcome page. Additionally, referral programs can benefit from personalized links that credit users for successful referrals.

Conclusion

Firebase Dynamic Links offer a seamless and powerful solution for enhancing user engagement and providing personalized experiences across different platforms. By leveraging the capabilities of Dynamic Links, app developers and website owners can guide users to specific content or features, regardless of whether the app is already installed. This feature not only improves user satisfaction but also contributes to higher conversion rates and overall app success. As the digital landscape continues to evolve, tools like Firebase Dynamic Links are becoming essential for creating standout user experiences.

Wednesday, 1 February 2023

Dive into Firebase Tools: Empowering Technical Excellence in App Development.

In the realm of app development, Firebase has emerged as a go-to platform, providing a wide range of powerful tools that simplify the development process and enhance app functionality. In this blog post, we will take a technical deep dive into Firebase's tools and explore how they can be leveraged to build robust and efficient applications.

Refer the below link for complete sample code:-

Download Sample Code

Firebase Authentication:

Firebase Authentication allows developers to implement user authentication seamlessly. Under the hood, it handles the complexities of user management, password storage, and authentication flows. Developers can integrate Firebase Authentication into their apps using SDKs for various platforms, including Android, iOS, and the web. It supports email/password authentication, social authentication providers (such as Google, Facebook, and Twitter), phone number authentication, and custom authentication systems. Firebase Authentication also provides user identity and access management features, including user roles and permissions.

Firebase Realtime Database:

The Firebase Realtime Database is a NoSQL JSON database that enables real-time synchronization of data across connected clients. It offers offline capabilities, allowing users to access and modify data even when the device is offline. The Realtime Database employs a reactive programming model, triggering events whenever data changes. Developers can listen for these events and update the user interface accordingly. The database supports automatic data synchronization and conflict resolution, making it ideal for collaborative applications that require real-time updates, such as chat apps, collaborative editors, and live dashboards.

Cloud Firestore:

Cloud Firestore is a flexible, scalable, and highly available NoSQL document database. It provides seamless data synchronization, offline support, and powerful querying capabilities. Firestore organizes data in collections and documents, allowing developers to build hierarchical data structures. It supports atomic operations, enabling batch writes and complex transactions. Firestore offers robust security rules, allowing developers to define fine-grained access control. With Firestore's scalability and real-time capabilities, it is suitable for applications that require complex data querying, real-time collaboration, and offline data access.

Firebase Cloud Messaging:

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that enables developers to send notifications and messages to devices. FCM supports various message types, including notification messages and data messages. Notification messages display a notification on the device's system tray, while data messages allow developers to handle the message payload themselves. FCM provides high delivery rates, scalable message targeting, and support for topics and device groups. It also offers device registration and token management for efficient message routing.

Firebase Hosting:

Firebase Hosting is a fully-managed hosting service that provides developers with a secure and scalable platform for deploying web applications and static content. It integrates seamlessly with other Firebase services, allowing easy setup and configuration. Firebase Hosting leverages a global CDN to deliver content quickly to users worldwide. It supports custom domains, SSL/TLS encryption, and automatic HTTP/2 push. With Firebase Hosting, developers can easily deploy and update their web applications without worrying about infrastructure management.

Firebase Cloud Functions:

Firebase Cloud Functions is a serverless compute platform that allows developers to write and deploy server-side code in response to events triggered by Firebase services or HTTP requests. Developers can write functions in JavaScript or TypeScript and deploy them using Firebase CLI or through continuous integration (CI) pipelines. Cloud Functions can be used for a wide range of tasks, such as processing data, sending notifications, integrating with third-party APIs, and performing background tasks. It offers autoscaling, pay-per-use pricing, and integrates seamlessly with other Firebase services.

Firebase Performance Monitoring:

Firebase Performance Monitoring helps developers gain insights into their app's performance by collecting data on various performance metrics. It provides detailed reports on app startup time, screen rendering, network requests, and custom traces. Performance Monitoring offers integration with popular mobile development frameworks, including Android, iOS, and React Native. Developers can use Performance Monitoring to identify performance bottlenecks, optimize app performance, and deliver a smooth user experience.

Firebase Test Lab:

Firebase Test Lab is a cloud-based app-testing infrastructure that allows developers to test their Android and iOS apps on a wide range of real devices hosted in Google data centers. It offers automated testing capabilities, including compatibility testing, security testing, and performance testing. Developers can run tests on different device configurations, operating system versions, and network conditions. Firebase Test Lab helps ensure app quality, identify compatibility issues, and optimize app performance across various devices.

Conclusion:

Firebase's comprehensive suite of tools empowers developers to build feature-rich, scalable, and high-performance applications. By leveraging Firebase Authentication, Realtime Database, Cloud Firestore, Cloud Messaging, Hosting, Cloud Functions, Performance Monitoring, and Test Lab, developers can streamline the development process, enhance app functionality, and deliver exceptional user experiences. Whether you are building a small mobile app or a complex web application, Firebase offers the tools you need to succeed. 

Saturday, 14 December 2019

How To Build Real Time Chat Interface Using Firebase In Android.

The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data.

We will apply the same concept for real time chat. Firstly, we will build chat interface with login and registration and than setup Firebase Realtime Database for messaging.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//activity_users.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.androidchatapp.Users"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No users found!"
        android:id="@+id/noUsersText"
        android:visibility="gone"/>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/usersList"/>
</LinearLayout>

//activity_chat.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="utf-8"?>
<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:background="#ffffff"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.androidchatapp.Chat">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_weight="20"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/layout1">

      </LinearLayout>
    </ScrollView>

    <include
        layout="@layout/message_area"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_marginTop="5dp"/>
</LinearLayout>

//message_area.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    android:gravity="bottom"
    android:orientation="horizontal">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColorHint="#CFD8DC"
        android:textColor="#CFD8DC"
        android:hint="Write a message..."
        android:id="@+id/messageArea"
        android:maxHeight="80dp"
        />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="4"
        android:padding="4dp"
        android:src="@android:drawable/ic_menu_send"
        android:id="@+id/sendButton"/>
</LinearLayout>

//Users.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
package com.elitetechnologies.realtimechat;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

public class Users extends AppCompatActivity {
    ListView usersList;
    TextView noUsersText;
    ArrayList<String> al = new ArrayList<>();
    int totalUsers = 0;
    ProgressDialog pd;

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

        usersList = (ListView)findViewById(R.id.usersList);
        noUsersText = (TextView)findViewById(R.id.noUsersText);

        pd = new ProgressDialog(Users.this);
        pd.setMessage("Loading...");
        pd.show();

        String url = "https://real-time-chat-eb94c.firebaseio.com/users.json";

        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
            @Override
            public void onResponse(String s) {
                doOnSuccess(s);
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("" + volleyError);
            }
        });

        RequestQueue rQueue = Volley.newRequestQueue(Users.this);
        rQueue.add(request);

        usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserDetails.chatWith = al.get(position);
                startActivity(new Intent(Users.this, Chat.class));
            }
        });
    }

    public void doOnSuccess(String s){
        try {
            JSONObject obj = new JSONObject(s);

            Iterator i = obj.keys();
            String key = "";

            while(i.hasNext()){
                key = i.next().toString();

                if(!key.equals(UserDetails.username)) {
                    al.add(key);
                }

                totalUsers++;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(totalUsers <=1){
            noUsersText.setVisibility(View.VISIBLE);
            usersList.setVisibility(View.GONE);
        }
        else{
            noUsersText.setVisibility(View.GONE);
            usersList.setVisibility(View.VISIBLE);
            usersList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al));
        }

        pd.dismiss();
    }
}

//Chat.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
package com.elitetechnologies.realtimechat;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;

import java.util.HashMap;
import java.util.Map;

public class Chat extends AppCompatActivity {
    LinearLayout layout;
    ImageView sendButton;
    EditText messageArea;
    ScrollView scrollView;
    Firebase reference1, reference2;

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

        layout = (LinearLayout)findViewById(R.id.layout1);
        sendButton = (ImageView)findViewById(R.id.sendButton);
        messageArea = (EditText)findViewById(R.id.messageArea);
        scrollView = (ScrollView)findViewById(R.id.scrollView);

        Firebase.setAndroidContext(this);
        reference1 = new Firebase("https://real-time-chat-eb94c.firebaseio.com/message/" + UserDetails.username + "_" + UserDetails.chatWith);
        reference2 = new Firebase("https://real-time-chat-eb94c.firebaseio.com/message/" + UserDetails.chatWith + "_" + UserDetails.username);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageText = messageArea.getText().toString();

                if(!messageText.equals("")){
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("message", messageText);
                    map.put("user", UserDetails.username);
                    reference1.push().setValue(map);
                    reference2.push().setValue(map);
                }
            }
        });

        reference1.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Map map = dataSnapshot.getValue(Map.class);
                String message = map.get("message").toString();
                String userName = map.get("user").toString();

                if(userName.equals(UserDetails.username)){
                    addMessageBox("You:-\n" + message, 1);
                }
                else{
                    addMessageBox(UserDetails.chatWith + ":-\n" + message, 2);
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }

    public void addMessageBox(String message, int type){
        TextView textView = new TextView(Chat.this);
        textView.setText(message);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 0, 0, 10);
        textView.setLayoutParams(lp);

        if(type == 1) {
            textView.setBackgroundResource(R.drawable.rounded_corner1);
        }
        else{
            textView.setBackgroundResource(R.drawable.rounded_corner2);
        }

        layout.addView(textView);
        scrollView.fullScroll(View.FOCUS_DOWN);
    }
}

Sunday, 14 April 2019

HB Blog 166: Push Notification Using Firebase Cloud Messaging API.

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.

Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app.

It offers a broad range of messaging options and capabilities.

With FCM, you can send two types of messages to clients:
  • Notification messages, sometimes thought of as "display messages." These are handled by the FCM SDK automatically.
  • Data messages, which are handled by the client app.
To write your Firebase Cloud Messaging Android client app, use the FirebaseMessaging API.


Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//build.gradle
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.harshalbenake.fcm"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.firebase:firebase-messaging:15.0.0'
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
    implementation 'com.google.firebase:firebase-core:15.0.0'
    implementation 'com.android.support:multidex:1.0.1'


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

//AndroidManifest.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.harshalbenake.fcm">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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=".FCM.FCMMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".FCM.FCMInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>

//FCMInstanceIDService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.harshalbenake.fcm.FCM;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class FCMInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * 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 onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // 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(refreshedToken);
    }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
    }
}

//FCMMessagingService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.harshalbenake.fcm.FCM;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FCMMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // 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.
        System.out.println("sendNotification");
        displayNotification("Message Notification Body");
    }

    /**
     * display Notification
     *
     */
    private void displayNotification(String strMessage) {
        try {
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(FCMMessagingService.this, "1000")
                            .setSmallIcon(android.R.drawable.btn_plus)
                            .setContentTitle(strMessage)
                            .setContentText(strMessage)
                            .setAutoCancel(true)
                            .setDefaults(Notification.DEFAULT_SOUND)
                            .setPriority(Notification.PRIORITY_HIGH);
                mBuilder.setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(strMessage));

                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                // allows you to update the displayNotification later on.
                mNotificationManager.notify(1, mBuilder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Thursday, 14 March 2019

HB Blog 165: Google Analytics Using Firebase.

Google Analytics is a web analytics service offered by Google that tracks and reports website traffic. It has became the most widely used web analytics service on the web. It provides an SDK that allows gathering usage data from iOS and Android app, known as Google Analytics for Mobile Apps.
In this tutorial we will see how to use Google Analytics using Firebase Android library.
Google Analytics for Firebase collects usage and behavior data for your app. The SDK logs two primary types of information:
  • Events: What is happening in your app, such as user actions, system events, or errors.
  • User properties: Attributes you define to describe segments of your user base, such as language preference or geographic location.
Analytics automatically logs some events and user properties; you don't need to add any code to enable them.
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//build.gradle
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.harshalbenake.firebaseanalytics"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.firebase:firebase-core:15.0.0'

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

//MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.harshalbenake.firebaseanalytics;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.firebase.analytics.FirebaseAnalytics;

public class MainActivity extends AppCompatActivity {
    private FirebaseAnalytics mFirebaseAnalytics;

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

        // Obtain the FirebaseAnalytics instance.
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        Bundle bundle = new Bundle();
        bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "1000");
        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "HBName");
        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
        bundle.putString(FirebaseAnalytics.Param.VALUE, "3.14");

        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

        mFirebaseAnalytics.setUserProperty("favorite_food", "rice");

    }
}