Blog


Reading Time: 2 minutes
Uruguay is creating capabilities and starting projects in Distributed Ledger Technologies.
Monday sunset witnessed a group of people meeting to talk about distributed ledger technologies in a rooftop very close to the Catholic University in Montevideo. In fact, Alejandro Narancio, a seasoned architect and software developer for more than 15 years, who runs a professional services company servicing customers in Latin America and United States, conducted this first meetup.
He has been involved with bitcoin and blockchain technologies since 2010, and currently is handling a project fully based in distributed ledger technologies using IBM Bluemix. Alejandro decided to start blockchain meetups in Montevideo and kicked off explaining to the audience what is bitcoin, how blockchain works, the importance of the smart contracts and some platforms like Ethereum. Deeper sessions are expected for future meetups to discuss multiple applications in different industries and addressing topics of interest of an unexpected numerous audience.
The meetup group was created by mid-December 2016 and got interest very quickly with many folks joining the group. Alejandro had to close the meetup invitations weeks in advance since the interest filled the rooftop capacity.
Alejandro proposed a very practical agenda, just to show the basics of these technologies and its origins. The audience in Uruguay could learn about bitcoin features and Satoshi Nakamoto, its main components, the problems that addresses, the process of sending a bitcoin, how mining works, cold storage, the underlying blockchain technology and its features, hashes, blocks and block chains. He also explained the concept of public and private blockchains and applications in the form of business use cases.The audience was very interested and was uncovered lot of interest of doing things in these technologies. That’s why the audience kept the attention to listen about smart contracts (something Nick Szabo started to talk about 20 years ago), what they are and some examples, and main platform products like Ethereum, Hyperledger IBM Bluemix and Argentinian RSK Rootstock Smart Contracts. The session finished with some details about Ethereum platform.

More meetups are planned, and will address topics like blockchain and the internet of things, Solidity (the most popular language for writing smart contracts in Ethereum), Hyperledger and blockchain based architectures.
After the meeting the crowd enjoyed pizzas, crafted beers and cupcakes. The attendees received a Paper Wallet Gift and a Cheat Sheet from the host InfUY who sponsored the event.

[WRG id=338]

Reading Time: 3 minutes

At Infuy we have been always looking for ways to improve the development skills and reduce the amount of errors. We have developed several applications for our clients and we come up re-doing several stuff over and over again, multiple times.In traditional application development, designers create original UIs and delivered a Photoshop file, (is the design tool of choice for many user interface UI-designers) and tell us what they would like the mobile app looks like. This can lead to the developer to spent a big amount of hours to create the skin of the application for all the size devices.
So we have thought that need to make something to improves this workflow and the best approach was to create a tool (KataPSD) that allows you to work most efficiently and effectively, and when it comes to creating stunning graphics and interfaces.
As we said, over the past year at Infuy we had this issue with mobile projects development. The big problem was time and effort spent on reading a photoshop file and creating all the components involved, so we need to reduce the hours and errors from our developers!
That was the background and as result we have come up with KataPSD.
For now we have released a closed Beta in order to control what projects and also give more feedback to the developers. But feel free to ask for a token to enter to the application. I will explain how this works briefly.
This is the login page from our application.
 

Login kata application
Login kata application

If you have the credentials settled up once you gain access you will see the following homepage.

 
In this page you will find a test application that we have made. You can have as many projects as you wish in this homepage. You can create more with the link on the upper right side of your screen. Once you click on a project you are going to be redirected to the following page.
 

 
 
 
In the first screen you can set the splash screen, icon and navbar images. Also you can start uploading the PSD in order to start working with all the layers in the PSD file, this layers are being handled as ‘screens’ and you can work at the same time with multiple PSD files at the same time to use in one project.
We will be uploading a video with some demo explanation of how KataPSD works.
In some point you can see a preview of all the components that are being rendered. One of the best functionalities that KataPSD has is the availability to download all the assets of the PSD within seconds, so supposed that you do not want yet to create the project.. so you can meanwhile download all the images from the PSD to start manipulating it.
 

This is the page that we are talking about. With the Full project function, you will be allow to download a complete XCode project with all the functionality working, you just need to start coding.
But feel free to checkout our site and start working on this! If you have some questions or doubts we will glad to help you with this. We are finishing the Android generating so stayed tunned for news.
Please check out the video

