Sunday, 15 November 2015

Create your own chrome plugin example demo

Background

In this post we will see how to create chrome plugins. We will see a simple demo plugin example in which when we click on the plugin icon we will will see the URL of current active TAB.


Getting Started

Create a directory where you will create files needed for your plugin. Lets call it "chrome_plugin" directory. 
  • First and foremost what you need is a file called manifest.json. This file essentially tell chrome browser details about your plugin like it's name, it's version, what permission it needs and the actual code files.

For our demo this file looks something like below -

{

  "manifest_version": 2,
  "name": "Open Source For Geeks Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },

  "permissions": [
   "activeTab"
   ]

} 


Contents of manifest.json file are basically json with plugin details. As you must have notices by now it references two essential resources -
  1. icon.png
  2. popup.html
  • Go ahead and put icon.png and create a file called popup.html is the same directory - "chrome_plugin".




 If you do not have the icon you can use the one above. It's 20*20 pixels icon.

  • Next edit popup.html with following contents - 

<!doctype html>

<html>
  <head>
    <title>OSFG Chrome Demo Plugin</title>
    <script src="popup.js"></script>
  </head>
  <body>

    <h1>Current Site URL : </h1>
    <br/>
    <div id="currentTabUrl"></div>
  </body>
</html>


Again a simple HTML file but note it asks to load a popup.js javascript file.

  •  Go ahead create a file called popup.js and add following contents to it -

function getCurrentActiveTabUrl(callback) {

  var tabQueryInfo = {
    active: true,
    currentWindow: true
  };

  chrome.tabs.query(tabQueryInfo, function(tabs) {
    var currentTab = tabs[0];
    var url = currentTab.url;]
    console.log(url);
    console.assert(typeof url == 'string', 'currentTab.url should be a string');
    callback(url);
  });

}
  

function renderOutput(outputText) {
  document.getElementById('currentTabUrl').innerHTML = "<a href='" + outputText + "'>" + outputText + "</a>";
}

document.addEventListener('DOMContentLoaded', function() {
  getCurrentActiveTabUrl(function(url) {
        renderOutput(url);
  });
});



Take some time to see the javascript code above. It essentially reads the current active TAB url and shows it in the popup in an anchor tag. And there you go your first chrome plugin is all set to be deployed.

NOTE : Most of the chrome APIs are asynchronous. So you cannot do something like -

var currTabUrl;
chrome.tabs.query(queryInfo, function(tabs) {
  currTabUrl= tabs[0].url;
});
alert(currTabUrl); // Will show "undefined" as chrome.tabs.query is async.


Deploying your chrome plugin

Deploying your plugin is again quite simple
  • Go to chrome://extensions/ URL is your chrome browser. Here you should see list of existing chrome extensions you are using.
  • Make sure "Developer Mode" check box is selected.

  • Now click on "Load Unpacked Extension" and select the folder you have plugin in - "chrome_plugin" directory is this case.

  • Now open any tab. You should see the plugin with icon you had put in the directory just besides Omnibox. Go to any URL and then click on the plugin icon.  



 You can download this sample chrome plugin code from here.

Appending custom methods to chrome right click Menu

Lets see how we can add custom functions to right click menu. Here is what we are going to do -  we will add a new option on right click which enables to search selected text in google maps.


The new manifest.json file looks like the following - 

{
  "manifest_version": 2,

  "name": "Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",
  
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "activeTab",
   "contextMenus"
   ]
}

Notice couple of differences here
  1. There is a new permission added called contextMenus. This basically lets you operator om chrome context menus.
  2. There is a new key added called background that basically tells chrome about background processes. You can specify scripts or page here.
 Next in background.js add following code

function searchgooglemaps(info)
{
 var searchstring = info.selectionText;
 chrome.tabs.create({url: "http://maps.google.com/maps?q=" + searchstring})
}

chrome.contextMenus.create({title: "Search Google Maps", contexts:["selection"], onclick: searchgooglemaps});


 And you are done. Reload the extension.



When you click on "Search Google Maps" you should see a new Tab opening with google maps and a search location of your desired selected String.


Related Links

Thursday, 12 November 2015

Understanding p-namespace and c-namespace in Spring


