Friday, 8 October 2021

 

SEND YOUR FIRST ANDROID NOTIFICATION USING FCM(Firebase Cloud Messaging)

Abstract: Here I will be discussing about how we can send push notification messages to all users (of an Android app) using Firebase Cloud Messaging (FCM)

1. Create an android project in Android Studio

2. Sign in to firebase with google credentials

3. Now go to the firebase console

(i). Here, create your own firebase project

Follow the subsequent steps. Then add your android app to the firebase clicking the symbol (for android).


(ii). link and register your android app to the project



4. In this process download the google-services.json config file. Put the file in you application’s root directory(just inside your android project’s app folder)



5. Add the firebase android SDK in the project level and app level build.gradle file:

build.gradle(project leve):

Add the following line into repositories, dependencies and allprojects section.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {

        google()

    }

    dependencies {

        classpath 'com.google.gms:google-services:4.3.8'

    }

}

allprojects {

    repositories {

        google()

    }

}

 

6. Now modify the build.gradle file(app level):

Add the following lines

apply plugin: 'com.android.application'

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

dependencies {

    implementation platform('com.google.firebase:firebase-bom:26.6.0')

    implementation 'com.google.firebase:firebase-analytics'

    implementation 'com.google.firebase:firebase-messaging:17.3.4'

}

 

Remember to choose right firebase-bom library 'com.google.firebase:firebase-bom:26.6.0', otherwise build process may fail.

The above bom library will work well with Android sdk 21

7. Now sync the build.gradle file in Android Studio.

8. Make a subclass of FirebaseMessagingService

    -> here override the method onMessageReceived(RemoteMessage remoteMessage)

    -> get the title and body of the notification message from this RemoteMessage object. With remoteMessage.getTitle() get the title, with remoteMessage.getBody() get the notification message.

Below is the code:

package your.package.name;

 

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

 

import androidx.core.app.NotificationCompat;

 

import com.google.firebase.messaging.FirebaseMessagingService;

import com.google.firebase.messaging.RemoteMessage;

 

public class FirebaseMessageReceiver extends FirebaseMessagingService {

    @Override

    public void onMessageReceived(RemoteMessage remoteMessage){

        if(remoteMessage.getNotification() != null){

            String title = remoteMessage.getNotification().getTitle();

            String body = remoteMessage.getNotification().getBody();

            addNotification(body);

        }

    }

 

    @Override

    public void onNewToken(String token){

    }

 

    private void addNotification(String msg){

        //String channel_i = "AmarSchool Notification";

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)

                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)

                .setContentTitle("Test Notification")

                .setContentText(msg)

                .setAutoCancel(true)

                .setPriority(NotificationCompat.PRIORITY_DEFAULT)

                .setChannelId(AdmActivity.CHANNEL_ID);

        Intent notificationIntent = new Intent(this, MyActivity.class);

        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        notificationIntent.putExtra("message",msg);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(contentIntent);

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

        manager.notify(0, builder.build());

    }

}

 

9. Implement the Notification utilities in this subclass.

10. Keep your MainActivity unchanged.

11. In the app manifest add the following code inside the application tag:

<application

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name”

        android:theme="@style/AppTheme">

….. ……. ….. …..     …….

<service android:name=".FirebaseMessageReceiver">

            <intent-filter>

                <action android:name="com.google.firebase.MESSAGING_EVENT" />

            </intent-filter>

        </service>

</application>

12. Now build the project and install it in your device.

13. Now again go to Firebase console. open your project. Go to cloud messaging.

-> [We will go to project settings and collect the service accounts credentials when we will use our own server to put logic to the message sent to our clients(users of the said android app)]



14. Click on ‘Send your first message’.

(i)In the window following set the title and notification text


 

(ii) Now set the target. Choose your app(package name) as user segment

(iii) Click review, then publish

Your message will appear to your handset.


Sunday, 19 September 2021

 

Putting Maths, Physics and Chemistry symbols in web pages served by Node.js
There are many ‘tex softwares’ to perform letting mathematical and other symbols in web pages but I recommend using Mathjax for this purpose. Mathjax is an open source javascript based software which can easily be adopted in Nodejs.
We can directly make link from cdn with <script src=’……’></script> code in our web page but I always prefer to make a separate copy of mathjax in our server.
To adopt mathjax in our nodejs server we have to first install mathjax with the npm(node package manager). We use mathjax3 as it has many advantages over mathjax v2.
Rendering MathJax in Nodejs system, is not a simple client side task. We have to follow few steps in our web app(server).
We need to access npm first. After getting npm we could use it to install mathjax into node system.
So at the server side or at the local pc which runs localhost by Node.js,
 npm install mathjax@3