KataPSD team.
 

Reading Time: < 1 minute

As mentioned in Wikipedia “Internationalization and localization are means of adapting computer software to different languages, regional differences and technical requirements of a target market (locale)(1).
In the context of Angular 2 applications, a popular tool for translation is ng2-translate (https://github.com/ocombe/ng2-translate).
While pretty effective in translation of texts we detect a possibility of improvement in localization aspects. Particularly there was no clear solution on how to efficiently manage text for different locales in the same language. You were forced either to copy all your translations in all the language files but adjusting the differences, or develop a solution like this plugin.
That was the inspiration for the plugin, while very simple it adds a bit of help at localizing applications, you just need to store the differences in the localization files and the default version will be extracted from the main language file.
You can see more details at https://www.npmjs.com/package/ng2-translate-localize but as a summary, the plugin adds the possibility of manage different files for each particular locale (es.json, es-UY.json, es-AR.json, …) and helps on the resolution of the translations against those files.

Reading Time: < 1 minute

At Infuy we are working in some internal products, one of them is this which is just launched (free version). With this version you are going to be able to generate a unsigned APK with a lot of functionalities. We are working on finishing the premium which will have several features such us, sending push notifications, Ads (Admob and DFP), availability to select some plugins from WordPress already being used and sign your APK.
But let me tell you a little more about this version 🙂 This will work for every WordPress blogger which want to have an Android application without any IT knowledge! You just need to install the plugin and you will have an unsigned APK that can be uploaded to the stores.
In this plugin you will be able to:

  • Change the colors of the layouts.
  • Add a splash screen
  • Add some banners
  • Customize the menus
  • See information of WooCommerce plugin
  • Bbpress, BuddyPress and AnsPress plugins

And you will have all your information in an android app within minutes. We will email you the APK package and if you want it you can contact us and we will the store work for you.
We will be launching the premium plugin later which will have a lot of features but first we would like to see how this behaves in the actual WordPress versions alive in the web. The plugins which will be available in the premium version are: BBpress, Buddypress, WooCommerce and Anspress.
So please stay tunned 😉
Checkout our site and you can download from Google Play the demo.
Visit our demo in the playstore (premium not released): WpToAndroid App Demo
This is our site: WpToAndroid Site
This is the plugin wordpress page! check it out! Link to demo
 

Reading Time: 2 minutes

AJAX (Asynchronous JavaScript and XML) is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. With that said you could use Javascript in conjunction with PHP or other languages (in this case of course it will be PHP)  🙂
Before starting to making a call to ajax we might need to understand a little bit of:

  1. How are the ajax calls are being made
  2. How are the files involves in WordPress that can be update and how is the process.

Ajax calls.

In this post i will assume that we all know the existence of <a href=”http://jquery.com/” target=”_blank”>jQuery</a>. Which will allow us to make things a little easier to understand.
With jQuery you have one function that can be called like this:

$.ajax({
type : 'post',
url : ajaxloading.ajaxurl,
data : {
action : 'sort_results',
parameter1: $value1
},
beforeSend : function() {
//some logic that will prevent for example execute twice the button
// you can disabled the button or showing a loading gif.
},
success : function( response ) {
// display the button again or hide the loading gif.
}
});

In this example we call ajax method which perform an asynchronous HTTP (Ajax) request. In this case we will do a ‘POST’ call.
In the data array we can pass the parameters which will be handled in the method that is called. One of this parameter needs to be the ‘action’ will be explaining later the purpose of this.
Lastly, we setup a ‘success’ method that will be the one which handles the return of the call and do some logic in the page.

WordPress files

functions.php or the theme functions file is a template used by WordPress themes. It acts like a plugin and gets automatically loaded in both admin and front-end pages of a WordPress site. In this file we will define the method which will be called from the javascript function

//function to sort results on resources page via AJAX
function sort_results() {
  $param1 = $_POST['parameter1'];
    ob_start();
    .....
    $content = ob_get_clean();
    echo $content;
    die();
  }
}
add_action( 'wp_ajax_sort_results', 'sort_results' );
add_action( 'wp_ajax_nopriv_sort_results', 'sort_results' );