Background

 In one of the previous post on Spring Dependency Injection we saw how beans are created. We also saw c namespace and how to use it.

  1. For values as dependency (like simple String) you can do <property name="brand" value="MRF"/> or <property name="bat" ref="myBat"/>
  2. Instead of using property tag you can also use p namespace - <bean id="cricket" class="Cricket" p:brand="MRF" p:bat-ref="myBat" />  (don't forget to add the namespace)
  3. Also note p namespace does not have any schema reference. 

Entire Spring configuration bean looks like -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="cricket" class="com.osfg.Cricket" p:brand="MRF" p:bat-ref="myBat" />

</beans>


In this post we will see what c name space is and how to use it.

Spring 3.1 Constructor Namespace  

As you already know by now you can do dependency injection by setters or by constructor - setter injection and constructor injection.

Let's see a simple  example of constructor based dependency injection.

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="cricket" class="com.osfg.Cricket">
    <constructor-arg value="MRF"/>
    <constructor-arg ref="myBat"/>
  </bean>

</beans>

NOTE : The <constructor-arg> tag could take type and index to reduce ambiguity, but not name.

You can simplify above xml using c namespace

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:c="http://www.springframework.org/schema/c"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="cricket" class="com.osfg.Cricket"
    c:brand="MRF"
    c:ref-bat="myBat"/>

</beans>

NOTE : Both the “p” ad “c” namespaces do not have a schema reference in the XML header.

Related Links

Wednesday, 11 November 2015

Using Handlers for async communication in Android

Background

In one of the previous posts we say how Android OS shows ANR(App not responding) if UI threads is blocked for more than 5 seconds. And to overcome this we used Async Tasks.

 In this post we will see how to use handlers which is another mechanism for asynchronous communication.

NOTE : Both handlers and async task internally use threads. So you can achieve the same functionality by pure java threading.

Using Handlers for async communication in Android

Here is what we are going to do. We are going to simulate a 6 seconds task. After that is completed we will send a message to the handler registered on the main thread and it will show a toast message showing task is completed.


To start with we have a simple layout with a button at the center that says "Start Process"

<RelativeLayout 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" tools:context=".MainActivity">

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Process"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Next lets get our handler ready.

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by athakur on 11/11/2015.
 */
public class MainActivityHandler extends Handler {

    public static int SHOW_PROCESS_FINISH_TOAST = 29;

    private Activity activity;
    private static final String TAG = MainActivityHandler.class.getSimpleName();

    public MainActivityHandler(Activity handlerActivity) {
        this.activity = handlerActivity;
    }

    @Override
    public void handleMessage(Message msg) {
        Log.d(TAG, "Received message : " + (msg == null ? null : msg.what));
        switch(msg.what) {
            case 29:
                Toast.makeText(activity,"Finished Processing Task",Toast.LENGTH_LONG).show();
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

This is just a class that extends handler and overrides handleMessage method. It then checks whether the message received is of type process completed show toast type. If so them simply show a toast message saying  "Finished Processing Task".

Now lets see this in action. Write your MainActivity as follows - 

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button myButton = (Button) findViewById(R.id.myButton);
        final Handler mainActivityHandler = new MainActivityHandler(this);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "Starting process");
                        try {
                            //simulate process for 6 seconds
                            Thread.sleep(6000);
                        } catch (InterruptedException e) {
                            Log.e(TAG,"Thread sleep interrupted",e);
                        }
                        Log.d(TAG, "Ending process. Sending Notification");
                        mainActivityHandler.sendEmptyMessage(MainActivityHandler.SHOW_PROCESS_FINISH_TOAST);
                    }
                }).start();
            }
        });
    }
}


 In the MainActivitys oncreate method we are getting reference of the button and on its onclick we are starting a new thread that does the processing for 6 seconds and then sends a message to the handler that it is done. We are also creating a new handler here.

NOTE1 : Handler is created on main thread or UI thread so it will have messages corresponding to UI threads message queue.

NOTE2 : You cal also post a runnable to be run on the thread to which handler belongs to.

Simply install the app on your phone or emulator and click on "Start Process" button. You should see the process completed toast after 6 seconds without any ANR.



So in a nutshell -

Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue



Realated Links

Saturday, 7 November 2015

Showing notification from you Android App

Background