Note: Otherwise, we have to update the package.json file and add the following line inside dependencies key section like this:
Package.json
{
  "name": "Render Math",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "express": "^4.17.1",
    ……………………………
    "mathjax": "^3.1.2",
    …………………………..
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
Then we have to run npm.
This will install mathjax in node_modules folder in our base project.
Now we got mathjax installed in our system.
Now follow the following steps to render mathjax to our web pages from our nodejs server.
1.                 Configure mathjax in script tag within header section of the html page.
<html>
            <head>
            <meta name='viewport' content="width=device-width, initial-scale=1.0" charset="utf-8">
            <script>
                        window.MathJax = {
                                    tex: {
                                                inlineMath: [['$', '$'], ['\\(', '\\)']]
                                    },
                                    svg: {
                                                fontCache: 'global'
                                    }
                        };
            </script>
            </head>
</html>
2.     . Now load the mathjax with the code: <script type=”text/javascript” scr=“path/tex-chtml.js id=”MathJax-script” async></script>. This is also inside <head></head> section in the html file.
Here ‘path’ is the path of the tex-chtml.js file which should be served by the Nodejs server.
NOTE: When we installed the mathjax through npm, the working components of the mathjax are stored inside the mathjax/es5 directory. So, if we put all the components of mathjax/es5 directory into a base directory folder and name it as mathjax, the text-chtml.js file will be accessible from “/mathjax/tex-chtml.js” location. So, in this case the ‘path’ inside the second script tag should be replaced as “/mathjax”.
Thus, now the src path should be “/mathjax/tex-chtml.js”
3.     . Up to this, the code required for rendering maths and other related symbols in our web page is like this:
<html>
            <head>
            <meta name='viewport' content="width=device-width, initial-scale=1.0" charset="utf-8">
            <script>
                        window.MathJax = {
                                    tex: {
                                                inlineMath: [['$', '$'], ['\\(', '\\)']]
                                    },
                                    svg: {
                                                fontCache: 'global'
                                    }
                        };
            </script>
            <script type=”text/javascript” scr=“/mathjax/tex-chtml.js id=”MathJax-script” async></script>
            </head>
</html>
4.    .  The above code is required to render mathjax from the own copy of mathjax from the server. It is now the task of the server/web app to serve the mathjax files to the webpages. So, we require the following code in the Nodejs web app:
 
app.get('/mathjax*', (req, resp)=>{
            var path = req.url;
            if(fs.existsSync(__dirname+path)){
                        fs.readFile(__dirname + path, function(err, data){
                                    if(err){
                                                resp.writeHead(404);
                                                resp.write(err);
                                                resp.end();
                                    }else{
                                                //logger.debug('caught..echo');
                                    resp.writeHead(200, {
                                                'Content-Type': 'text/javascript'
                                    });
                                    resp.write(data);
                                    resp.end();
                                    }
                        });
            }else resp.end('Not found');
});
NOTE: It is worthy to mention that all the concerned nodejs components are kept inside the /mathjax directory inside base directory. Also, we used a wildcard character (*) after ‘/mathjax’. So, we could access the tex-chtml.js and any other component file from this url path.
5.     Now restart Nodejs and put some mathematical expression like $ x^3 + y^3 $ inside anywhere in the web content. This will appear as

. It is important that every expression which contain mathematics or such symbols should be written inside two ‘$’ characters or should be preceded by “\\(“ and followed by “\\)” characters.
 
All of static contents containing mathematical expressions will be displayed by now.
 
To render mathematical expressions for dynamic web pages we have to use mathjax typesets. There two types of mathjax typesets – synchronous and asynchronous.
For the synchronous way, we have to use MathJax.typeset(). It will tell mathjax to look for mathematics in the page for any unprocessed mathematical expressions and then typeset it.
 
For the asynchronous way we have to use MathJax.typesetPromise();
The following code snippet should be followed:
 
function doMathJax(div,s){
const done = document.createElement('span');
            done.textContent = '';
            const syncTypeset = div;
            syncTypeset.innerHTML = s;
            setTimeout(async ()=>{
                        await MathJax.typesetPromise();
                        syncTypeset.appendChild(done.cloneNode());
            },1000);
}
Function doMathJax will render mathematical expressions inside the variable s to the html element div.
 
We can do it also as following:
MathJax.typesetPromise().then()=>{
            //modify the DOM here.
            MathJax.typesetPromise();
}).catch((err)=> console.log(err.message));

Thursday, 2 January 2020


SUBHRA’S LAB SERVICES


è Conduct Exam/Interview/Survey Online

·       Conduct Exam/interview/survey remotely through over the internet.
·       To accomplish this Examiner/Interviewer/Surveyor has to send an html form to each of the examinee/interviewee/surveyee
·       The examinee/interviewee/surveyee will answer each/some of the questions and at the end will submit the forms from his/her own mobile phone.
·       The Examiner/interviewer/surveyor will get the responses from the html form and will generate the reports as per his/her requirements.

è ICLOCK-G (Internet Device)