In this code snippet we have two importants things.

  1. the call add_action which will be registering in wordpress that we have and wp_ajax_sort_results which will execute or tie to sort_results function.
  2. The actual function that handles the logic, get the parameters and echo the output.
  3. If you don’t, admin-ajax.php will execute it’s own die(0) code, echoing an additional zero in your response.

It is important that you realize that the name of the action will be the same as the wp_ajax_XXXX. The function can be named anything, I just used the same string as the action name for consistency.

Conclusion

Ajax is a powerful tool in a developers tool belt to add interactivity and to lower server strain. This can opens a lot of doors, but if you do not make the things in a right way your code could messy and hard to mantain. WordPress give you the possibility to use his framework to use it so it will be a good change to take advantage of it!.
 

Reading Time: 5 minutes


If you were reading the headlines in the last months you must have read something related to Google and his huge milestone with AlphaGo. But, what is AlphaGo and more important what it means for our future?
 

Why Go?

Go is the traditional challenge for test an AI system. Since a few decades back the target of most of the AI research labs in the world was to develop a system able to beat a Go master player.
But why Go? Go was originated on China around 3.000 years ago, the rules are quite simples. There are two players (one with black stones and the other with white) that take turns to place stones in the board (the board in general is with a size of 19 x 19 lines). Each player tries to capture stones from his rival or surround empty space to make points of territory.
Even with those simple rules, the possible boards combinations of Go are quite large, even are quite more combinations than chess. Let’s try to put it in numbers; the possible boards combinations in chess is something around 1 x 1057, which is a huge number! But nothing compared with Go, which are the possible board combinations of Go (for a 19×19 board)? Well is around 1 x 10170! As you can imagine this number is bigger than chess.
But let’s put that number in perspective, the universe has around 1 x 1080 atoms, so Go has more board combinations than atoms in the universe. Not only that, it has more combinations than 1 x 1080 universes each one with 1 x 1080 atoms! Impressive right?
As you can expect is practically impossible for a computer (or all the computers in the actual world) to evaluate all those possible boards during a Go match.
At this point you can think that the only difference between Go and Chess is the number of possible boards, but that’s not complete true.
In a Chess game you can always determine who is wining, each piece has a value and you know that if you have a queen and your adversary doesn’t you’re probably wining. Also in Chess there are well known heuristic, so a master in Chess can explain why is moving a piece to a particular position.
In Go those things are not true, first you can’t be sure all the time which player is wining, and second there aren’t heuristics to evaluate each move. Go masters just trust in his intuition and feel, if you ask to a Go master why he made some particular move he will probably answer because he feel it in that way.
So this last part is what makes Go so particular, interesting and hard to play to AI, mimic that “feeling” sense was the biggest challenge for a software who tries to beat a Go master player.
 

What is AlphaGo?

 
But what is AlphaGo after all?
AlphaGo is a computer program, which use deep learning and Google’s neural network in order to teach itself to play go.
But what is a neural network? Neural networks try to simulate the neurons in the brain. In biology a neuron has 3 main parts:

  • Dendrite (who takes the input)
  • Soma (make something)
  • Axon (output)

So basically (and I am trying to simplify the concepts here) a neuron takes one or more inputs, do something with that input and may produce an output. That is the behavior software neural networks try to accomplish. A neural network system can contain a single layer of neurons or be a multi-layer system, where one layer takes as input the output of the previous layer.
AlphaGo takes the board description as an input (that means the entire board with all the stones places over him) and process this input over 12 different network layers containing millions of neuron-like connections. The output of this will be a small set of the best possible moves, how AlphoGo calculates this set and how decides which move must select is out of the scope of this post.
 

What makes AlphaGo so special?

 
This is not the first time an algorithm beat a master in some game. If we look back we can remember when IBM Deep Blue beat Garry Kasparov twenty years ago.
But which is the difference between AlphaGo and Deep Blue?
Well Deep Blue was created to play chess, it had handwritten algorithms and heuristics to know which was the best move to make based on the state of the board. In the other hand AlphaGo use a combination of neural network to learn how to evaluate a board and figure out which is the strongest move to make, and mimic that “intuition” that a master Go player has.
Deep Blue can only play chess, and that’s it. It’s one of the best (if not the best) chess algorithms invented by the human but it can’t play Go or checkers. It just can’t because he only knows how to play chess and he is not able to learn new abilities.
The algorithms and methods used in AlphaGo can be used to learn any game; Go, Chess, checkers, Atari, or whatever. In the case of AlphaGo the intention was to teach the system to play Go, so Google researchers feed the system with millions of historical games and put the system to play online and against itself until the system has enough training to play itself and beat one of the best human players in the human history.
See the difference? Deep Blue was a huge achievement for that time. But was hand programmed to make a unique task and had one of the larger processing power for his time. AlphaGo in the other hand it has not be hand programmed to play go, the same system can learn any other topic. It just needs a huge amount of data and training. If you give these two things he will get better and better at the time goes.
 