Many time you must have seen apps send out notifications that you see in the title bar of your screen. For eg. when you receive a SMS or when your battery is low. Android provides mechanism for your app to send out such notifications. In this post we will see how to do it programmatically.


Showing notification from you Android App

Here is what we are going to do. We will simply create a button that when on click will show a notification and close the App. On click of that notification we will restart our App.

Before we write our Activity code create a simple layout with button at the center. To see more details on centering your layout refer -

PATH : NotificationDemo\app\src\main\res\layout\activity_main.xml

<RelativeLayout 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" tools:context=".MainActivity">

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Notification"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Next lets write our Activity class - 

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button myButton = (Button) findViewById(R.id.myButton);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, (int) System.currentTimeMillis(), intent, 0);

                Notification notification  = new Notification.Builder(MainActivity.this)
                        .setContentTitle("Test Notification")
                        .setContentText("You have received a notification from OSFG")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(pIntent)
                        .setAutoCancel(true)
                        .addAction(R.mipmap.ic_launcher, "Action1", pIntent)
                        .addAction(R.mipmap.ic_launcher, "Action2", pIntent).build();


                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                notificationManager.notify(0, notification);
                finish();
            }
        });
    }
}

Now lets test out our code. Install the App on your Android phone or VM and launch it. You should see following screen -



Now click on Show notification button. You should receive a notification in the title bar and your App should get close.




Now look at the code again and relate the subject title and actions we had set. Also notice that we are calling finish() on showing notification that will effectively terminate our main activity. Now click on the notification (or the actions in it). Our App should get launched again. You should see activity with show notification button again.

NOTE : You can call the cancel() for a specific notification ID from the NotificationManager. You can also do cancelAll() method that will essentially removes all of the notifications you had previously issued.

NOTE : You can also use NotificationCompat to get builder. You can use things like NotificationCompat.Builder#setLargeIcon(Bitmap) to allow you to take full advantage of Android 3.0+ with things like the large icon, while maintaining compatibility on versions of Android prior to 3.0 that do not support such thing.

What is this pending intent?

If you are still wondering what is this intent and how is it different than a normal intent then you are on right track. PendingIntent is executed by remote component (Like NotificationManager,alarm manager or other 3rd party applications) with the same permissions as that of the component that hands it over (The one that creates the notification).

 NOTE :  To perform a broadcast via a pending intent you can get a PendingIntent via the getBroadcast() method of the PendingIntent class and to perform an activity via a pending intent, you can get the activity via PendingIntent.getActivity() method.

Disabling notifications

Some apps provide settings in their App itself to turn off notifications. If setting is not provided you can also disable it from App info screen. For more details refer one of the earlier posts - 


Related Links

How To Add Google+ Follower Widget in your website or WordPress/Blogger blogs

Background

It been almost two and a half years since I am blogging on bloggers and I though it's time I see what wordpress has to offer. To surprise the UI is kind of complex and have limited widget support. Also it does not allow you to add plugins. After a few customizations I decided to add a Google+ followers widget but there unfortunately isn't one. Hence this post. It's a simple html/javascript. So you can plug it into any website. Bloggers as you know already has a widget for this.


How To Add Google+ Follower Widget in your blog/website

  • First create a simple text/html widget
  • Next add following javascript code to it
<div class="g-plus" data-action="followers" data-height="300" data-href="https://plus.google.com/102342595285863325267" data-source="blogger:blog:followers" data-width="320">
</div>
<script type="text/javascript">
      (function() {
        window.___gcfg = {'lang': 'en'};
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
      })();
    </script>


  • Next Save and Publish. You should now be able to see the widget on your wordpress site.
NOTE : Make sure you use your own G+ page URL as the value of data-href attribute in div tag.

You should see it get rendered as follows -


Sunday, 1 November 2015

Spring dependency injection using annotation based Autowiring

Background



In last post you would have seen what dependency injection is and how is it generally achieved in Spring. It is done using beans that you define in you xml file using tags bean , constructor-arg and property.

But as your project size grows it becomes difficult to keep adding bean in your XML files with its dependencies as the size of xml file continues to grow. So Spring has provided a feature called autowiring where bean dependencies are automatically injected based on various criteria like name, type etc (you can find all types in the previous post). Going a step forward Spring also provides annotations based injection in which case you don't event have to define beans. Spring will scan annotations and inject dependencies on it's own Ofcourse there are rules by which this is governed. We will see this autowiring feature in this post with and without annotations.

