Android Push Notifications using Firebase Cloud Messaging, PHP and MySQL

Android Push Notifications using Firebase Cloud Messaging

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. FCM replaces Google Cloud Messaging (GCM). Earlier, in google’s documentation “Google Cloud Messaging for Android (GCM) is a service that helps developers send data from servers to their Android applications on Android devices”. Now, using FCM data from servers are send to Android Application on Android devices. For understanding FCM, I am going to demonstrate using Android Push Notifications. Using this service you can send data to your application whenever new data is available instead of making requests to the server in a timely fashion. Integrating FCM in your android application enhances user experience and saves lot of battery power.

Overview of FCM with server

  1. Android Push Notifications using Firebase Cloud Messaging overview
    FCM, Server and Android device

    Android device sends sender idapplication id to FCM server for registration.

  2. On successful registration, FCM server provides registration id to the android device.
  3. Upon receiving registration id, the device sends it to our server for storing it safely.
  4. Registration id is safely stored in a database on our server.
  • Whenever push notification is needed, our server sends message and registration id to FCM server.
  • FCM server delivers the message to respective devices using their registration id.

Registering with FCM

Goto Firebase Console page and create new project

firebase console
Console of Firebase

Give Project a name and choose your countryNew firebase project

Choose Add Firebase to your Android app and follow on-screen instructionadding firebase to android app

Enter your package name and Fingerprint (optional) and click Add apppackage name adding

google-services.json will download automatically add it to the app directory of your android app and click Continuegoogle-services.json

Add all the required dependencies and libraries to your android app project and click FinishDependencies

How server handle Android Push Notifications

Before proceeding with Android push notification application, you should be aware of how request from the device get handled at the server side.

Registering device

The following PHP code runs on the server and connects to a database. It also adds the token received from device to the database.

Also read: install and setup localhost server

Also read: creating database on localhost server

<?php

if (isset($_POST['token'])) {
    $token = $_POST['token'];
    $conn = mysqli_connect("localhost", "root", "", "fcm");
    $query = "INSERT INTO users(token) VALUES('$token')";
    mysqli_query($conn, $query);
    mysqli_close($conn);
}
?>

Sending push Notification

The following code fetches device data from the database stored on the server and then forward the message content along with device token to FCM to send a notification to each device. Authorization:key can found on the FCM server in the cloud messaging section mentioned as server key.

<?php
function send_notification($token, $message)
{
    $url = "https://fcm.googleapis.com/fcm/send";
    $fields = array(
        'registration_ids' => $token,
        'data' => $message
    );
    $headers = array(
        'Authorization:key = AIza################################4DnY',
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

$conn = mysqli_connect("localhost", "root", "", "fcm");
$sql = "SELECT token FROM users";
$result = mysqli_query($conn, $sql);
$token = array();

if (mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_assoc($result)){
        $token[] = $row["token"];
    }
}
mysqli_close($conn);
$message = array("message" => "FCM Push Notification");
$msg_status = send_notification($token,$message);
echo $msg_status;
?>

Creating Android Push Notifications project

Go to Start > Android Studio > Android Studio to open Android Studio

Click Start a new Android Studio project on the welcome screen of Android Studio

Give Application name, create package name and click next

Choose for what you want to build this project, choose minimum SDK (Recommended: API 10 Gingerbread) and click next

Choose to Add no Activity to get rid of messy thing going to happen and Click Finish to build the project. Wait for Gradle to complete building your project.

Open project level build.gradle file to add dependency

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

Open app level build.gradle file to apply plugin. Add this line to the end of the file.

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

Add some of supporting libraries to app level build.gradle file

compile 'com.google.firebase:firebase-messaging:9.6.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'

Open AndroidManifest.xml and add two services as follow

<application>
    
    //...
    
    <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>

Create two class named FirebaseMessagingService and FirebaseInstanceIDService in java folder

FirebaseInstanceIDService.java

In this class, the device will generate token and will request the server to save the token in the online database.

package com.waprogram.androidfirebasecloudmessaging;

import android.util.Log;

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

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d("Token",token);
        registerToken(token);
    }

    private void registerToken(String token) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("token",token)
                .build();
        Request request = new Request.Builder()
                .url("http://waprogram.com/firebase/register.php") //This url is not live now.
                .post(requestBody)
                .build();
        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FirebaseMessagingService.java