What this AlphaGo winnings means for all of us?

 
It’s hard to predict exactly what AlphaGo means for our future. Before AlphaGo the experts were confident to make predictions for the next 10 years, but now they aren’t sure for more than the next 5 years.
Is AlphaGo (or any other neural network) near to be as powerful as the human brain? Well not yet, the human brain has around 1 trillion synapses between they neurons. Right now the biggest public known artificial neural network has around 1 billion synapses between they neurons. So we are around 1000 times less powerful than the brain.
How long it will take to an artificial neural network reach the milestone of 1 trillion synapses? Nobody knows with confident, we are sure that it will not be in the next 5 years, but we aren’t sure if it will take 6 or 20 years. But is definitely a fact that someday we will get to that point.
AlphaGo itself as a great Go player is not quite significant for us; it will not affect our lives. But what AlphaGo means in the sense of an artificial neural network capable of self-learn how to play one of the hardest games in the history and beat the BEST player of the world in that game, that’s important. Is important to notice the idea of an artificial system learning a new discipline and become in just a few months better than any human (more particular than a human that been playing the same game all of his life). Is important to understand that master Go players wins games following his intuition and AlphaGo prove that we can teach an algorithm to do that (or at least to make it look like it does).
Is hard to predict what will happen in the future, is clearly uncertain what will happen. What is a fact for me is that we are just seeing the top of the iceberg, this area will continue to evolve and progress and probably it will progress faster over the next months/years.
For us as computer scientists or IT companies we have to start to learn these new topics and start to integrate in our development workflows. Is without a doubt a game changer in how we make the things (or how we learn or are used to make the things), but we should start to take it seriously and at least learn and think how to integrate this new/old technologies in our daily jobs.

Reading Time: 5 minutes

Some time ago (a few years to be more accurate), I had an epiphany, if I may embellish it, or in a common Uruguayan idiom: me cayó la ficha.
I realized the following:
Writing CSS can be really simple if we only focus on changing an element’s width, height or background color. Like a painter coloring a drawing, if we need to change the color we need to start over, change the brush and use the correct color.
It might sound silly, but when given some thought, doing the same in CSS involves only to copy code and change the background property. The same can be said for hundreds of examples.
What happens when we’d like to write our CSS with the goals that the code has to be maintainable, scalable, predictable, reusable, etc?
If we want to avoid the impossible task of maintaining spaguetti code, we may find salvation in one or many Holy Grail solutions that can be found online. It sounds like an hyperbole but in the end they might save us from the nightmare of refactoring such code.
We’ll show here 3 methodologies:

  • OOCSS (Object Oriented)
  • SMACSS (Scalable Modular Architecture)
  • BEM (Block, Element, Modifier)

It should be noted that these are not W3C defined standards. This means they are not absolute laws on how code must be written but general practices that we can follow.
OOCSS
“The main premise is to follow object-oriented programming paradigms in regards to code reuse. The goal of OOCSS is simple: to build optimized code that allows us to quickly and easily improve on it”.
– ID:
Usage of ID should be exclusively relegated to forms and in JS code. When writing CSS we should only use classes which allows us to easily reuse code when necessary.
– Properties
Since code reduction and reuse are the goals we need to pay extra attention to similar elements that have repeated properties. Ideally we should take those common properties and group them in a common class, with unique properties to each element in a new class.

SMACSS
More than a set of best practices, these can be considered an architecture, a guide for writing styles or even a philosophy created by Jonathan Snook.
It is basically a way to organize our CSS files in a project in order to improve maintainability, flexibility and the possibility of scalability in time. This is achieved by categorizing styles files. SMACSS defines 5 types of categories:
– Base files
These include base styles, normalization, typographies, etc.
– Module files
Modules are reusable independent components (This are called components in OOCSS. While in BEM they are known as blocks)
– State files
As the name implies, these are the state rules for the modules. Here is defined the look of each modules in each particular state.
– Layout files
These are styles that format our grid. For example: size of columns, etc.
– Theme files
These are related to the visual look of the site: sizes, shapes, colors, etc.