·       DISPLAYS THE TIME(IST) AS DOWNLOADED FROM NTP SERVER
·       DISPLAYS THE CAPTION TEXT AS DIRECTED BY THE USER
·       ONCE SETUP IS DONE THE CAPTION TEXT WILL CHANGE FROM TIME TO TIME
·       THERE IS A CERTAIN TIME INTERVAL BETWEEN TIME DISPLAY & SCROLLING CAPTION TEXT DISPLAY
·       THE USER WILL STORE THE CAPTION TEXTS & DISPLAY TIME/DATE IN GOOGLE SERVER
·       OPERATIONS CAN BE PERFORMED FROM ANY REMOTE PLACE ALL OVER THE WORLD
·       SUITABLE FOR RECEPTIONS, PUBLIC/PRIVATE EVENTS, COUNTERS, OFFICE BOSS’S BACK WALL ETC.

è GONG BELL SCHEDULER (Internet Device)

·       GONG BELL IS SCHEDULED TO RING AS SET BY THE USER
·       AN USER CAN SET A MAXIMUM EIGHT NUMBER OF TIME EPOCHS AT WHICH THE BELL WILL BE SCHEDULED TO RING FROM HIS/HER ANDROID SET
·       AN USER CAN ALSO ISSUE COMMAND TO RING A BELL WHENEVER HE/SHE WANTS
·       ALL OF THESE OPERATIONS CAN BE PERFORMED FROM ANYWHERE IN THIS WORLD
·       BLYNK SERVER & BLYNK APPS ARE USED FOR THE ABOVE OPERATIONS
·       SUITABLE FOR SCHOOLS, WORKSHOPS, INDUSTRIES ETC.

è DISPLAY BOARD WITH CAPTION TEXT SCHEDULER (Internet Device)

·       DISPLAY BOARDS ARE USED TO DISPLAY TEXTS IN ENGLISH/BENGALI
·       TEXTS CAN BE CHANGED REMOTELY FROM ANYWHERE IN THIS WORLD
·       ONCE SETUP IS DONE THE CAPTION TEXT WILL CHANGE FROM TIME TO TIME
·       THE USER CAN STORE THE CAPTION TEXTS & DISPLAY TIME/DATE IN GOOGLE SERVER
·       SUITABLE FOR SHOPS, COUNTERS, HOSPITALS, EMERGENCIES ETC.
·       SPECIALITY IN VERTICAL SCROLLING (UP AND DOWN)

è PCB DESIGNING (USING KICAD)

·       DESIGNING PRINTED CIRCUIT BOARD UPTO TWO LAYERS
·       SUITABLE FOR MICROCONTROLLER INSTALLATION, IC INSTALLATION AND DIFFERENT ELECTRONICS COMPONENT INSTALLATION
·       MAKE A COMPLEX CIRCUIT EASILY ACHIEVABLE

è ANDROID PROGRAMMING

·       OBJECT ORIENTED PROGRAMMING
·       DIFFERENT MODIFIERS
·       ANDROID PROGRAMMING ENVIRONMENT
·       JAVA PROGRAMMING BASICS
·       CREATING DRAWABLE .PNG FILE FOR DIFFERENT SCREENS
·       MANIFEST FILE FOR GRANTING PERMISSIONS FOR DIFFERENT APPS
·       YOUR FIRST ANDROID APP
·       DIFFERNET TYPES OF APPS
  

è ARDUINO PROGRAMMING

·       WORKSHOP ON ARDUINO PLAYGROUND
·       Pre requirements for the Candidates:
·       Physics/Maths with Prior Knowledge of programming language C.
·       Course Details:

Day1
·       Microcontroller
·       ii. Atmega328
·       iii. What is Arduino, Why Arduino
·       iv. Arduino uno, Arduino pro mini
·       v. Arduino ide
·       vi. Hardware Requirements
·       vii. Programming concepts

Day2
·       viii. Hardware connections
·       ix. First Blink program
·       x. Programming Concepts

Day3, Day4
·       xi. Programming Concepts
·       xii. Real Life Project:
o   Switch off/on a light with an ordinary remote control
o   Detecting Human presence in an area under surveillance.
o   Communicating with rf433 Receiver/transmitter.

Day5.
·       Watchdog reset.

Project Kit:
Remote Control (to be supplied
Motion Detector (to be supplied)
Radio frequency transmitter/Receiver. (to be supplied)

Benefits of this Workshop:
i. Making products like street light timer.
ii. Switching off/on selected electrical goods with ordinary remote control.
iii. Making devices for counting of total number of people entered in a hall or in a closed space.
iv. Detecting a particular object from a number of objects.
v. Devising surveillance devices.
vi. Etc.

8051 PROGRAMMING

o   8051 Architecture
o   Kill uVision – the Programming Environment for 8051
o   8051 Basic Circuit
o   First 8051 program
o   8051 Burner
o   Uploading code (.hex file) to 8051
o   8051 Timer Programming
o   8051 Interrupt Programming
o   Interfacing different Devices (any two) with 8051