This class will display a notification on successful receiving of a notification from the server. It will also open MainActivity on click notification in notification bar. It is one of the inportant class in Android Push Notifications project.

package com.waprogram.androidfirebasecloudmessaging;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.RemoteMessage;


public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String msg = remoteMessage.getData().get("message");
        showNotification(msg);
    }

    private void showNotification(String message) {
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle("FCM Notifier")
                .setContentText(message)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0,builder.build());
    }
}

MainActivity.java

MainActivity initializes the app with the proper token to uniquely identify the device.

package com.waprogram.androidfirebasecloudmessaging;

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

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity {

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

        FirebaseMessaging.getInstance().subscribeToTopic("test");
        FirebaseInstanceId.getInstance().getToken();

    }
}

 

Procedural Oriented Programming vs Object Oriented Programming

Procedural Oriented Programming vs Object Oriented Programming

Procedural Oriented Programming vs Object Oriented Programming is a very interesting topic to discuss. We will discuss how they are different from each other and in what context. At the end of this, you will be able to say which on is best out of POP and OOP.

In Procedural Oriented Programming, as the name implies, it contains step by step procedure to execute. Here, the problems get decomposes into small parts and then to solve each part, it uses one or more functions. It follows Top Down approach. It is less secure because it can hide data properly. Overloading isn’t possible. Making changes to data or function isn’t an easy task. Data easily flow from functions to functions. Example: C, VB, FORTRAN, Pascal etc.

Also read: Object Oriented Programming

Object Oriented Programming is a programming concept which focuses on an object rather than actions and data rather than logic. It follows Bottom Up approach. It is more secure because it uses data encapsulation to hide data from the open world. Overloading and overriding is possible. Adding or modification of data and function is a very easy task. Objects can move and communicate with each other through member functions. Example: C++, JAVA, VB.NET, C#.NET etc.

Procedural Oriented Programming vs Object Oriented Programming : Summary

Procedure Oriented ProgrammingObject Oriented Programming
The program is divided into small parts called functions.The program is divided into parts called objects.
Importance is not given to data but to functions as well as the sequence of actions to be done.Importance is given to the data rather than procedures or functions.
POP follows Top Down approach.OOP follows Bottom Up approach.
POP does not have any access specifier.OOP has access specifiers named Public, Private, Protected, etc.
Data can move freely from function to function in the system.Objects can move and communicate with each other through functions.
It is not easy to add new data or function in POP.OOP provides an easy way to add new data and function.
The most function uses Global data for sharing that are accessible from function to function in the system.Data cannot move easily from function to function. It can be kept public or private so we can control the access of data.
POP does not have any proper way of hiding data so it is less secure.OOP provides Data Hiding so provides more security.
Overloading is not possible.Overloading is possible in the form of Function Overloading and Operator Overloading.

Object Oriented Programming (OOP) to standardize the programs

Object Oriented Programming

Object Oriented Programming (OOP) is an approach to standardize the programs by creating memory area for both data and function. OOP was developed to increase productivity and to overcome traditional approach of programming. It gives more emphasis on data items rather than functions. OOP decomposes a complex problem into a number of entities called objects. These objects in Object Oriented Programming used as a bridge between one function and another function for data flow. You can easily modify data without changing any functions. If you are to define OOP,

An Object Oriented Programming is a modular approach, which allows the data to be apply within stipulate area. It also provide resuasability feature to develop productive logic.

Features of OOP

  • It gives more emphasis to data items rather than functions.
  • It makes the complex problem simpler by dividing them into a number of objects.
  • The objects are used as a bridge to have data flow between functions.
  • You can easily modify the data without changing anything into a function.
  • Provide reusability feature through the implementation of inheritance.
  • Data hiding feature provides security from global world.

Elements of Object Oriented Programming