We invite the reader to research more on these two methodologies previously mentioned while now we’ll focus on
BEM.
What is BEM?
It is a methodology with three fundamental rules to name and categorize CSS selectors in a strict, transparent and self-explanatory manner.
– Block
It is an independent entity. It can be seen as an object or module.
.block {}
– Element
It is a part of a block that serves a particular purpose. For example a title or a button.
.block__element {}
– Modifier
It handles the changes of look or behaviour of blocks or elements. For example the appearance of a menu when the status is active.
.block–modifier {}
Now let us continue with something more practical:
HTML
<div></div>
We can apply a bunch of CSS properties to this simple DIV in order to make it look how we like; however this does not mean we should put all eggs in one basket.
Let us do the following:
HMTL
<div class=”news”></div>
Inside our DIV we want to show news, but what if we would like to have different categories like Technology, Economy, Fashion, etc? What if each category must have its own unique look (color, backgrounds, sizes, etc)?
How should we accomplish this?
CSS
.news-technologies{…}
.news-economy{…}
.news-fashion{…}
 
If we do it this way, we will make it simple and easy for us, at least for the moment. But like I said, this is putting all eggs in one basket just because we can.
What if we think differently and try to implement BEM when styling our news?
I can be as simple as writing something like this:
CSS
.news{common properties…}
.news–technologies{…}
.news–economy{…}
.news–fashion{…}
 
HTML
<div class=”news news–technologies”></div>
<div class=”news news–economy”></div>
<div class=”news news–fashion”></div>
 
What we just did is create a block and a modifier
CSS
.news{ common properties …} /* Block */
.news–technologies{…} /* Modifier */
 
What if we’d like to add a new element inside our news DIV like for example a title?
We might write something like this:
CSS
.news__title {} /* Element */
HTML
<div class=”news news–technologies”>
<h1 class=”news__title”></h1>
</div>
 
Let us now summarize and try reach a conclusion. We may think a chance as small as this can not make a difference, but we need to see the forest from the trees.
Imagine a large website with hundreds of elements that need styling. What if you could modify each element or block depending on the situation, status or location in the page with the knowledge that any new feature can be solved by the creation of a new Modifier class, maximizing code reuse?
It is difficult to believe, right? But if you try to look beyond and understand the premises behind, you might find out that by using BEM (or OOCSS, or SMACSS) your world can become much better.
 
The conclusion I reached, in that, in my personal opinion, each paradigm has a bit of the others.
What if we could mix all premises and also use preprocessors (like CSS on steroids :D) like LESS, SASS or Stylus, taking them into the next level.
We can agree that the end result is only limited by our imagination, or rather by the scope of the project we are working on. We can now know that when the projects grows we can do the same, like friends walking side by side. We can now follow any new trend or fad, like becoming Web 2.0, or looking flat, or being at the front of a Material Design….
I can go on. Like I said, our limit is in the imagination.
 
Here are some examples on how to implement it:
CSS

.btn {
display: inline-block;
cursor: pointer;
font-size: 14px;
padding: 6px 12px;
color: #ccc;
text-decoration: none;
}
.btn--small {
padding: 3px 8px;
font-size: 12px;
}
.btn--medium {
padding: 6px 15px;
font-size: 14px;
}
.btn--large {
padding: 8px 20px;
font-size: 16px;
}
.btn--rounded {
border-radius: 5px;
}
.btn--cancel {
background: red;
color: #fff;
}
.btn--active {
background: blue;
color: #fff;
}
.btn--ok{
background: green;
color: #fff;
}

 
HTML

<a href="#" class="btn btn--small btn--cancel btn--rounded">BUTTON</a>
<a href="#" class="btn btn--medium btn--cancel btn--rounded">BUTTON</a>
<a href="#" class="btn btn--large btn--cancel btn--rounded">BUTTON</a>
<a href="#" class="btn btn--large btn--active btn--rounded">BUTTON</a>
<a href="#" class="btn btn--large btn--ok">BUTTON</a>

 
 