Lets continue with the Cricket example we saw in Last post.

Models

Lets rewrite our model classes - 

Bat.java

package models;



public class Bat {    

    private String name;

    public Bat() {}

    

    public Bat(String name) {
        this.name= name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    
    public void play() {
        System.out.println("Bat is swung");
    }

}


Ball.java

package models;

public class Ball {
    

    private String name;


    public Ball() {} 
    

    public Ball(String name) {
        this.name= name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    

    public void play() {
        System.out.println("Ball is bowled");
    }

}

And finally Cricket.java

package models;



public class Cricket {

    private Bat bat;
    private Ball ball;

    public Bat getBat() {
        return bat;
    }

    public void setBat(Bat bat) {
        this.bat = bat;
    }

    public Ball getBall() {
        return ball;]
    }

    public void setBall(Ball ball) {
        this.ball = ball;
    }

    

    public void play() {
        ball.play();
        bat.play();
    }

    

}

now lets configure Spring for these models. 

Spring configuration

Under src folder create a file called beans.xml and add following beans to it

beans.xml

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    

   <bean id="bat" class="models.Bat" />
   <bean id="ball" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" autowire="byType"/>

</beans>

Note :  Notice the attribute autowire of tag bean which is set to byType. This means Cricket has dependency on Bat instance so find a bean of type Bat and inject into cricket. You can also set it as byName in which case it will match bean name and inject dependency, However be careful in using this - if spring finds two beans of type Bat it will throw exception.

Now lets run this setup

Main.java

import models.Cricket;



import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {

    
    public static void main(String args[]) {
       
        ApplicationContext context =  new ClassPathXmlApplicationContext("beans.xml");
        Cricket cricket = (Cricket) context.getBean("cricket");
        cricket.play();
    }
    
}
Output :
Ball is bowled
Bat is swung
Now lets see the same thing with annotations.

Note : Note that spring first created beans that are dependencies and then injects in into objects that need them. Also all beans by default are singleton.

Spring dependency injection using annotation based Autowiring

Changes needed
  1. In your beans.xml file remove autowire="byType" from the cricket tag.
  2. In your Cricket class use @Autowired annotation over your Bat and Ball instance variables.
 beans.xml

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>
    
   <bean id="bat" class="models.Bat" />
   <bean id="ball" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" />

</beans>


Cricket.java

public class Cricket {
    
    @Autowired
    private Bat bat;
    @Autowired
    private Ball ball;
    //more code 
} 



Now run the same program as above and you should again get the same output. Few point to note -
  1.  Using @Autowired annotation is same as saying find the bean by type.If Spring finds no bean of injected type for auto-wiring, then it will throw NoSuchBeanDef Exception. If you think that this dependency is not a must than you can use @Autowired(required=false).
  2. As mentioned before @Autowired annotation is similar to autowiting by type. If there are two beans of same type you land in trouble. In such cases you can use resolve by name. For this you can use @Qualifier(value="beanName")
  3. Combination of using @Autowired(required=false) with @Qualifier(value="beanName") is very flexible as you can use this to specify you dependency is not a mandate and you can also specify bean name to resolve with.

To use Qualifier annotation Change your beans.xml as follows

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>

    
   <bean id="myBat" class="models.Bat" />
   <bean id="myBall" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" />

</beans>


and your cricket class as follows

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Cricket {

    
    @Autowired(required=false)
    @Qualifier(value="myBat") 
    private Bat bat

    @Autowired(required=false)
    @Qualifier(value="myBall") 
    private Ball ball;

     //more code 

}


and run the Main class again you should see same result.


Note : If you want to resolve by name then you can use @Resource annotation. Sample usage would be @Resource(name="myBat") . But note here that you loose the flexibility of marking it as non mandatory as you did with @Autowired annotation. All dependencies become mandatory.


Change the Cricket class as

public class Cricket {
    

    @Resource(name="myBat") 
    private Bat bat;

    @Resource(name="myBall") 
    private Ball ball;
   
    //More code
} 



and rerun Main methods. You should see same output.


Related Links

t> UA-39527780-1 back to top