Among all of us, all have a different interpretation of the concept of OOP. Hence, it is necessary to understand it’s basic elements. Here are some:

  • Objects
  • Classes
  • Encapsulation
  • Abstraction
  • Data Hiding
  • Inheritance
  • Polymorphism
  • Dynamic Binding

Object

Object is a unique entity, which contains data and functions (Characteristics and behaviour) together in OOP language.

In OOP, Problems are decomposed into a number of objects. These are the basic element OOP. The related objects may exchange data and information and interact with each other.

Real World: Table would be the best example. You can give another of your choice.

Table Characteristics: 

  • It has four legs.

    Table an object example
    Table
  • Has a plane top.
  • It can have the drawer.

Behaviours:

  • It is used to keep glasses.
  • Used to keep books.
  • It is also used to keep money in drawer

Classes

The Class is a set of similar objects. Each object of a class possesses same attributes and common behaviour defined within the same class.

Class Example
Automobiles, Pens, Books

In OOP, Classes are used for defining the functionality of objects. These are
called object factory. A class is also called a user-defined data type.

Real World: Automobiles, Pens, Books etc.

Encapsulation

The process of wrapping data and functions into a single unit (called class) is known as Encapsulation.

Encapsulation examples
Television with remote control, Air Conditioner with remote control

In OOP, Class holds both data and functions together. They are not accessible outside the class or globally. It enforces data security by implementing data hiding feature.

Real World: Television with remote control, Air Conditioner with remote control etc.

Abstraction

Act of representing essential features without including background details is known as Abstraction.

Abstraction example
Car, Fan, Bulb

In OOP, Class holds both data and functions together. Only some required functions are accessible by using object of that class. That is, it hides all the functionalities and data from global world.

Real World: Car, Fan, Bulb etc.

Data Hiding

The insulation of data, which cannot be accessed directly outside the class premises although they are available in the same program, is known as Data Hiding.

Real World: Air Conditioner with remote control etc.

Inheritance

It is the process by which objects of one class can link & share some common properties of objects from another class.

The term inheritance is derived from biology. It supports the concept of hierarchical classifications. It provides the feature of reusability by which you can use the existing class.

Real world: Parent to child etc.

Polymorphism

It is the process of using a function for more than one purposes. It allows the use of different internal structure of the object by keeping the same extrenal interface.

Example: Function overloading, Constructor overloading, Operator overloading.

Dynamic Binding

It is the process to link the function call with function signature at run-time i.e., during execution of a program.

Test yourself now!

Object may be defined as

A ________ is an object maker

The process of wrapping data and function is known as?

Ability to take more than one form

Creating Android Application in no time using Android Studio

Creating Android Application

I am learning Android Application Development nowadays. Android is holding today’s market completely. Each and every company are requiring to come to android market to make their business success. For creating Android Application in easy and fastest way one need to have Android Studio and Android SDK (must). I will explain the process of installing android studio and android SDK. According to developer.android.com, Android Studio provides the fastest tools for building the android application. It also provides world-class code editing, debugging, performance management. With a flexible build system, and an instant build/deploy system all allow you to focus on building unique and quality apps.