Inspired by:
CSS Architecture, by Philip Walton (11/16/12)
MindBEMding – getting your head around BEM syntax, by Harry Roberts (1/25/13)

Reading Time: 5 minutes

We had to implement in some of our android apps the ability to send push notifications in order to send a message or a notification of a new event to the devices, request data synchronization, etc. In this case we will be showing a scenario using PHP and MySQL on the backend, which will serve downstream messages through HTTP to our app.
As you might know the worflow in which Google Cloud Message works is as follows:

  1. First android device sends sender id and application id to the GCM server for registration.
  2. Upon successful registration GCM server issues registration id to android device
  3. After receiving registration id, device will send registration id to our server
  4. Our server will store registration id in the database for later usage.
  5. After this, whenever a push notification is required, our server sends a message to GCM server along with the device registration id
  6. GCM server will deliver that message to the right mobile device using that registration id.

In order to register your project into the Google Cloud Messaging you will need to access to Google APIs Console page
The project ID you get will then be the one used as the sender id in your android app. You must then go and click on Services on the left pane and turn on Google Cloud Messaging for Android.
Finally, click on API Access and note down the API Key, as this API key will be used when sending requests to GCM server.
Ok now let’s jump to the code and see how it is done!

Components

In order to get this to work we’ll need to create a few components in our android app.

GcmBroadcastReceiver

This is the Receiver that receives notifications from GCM servers and starts a service to process the message in a background thread. It basically forwards the intent to the background service, in our case will be using an IntentService. If you noticed, we are using a WakefulBroadcastReceiver which is a helper class for implementing a Receiver that gets a device wakeup event (holding a wake lock) and starts a service to do the work, all this ensuring that the device doesn’t go back to sleep while the service is setup and starts. The service then notifies the receiver to release the wake lock once it’s work is done.

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.ON_AFTER_RELEASE, "WakeLock");
        wakeLock.acquire();
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
        wakeLock.release();
    }
}

We then have to define the receiver in the manifest, providing the right intent filter to be able to respond to GCM messages. Consequently, we set the intent filter action to be com.google.android.c2dm.intent.Receive

<receiver
       android:name=".network.gcm.GcmBroadcastReceiver"
       android:permission="com.google.android.c2dm.permission.SEND" >
     <intent-filter>
          <action android:name="com.google.android.c2dm.intent.RECEIVE" />
          <category android:name="com.infuy.example.android.gcm" />
     </intent-filter>
</receiver>

GcmIntentService

This is the IntentService that handles the intent that comes from GcmBroadcastReceiver and sends a notification with the message content once it’s done

public class GcmIntentService extends IntentService {
    private static final String TAG = GcmIntentService.class.getName();
    public static final int NOTIFICATION_ID = 1;
    public GcmIntentService() {
        super(GcmIntentService.class.getSimpleName());
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);
        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            switch (messageType) {
                case GoogleCloudMessaging.
                        MESSAGE_TYPE_SEND_ERROR:
                    sendNotification("Send error: " + extras.toString());
                    break;
                case GoogleCloudMessaging.
                        MESSAGE_TYPE_DELETED:
                    sendNotification("Deleted messages on server: " +
                            extras.toString());
                    // If it's a regular GCM message, do some work.
                    break;
                case GoogleCloudMessaging.
                        MESSAGE_TYPE_MESSAGE:
                    // Post notification of received message.
                    sendNotification(extras.getString("message"));
                    Log.i(TAG, "Received: " + extras.toString());
                    break;
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }
    // Put the message into a notification and post it.
    private void sendNotification(String msg) {
        NotificationManager mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent notificationIntent = new Intent(this, NotificationMessageActivity.class);
        notificationIntent.putExtra(NotificationMessageActivity.NOTIFICATION_MESSAGE, msg);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack
        stackBuilder.addParentStack(NotificationMessageActivity.class);
        // Adds the Intent to the top of the stack
        stackBuilder.addNextIntent(notificationIntent);
        // Gets a PendingIntent containing the entire back stack
        PendingIntent contentIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(getString(R.string.notification_title))
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(msg))
                .setContentText(msg)
                .setAutoCancel(true);
        mBuilder.setContentIntent(contentIntent);
        Notification notification = mBuilder.build();
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }
}