Downloading and Installation of Android SDK and Studio

  1. System Requirement for installing android studio

    You can find more system requirement on developer.android.com.

    1. Windows

      •  Microsoft® Windows® 7/8/10 (32 or 64 bit)
      • 2 GB RAM minimum, 8 GB RAM recommended
      • 2 GB of available disk space minimum, 4 GB Recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
      • 1280 x 800 minimum screen resolution
      • Java Development Kit (JDK) 8
      • For accelerated emulator. 64-bit operating system and intel® processor with for intel® VT-x, intel® EM64T (intel® 64), and Execute Disable (XD) Bit functionality.
    2. Mac

      •  Mac® OS X® 10.8.5 or higher, up to 10.11.4 (EI Captain)
      • 2 GB RAM minimum, 8 GB RAM recommended
      • 2 GB of available disk space minimum, 4 GB Recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
      • 1280 x 800 minimum screen resolution
      • Java Development Kit (JDK) 6
    3. Linux

      • GNOME or KDE desktop
      • Tested on Ubuntu® 12.04, Precise Pangolin (64-bit distribution capable of running 32-bit applications)
      • 64-bit distribution capable of running 32-bit applications
      • GNU C Library (Glibc) 2.11 or later
      • 2 GB RAM minimum, 8 GB RAM recommended
      • 2 GB of available disk space minimum, 4 GB Recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
      • 1280 x 800 minimum screen resolution
      • Java Development Kit (JDK) 8
      • For accelerated emulator: Intel® processor with support for Intel® VT-x, Intel® EM64T (Intel® 64), and Execute Disable (XD) Bit functionality, or AMD processor with support for AMD Virtualization™ (AMD-V™)
  2. Process of installation

    1. Download Android Studio and SDK according to your system from developer.android.com.
    2. Double-click on the setup file. and
    3. Follow on-screen instruction to complete the setup

      • The installation will check for JDK first, installation of JDK must be prior to Android SDK and Studio installation.
      • Then click Next. Follow screen instruction to choose installation directory and click Next again till Install button appears.
      • Click on install and wait for the installation to complete, it may take up to 20 minutes.

Creating Android Application

This is the very first application so we will create ‘Hello World!‘ displaying application. But before creating an android application, you should know about some view groups, views, widgets etc. However, I will explain some of them here.

  1. Linear Layout

    This is a View Group. It arranges all the elements in order one by one i.e. each element will occupy equal spaces Linearly. It’s some important or required properties. Those properties are its height, width, and orientation. Its height and width can have any custom or constant dimension for a device. Its orientation can be either of two that is horizontal or vertical read more about Linear Layout.

  2. Relative Layout

    It is also a view group that displays child views in relative positions. The positions of each view can be specified as relative to siblings elements or in positions relative to the parent read more about Relative Layout. There are more different view groups such as Frame, Table, Grid etc.

  3. Text View

    Text View is a widget view that displays text in your application. This does not support an editable feature. It can only display information. It is generally used for displaying the description of some other views.

  4. Edit Text

    It is a widget view that displays text and allows you to edit the text in it. It does support editable feature to enable users to enter some text or number etc to process them to generate some meaningful results.

  5. Button

    It is a widget view that allows user to click it and the application will handle click event according to the requirement of the application.

  6. Image View

    It is a widget view, which handles display of Image according to the requirement of application and user.

Creating android application project into Android Studio

  1. Open Android Studio. Start > All programs > Android Studio > Android Studio
  2. Click Start a new Android Studio project.Creating new project
  3. Configure your new application and give it a name and package name, then click Next.name new project
  4. Select Minimum SDK to run your application on. Choose wisely, so that your app can run on many devices.minimum sdk selection
  5. Choose Activity. I chose Blank Activity for this project and click Next.Activity selection
  6. Give Activity a name or leave it the default one.Activity name
  7. Click Finish to start building your application, it will take some time depending on your machine processor and RAM.building project
  8. You see Android Studio coding screen after the successful building of your application.main screen

Coding its Design

In creating the android application, Its material design is very important. It is the presentation factor of an app. So how attractive can it depend completely on your imagination and coding.

<?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"
    android:orientation="vertical"
    tools:context="com.waprogram.helloworld.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</LinearLayout>

We are creating a Linear Layout for this app having a vertical orientation. Its height and width both set to match_parent to adjust with height and width of the device completely.

A text view is also created to hold the text Hello World!. It has height and width of wrap_content.

Source Code

This is important for creating an android application, Application is created by calling an onCreate() function.

package com.waprogram.helloworld;

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