As well as we did with the receiver, we need to define the IntentService in the application manifest in order to have it available in our app.

<service android:name=".network.gcm.GcmIntentService" />

Permissions

Your application must request some permissions to the Android system.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<permission
 android:name="com.example.gcm.permission.C2D_MESSAGE"
 android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />

 

Example code

The following method will check if the Google Play Services APK is installed and available on the device. If not, it will attempt to fix the error showing an error dialog which will lead the user to Google Play app so they can download and install the required APK.

private boolean checkPlayServices() {

    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());

    if (resultCode != ConnectionResult.SUCCESS) {

        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();

        } else {

            Log.i(TAG, "This device is not supported.");

            getActivity().finish();

        }

        return false;

    }

    return true;

}

The following method registers the application with GCM servers asynchronously and stores the registration ID and app versionCode in the application’s
 shared preferences.


private void registerInBackground() {


new AsyncTask<Void, Void, String>() {

        @Override

        protected String doInBackground(Void... params) {

            String msg;

            try {

                if (mGcm == null) {

                    mGcm = GoogleCloudMessaging.getInstance(getActivity());

                }

                mRegId = mGcm.register(getString(R.string.gcm_sender_id));

                msg = "Device registered, registration ID=" + mRegId;




                storeRegistrationId(getActivity(), mRegId);

            } catch (IOException ex) {

                msg = "Error :" + ex.getMessage();

            }


     return msg;

}


@Override

protected void onPostExecute(String msg) {

            Log.d(TAG, msg);

        }

    }.execute();

}

Once you have the Registration Id from GCM servers, you need to send it to your backed server which will include the id when triggering a notifcation. The following example shows a Volley request, sending the registration id to our server. Further reading about Volley here

JsonRequest request = new JsonRequest
        (Request.Method.POST, RegistrationService.URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // handle server response ...
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // handle server error response ...
            }
        }){
    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("gcm_regid", mRegId); // mRegId is the registration Id obtained from gcm.register()
        return params;
    }
};
request.setTag(TAG);
ServicesHandler.getInstance(getActivity()).addToRequestQueue(request);

On the backend, you’ll need to have a place to store this registration Id (usually in a table)  and associate it with your users in order to attach the Id to the push notification requests you send to GCM servers.
This is the snippet of code on the php backend that sends the notification to the device through the GCM servers.

/**
     * Sending Push Notification
     */
    public function sendnotificationAction() {
        ...........
        // Get the user_id
        $register_id = $user->gcm_regid;
        $message = ‘This is a notification to send to the user’;
        // Set POST variables
        define("GOOGLE_API_KEY", “XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”);
        $url = 'https://android.googleapis.com/gcm/send';
        $registration_ids = array($register_id);
        $message_json = array("message" => $message);
        $fields = array("data" => $message_json, 'registration_ids' => $registration_ids);
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();
        // Set the url, number of POST vars, POST data
        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_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        // Close connection
        curl_close($ch);
        return true;
    }

And that’s pretty much it. We encourage you to try introducing push notifications in your app, as it not only introduces a mechanism to send push notifications from your backend and get them displayed them in your android status bar, but it also allows you to have your server begin a communication with your app. This is useful to prevent your app from having to poll your server for some new event or data, which means avoiding the cell radio draining your battery and have your app use fresh data instantly. Moreover, you can have your server trigger periodic sync updates at any given time or when some new data is available and eligible to be updated on your client apps.

Reading Time: < 1 minute

In some register forms you need to get the phone number in order to avoid that some users enters some invalid phones. So in order to achieve this you could detect the number from the SIM. The tricky point is that some Carriers does not have such info updated on the SIM, so in this scenarios this will not work.
Here there is a snapshot in which place you need to take a look to see if the phone is correct in the cellphone.
As you can see here the ‘My phone number’ is Unknown, so I do have a Carrier which does not update correctly the phone in the SIM 🙂
In this scenario we do have register the phone.
The code in order to grab the information of the SIM in case the info is there is the following:

 public static String getSIMCardPhoneNumber(Context context){
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String phone = tm.getLine1Number();
        String dId = tm.getSimSerialNumber();
        Log.d("SIM", "Phone number: " + phone);
        Log.d("SIM", "Did number: " + dId);
        return tm.getLine1Number();
    }

I hope this helps you!