public class MainActivity extends AppCompatActivity {

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

The onCreate method creates the activity and displays them on the device.

HEX Code to color converter Android application using C#

color converter android application

There are about 16,777,216 colors with negligible changes. These colors are convert from HEX (HexaDecimal) code. They form a combination from #000000 (Black) to #FFFFFF (White). You can divide this HEX code into three blocks first for RED followed by GREEN and last for BLUE, Detailed below. About a Month ago, You have come through single C# code for Android, iOS, MacOS and Windows application development. Now you will develop a color converter android application using C# in Xamarin Studio. Also follow steps from Android application on Xamarin Studio.

Understanding HEX code

Color HEX code is a maximum of six characters, and each two character is divided according to RGB color. That is first two characters are for RED, second two characters are for GREEN, and last two characters are for BLUEIt starts with # and followed by other combination up to the maximum of six characters.

HEX number is 16 i.e. 0-15 or 0-F.

Number Hexadecimal conversion
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
13 D
14 E
15 F

Starting project color converter android application

You will need Xamarin Studio and Android SDK for this to code on C# and pack on Android Platform (apk).

Project root directory/Project Structure will look something like below.project directory

 

Design Source code of color converter android application:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <TextView
 android:text="Desinged and Developed by Sumit Ranjan"
 android:layout_width="match_parent"
 android:layout_height="30.0dp"
 android:id="@+id/textView1"
 android:gravity="center"
 android:textColor="#ff5c6bc0" />
 <TextView
 android:text="Enter HEX Value"
 android:textAppearance="?android:attr/textAppearanceSmall"
 android:layout_width="312.5dp"
 android:layout_height="23.5dp"
 android:id="@+id/textView2"
 android:paddingLeft="20px" />
 <EditText
 android:layout_width="match_parent"
 android:layout_height="43.0dp"
 android:id="@+id/hex"
 android:hint="Atleast 6 letters (MAX 6)" />
 <Button
 android:text="Convert"
 android:layout_width="match_parent"
 android:layout_height="40.0dp"
 android:id="@+id/convert" />
 <RelativeLayout
 android:layout_width="382.5dp"
 android:layout_height="27.0dp"
 android:id="@+id/relativeLayout1"
 android:gravity="center">
 <TextView
 android:text="0"
 android:id="@+id/red"
 android:layout_width="122.5dp"
 android:layout_height="wrap_content"
 android:paddingLeft="20px"
 android:gravity="center"
 android:textColor="#ffd50000" />
 <TextView
 android:text="0"
 android:id="@+id/green"
 android:layout_width="128.5dp"
 android:layout_height="wrap_content"
 android:layout_toRightOf="@id/red"
 android:gravity="center"
 android:textColor="#ff00c853" />
 <TextView
 android:text="0"
 android:id="@+id/blue"
 android:layout_width="173.0dp"
 android:layout_height="wrap_content"
 android:layout_toRightOf="@id/green"
 android:gravity="center"
 android:textColor="#ff2962ff" />
 </RelativeLayout>
 <ImageView
 android:layout_width="match_parent"
 android:layout_height="395.5dp"
 android:id="@+id/color" />
 </LinearLayout>

Output:Demo look

 

Summary of Design

  1. LinearLayout

    This layout arranges all the elements within it in order one by one i.e. each element will occupy equal spaces Linearly. Its Height and Width matches parent height and width with vertical orientation(can be Horizontal also). This application contains only one Linear Layout, which contains all the elements including one Relative Layout. Read more about Linear Layout.

  2. RelativeLayout

    It is a view group that displays child views in relative positions. The positions of each view can be specified as relative to siblings elements or in positions relative to the parent. In this application, Relative Layout is used as the child of LinearLayout and holding three Text View as its children. Read more about Relative Layout.

  3. Text View

    It is a view group that displays text in your application. This Text View do not support an editable feature. This application contains five Text Views. Three are for holding color code in decimal number system and two are for information.

  4. Edit Text

    It is a widget group that display text and allow you to edit the text in it. This application contains only one Edit Text, which takes HEX code input from the user.

  5. Button

    It is a widget group that allows user to click it and application will handle click event according to the requirement of the application.

  6. Image View

    It is an image display widget, which handles displaying of Image according to the requirement of the application. This application uses it to display color according to the HEX code you enter.

Source Code of color converter android application:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Util;
namespace HEXColor
{
[Activity (Label = "HEX Color", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
TextView red,green,blue;
EditText hex;
Button convert;
ImageView colorview;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
red = FindViewById<TextView> (Resource.Id.red);
green = FindViewById<TextView> (Resource.Id.green);
blue = FindViewById<TextView> (Resource.Id.blue);
hex = FindViewById<EditText> (Resource.Id.hex);
convert = FindViewById<Button> (Resource.Id.convert);
colorview = FindViewById<ImageView> (Resource.Id.color);
convert.Click += Convert_Click;
}
void Convert_Click (object sender, System.EventArgs e)
{
string hexVal = hex.Text;
if(hexVal!=""){
string redVal = hexVal.Substring (0,2);
string greenVal = hexVal.Substring (2,2);
string blueVal = hexVal.Substring (4,2);
int redColor = int.Parse(redVal,System.Globalization.NumberStyles.HexNumber);
int greenColor = int.Parse(greenVal,System.Globalization.NumberStyles.HexNumber);
int blueColor = int.Parse(blueVal,System.Globalization.NumberStyles.HexNumber);
red.Text = redColor.ToString ();
green.Text = greenColor.ToString ();
blue.Text = blueColor.ToString ();
colorview.SetBackgroundColor (Android.Graphics.Color.Rgb (redColor,greenColor,blueColor));
}
}
}
}

How color converter android application work

  1. using Keyword

    using keyword is used to import libraries internally. This application imports Android.App, Android.OS, Android.Widget and Android.Util.

  2. Local Variables

    These are variables, which are accessible only in that scope where it is declared. TextView red,green,blueEditText hexButton convertImageView colorview are the local variable in this application, which is accessible only within the class it is declared.

  3. Linking to layout

    Later, these local variable is linked with its resource file using FindViewById<TextView> (Resource.Id.red) and so on.

  4. User defined function

    Attaching click event to the user defined function Convert_Click to handle click event by assigning the HEX input value and dividing that into 2-2 parts as explained earlier in this section and assigning them to separate variables and used later.

  5. In-built function

    Setting background of colorview using function SetBackgroundColor and passing another function Android.Graphics.Color.Rgb having three parameters, which is a color value. This color value is fetched using constant System.Globalization.NumberStyles.HexNumber.

How to Create a Chrome Extension in no Time

chrome extension

One of my favorite projects includes Development of Chrome Extension. I developed it for deals and offer site hiva26.com. This Extension is already live on Chrome webstore. But, have you ever wanted to create your own Chrome extension? Have you wondered how difficult it would be? Well, it turns out it is super easy—probably a lot easier than you ever imagined. Now it’s your turn to create chrome extension of your own. In this tutorial, I am going to show you how to create a basic Chrome extension in about 5 minutes—no joke!

What we are going to create?

I’m going to create an extension, which will shorten a URL. This extension will short the URL using srpro.xyz. I actually get frustrated of long URLs, so I decide to create my own URL shortnr site and an Extension also. There are already lots of sites, which short URL such as goo.gl, bitly.com, tinyurl.com, etc.

URL Shortner

 

But for understanding its working I created my own URL Shortening site. This extension will generate a short URL of maximum 15 characters on just a single click. Now let’s proceed with its development.

What is Chrome Extension?

Before we get to start with building our extension, it’s probably a good idea to have a basic understanding of what it is and how it work. Extensions are small software programs that can modify and enhance the functionality of the Chrome browser. You write them using web technologies such as HTML, JavaScript, and CSS.

Extensions have little to no user interface. Extensions bundle all their files into a single file that the user downloads and installs. This bundling means that, unlike ordinary web apps, extensions don’t need to depend on content from the web. You can distribute your extension using the Chrome Developer Dashboard to publish to the Chrome
Web Store. Read more about extension documentation.

Step 1: Creating project URL Shortener

The first thing we need to do is create the project and all the files we need for our extension. Let’s start by creating a new directory that we’ll call “URL Shortener”. We’ll put all the files we need for our extension in this new folder. Chrome allows us to load up an extension by pointing it at a folder that contains the extension files.

All Chrome extensions require a manifest file. The Manifest file tells Chrome everything it needs to know to properly load up the extension in Chrome. So we’ll create a manifest.json file and put it into the folder we created. You can leave the manifest file blank for now.

Next, we’ll need an icon for our extension. This just needs to be a 32x32px or 64x64px or 128x128px PNG file or three of them. You can get a sample icon from Google’s demo project that you can modify.

Next, we’ll need an HTML page to show when a user clicks our Browser Action. We’ll create an index.html file and a start.js file in our “URL Shortener” directory.

Due to security constraints, we can’t put inline JavaScript into our HTML files inside of our Chrome extensions. We have to create a separate file to hold any JavaScript code we need and we’ll reference it from the HTML file.

Step 2: Create manifest.json file

We have our basic project structure. Now we need to add the code to our manifest file to describe our plugin to Chrome.
Open up the manifest.json file and enter the following code:

{
 "manifest_version":2,
 "name":"URL Shortnr - srpro.xyz",
 "short_name":"URL Shortnr",
 "description":"Shorten. Share. Monitor.",
 "version":"1.0",
 "browser_action":{
 "default_popup":"index.html"
 },
 "icons":{
 "32":"image/icon.png",
 "64":"image/icon.png",
 "128":"image/icon.png"
 },
 "permissions":[
 "http://srpro.xyz/",
 "activeTab"
 ]
}

Most of the fields in this JSON file are self-explanatory, so I needn’t waste your time explaining everything. But take note of the browser_action section where we specify what HTML page should be displayed.

You’ll also notice I’ve added a permissions section that specifies that we need to have permission to access the “activeTab”. This is required in order to enable us to get the URL of the current tab to pass on to URL Shortener.

Step 3: Create the UI

The next step is creating the UI for URL Shortener, which will be displayed by browser_action when it is clicked. Its User Interface is very simple, it will only display shortened URL.

chrome extension

 

Open up the index.html page and add the following:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>URL Shortnr</title>
<style type="text/css">
body{
 margin:0;
 padding:0;
 color: #3b5998;
 background-color: #fff;
 font-family: Aldrich;
 font-size: 15px;
}
body{
 padding:5px;
 height:70px;
 width:300px;
}
a{
 color: #ff0000;
 text-decoration: none;
}
.container{
 width:auto;
 height:auto;
}
</style>
 <script type="application/javascript" src="jquery.min.js"></script>
 <script type="application/javascript" src="start.js"></script>
</head>
<body>
<div class="container" id="append">
</div>
</body>
</html>

You’ll notice in this HTML I’ve included the start.js script. This is where we’ll put the logic for our chrome extension.

Step 4: Implement the logic

The last thing we need to do to create the plugin is to implement the logic that should execute when a user clicks the browser_action button in chrome browser. We’ll want to add an event listener to listen for the click event on the browser_action.

When it is clicked, we will post submit the URL contain in the Tab to the srpro.xyz server and intern it will return us a handsome shortened URL of fifteen characters long.

Open up the start.js file and add the following code:

$(function () {
 chrome.tabs.getSelected(null,function(tab) {
 $.post("http://srpro.xyz/php/short.php",
{url:tab.url},
function (data) {
 $("#append").html(data);
 }).fail(function () {
 $("#append").html("Something went wrong");
 });
 });
 $("#append").click(function () {
 var u = $("#append>a").attr("href");
 window.open(u);
 });
});

Note: The Implementation/JavaScript code is only for Educational purpose. Wrong use may lead you to the problem.

Testing it out

Type chrome://extensions in a tab to bring up the extensions page. Check Developer mode to enable loading unpacked extensions. This will allow you to load your extension from a folder. Click “Load unpacked extension” or simply drag the URL Shortner folder onto the page to load up the extension. You should immediately see the extension show up as a Browser Action with your icon in the toolbar window of the current tab.

To test out the extension, navigate to a page you want to test with URL Shortnr. Then, go ahead and click the icon for our URL shortener extension, after the HTML page comes up, you will see Shortened URL of the current tab URL.

And that’s it! If you have any problems or questions, feel free to add to the discussion below. I hope this introduction to creating Chrome extensions has been sufficient to get you started.