Saturday, February 25, 2017

Quick connect to nearby connect

This was the day when we were collecting food money anything which can be donated to the flood victims for Chennai. By evening we got everything in the evening we already had enough money and food supplies to be sent to Chennai.. We wanted a Truck ! It was difficult to find one .. We put it on our whatsapp group but we were mostly software engineers and none of us had a truck owner's or truck driver's phone number . Few we had which were either booked or out of station. At that time I thought of this app where we can just post and search our requirement with nearby people and get help from. Who knows at the same time hundreds of truck may be going just crossing us towards Chennai. Anyway after two hours of wait and search finally we got one Truck and we could send stuff to Chennai.

Back home I started my research experimented on the available technologies, wrote few successful proof of concept app with redis, mongo and vertx-java. Then I came up with this idea of integrating nearby technology with a social network touch to make it very generic. It took me great deal of experiment to come up with a user friendly UX. Finally I am done and it's here as you see. It took me long and by the time lot of easier technology like firebase to build such servers have come up but i sticked to my design and technology as I feel it's more configurable.

Ok let me explain a little bit about this app and it's usage .

When we get any useful information of interest from someone unknown through any medium, We tend to ask WHO are you ? WHAT is this ? WHERE is this ? WHEN is this ? HOW much it cost ? etc etc . And if it's exciting and useful we try to help or visit or avail if it is NEARBY. Take few example say 1) A new Ice Cream shop which has opened just near your office and now that the owner wants to tell this to the nearby people, how would he tell all this in short and sweet manner ? 2) You went to a theater to watch a movie but unfortunately you had to leave it for some urgent work how would you sell ticket ? 3) You want to invite people nearby for free health camp . 4) Do carpool and let others know that you are giving free rides till your office. 5) You are going for a office party and you are in short of few people to avail a corporate discount. How will you find interested people from your office who may like to join and avail the offer ?

Take this another case where and how Quikc can help - NGO/College students want to drive the Nearby community for a weekend cleaning drive. They can create a post and publish it with Quikc with channel say #CleanSunday . Now the same message goes to every device who would be using this app and they can join and help. Also college students can use this app to invite unknown nearby interested students and do get-togethers for any such events.

Another case let's say you need an electrician so you would ask nearby people usually to get his contact and then you call him, but what if he is farther he may not be available in-time.. Instead of wandering you can post the same message with #Quikc with a channel name say #NeedElectrician and someone nearby you may be an electrician or know fixing things who would be of your help.

Quikc solves all these problems in a simple and user friendly way by an android app. Just post a message create a channel and push the message to nearby people and that's it you are done. Try this app from google play share your feedback, suggestions and feel free to write me back if you want to say hello.

Friday, April 8, 2016

How to Facebook or Google or G+ login in android and fetch user profile

While working on an idea of my new app I had this requirement of allowing users to use there Facebook or Google account. Facebook auth was easy and without any difficulty I could get the users profile info etc. But Google Auth + GPlus data fetching was a pain as they both involve different api strategy and I started working on it but I was stuck for days ! Unfortunately any example I found in internet for Google Auth + GPlus data fetching is either obsolete or doesnt work ! Even googles developer page is also not updated with correct functions.
It was quite impossible to get both data in one api call ! I then cracked it with the below minor changes to my existing code. Hope it helps to any android enthusiatic.

It was quite impossible to get both data in one api call ! I then cracked it with the below minor changes to my existing code. Hope it helps to any android enthusiatic.
Fetch G+ data with GoogleSignin
A slight modification to GoogleSignInClient can fetchus both Google account + GPlus data
Create the GoogleSignInOptions as below
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestScopes(new Scope(Scopes.PLUS_LOGIN))
                .build();
Create the GoogleApiClient as below
m_GoogleApiClient = new GoogleApiClient.Builder(m_activity)
                .enableAutoManage(m_activity, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addApi(Plus.API)
                .build();
public void fetchConnectedProfileInfo()
{
    Log.d(TAG, "fetchConnectedProfileInfo");
    if (m_GoogleApiClient.hasConnectedApi(Plus.API)) {
        Plus.PeopleApi.load(m_GoogleApiClient, "me").setResultCallback(this);
    }
}
Call fetchConnectedProfileInfo() from MainActivity.java onActivityResult()

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    getCallbackManager().onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            GoogleSignInAccount acct = result.getSignInAccount();
            Bundle googleData = m_gAuthProcessor.getGoogleAccData(acct);
           fetchConnectedProfileInfo();
        } else {
            notifyus("googleAuthFailed", null);
            // Signed out, show unauthentic
        }
    }
}
Code is available here https://github.com/sandipsahoo2k2/social-login

Sunday, March 27, 2016

creating a mobile site with users status | realtime apps

we would be using digital ocean for this

https://www.digitalocean.com/community/articles/initial-server-setup-with-ubuntu-12-04
https://www.digitalocean.com/community/articles/how-to-set-up-a-host-name-with-digitalocean
https://www.digitalocean.com/community/articles/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu

https://www.digitalocean.com/community/articles/how-to-set-up-multiple-wordpress-sites-on-a-single-ubuntu-vps

install npm and nodejs in digital ocean
create a soft link for nodejs

ln -s  /usr/bin/nodejs  /usr/bin/node other wise you wont be able to install redis/hiredis with node module.
-I/usr/include/x86_64-linux-gnu if make fails for redis compilation

Great Tutorial
http://www.smartjava.org/content/create-simpe-restful-service-vertx-20-rxjava-and-mongodb
http://www.javaworld.com/article/2078838/mobile-java/open-source-java-projects-vert-x.html?null


android examples
-----------------
http://javapapers.com/android/android-chat-with-google-gcm-xmpp/
http://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat-app-part-3/
http://code.tutsplus.com/tutorials/quick-tip-add-facebook-login-to-your-android-app--cms-23837


Saturday, November 15, 2014

Why I couldn't do what an UXD proposed me to do in my android app

Don’t shoot a programmer, He draws as he can..

Things to keep in mind with UI Assets.. 

Scale and Size of Image and Icons. For every icon/image that we would use strictly follow android UI guidelines so we need 5 size for icons with 2:3:4:6:8 scaling ratio. This means the baseline (MDPI) asset is 48x48 px, and the high-density(HDPI) asset should be 1.5x the baseline at 72x72 px, and the x-high density (XHDPI) asset should be 2x the baseline at 96x96 px, and so on.


So we must create icons/image with above scalling. The easiest thing for a developer to use http://romannurik.github.io/AndroidAssetStudio/  link.
Howto’s : If we have the highest density and scaled image we can easily create assets with the above link for Luncher/Action bar/Notification/Generic Icons. This tool will create all necessary set of icons for all device size. Note : Create an  image/icon with highest density/scale with GIMP or adobe illustartor first then use them as the input for the above tools.
Some Take away :

Splash Screen  – I couldn’t implement it cause the screen-shot that the UXD gave me was not covering the phone width, it was little ugly when I tried to stretch and I didn’t have screen shot for the Icons that I had created with a replacement for the icons shared by him, for the helper views too. So skipped for this release (I liked the proposal, if not today some day I will incorporate with the app)

SearchWidget – I am using the default android search widget in which the search_icon comes in the left side I tried a lot, did some search but could not make it possible to keep it in right side. (I could have achieved with my customized search widget which would take me few days to build !, Why ? if I make my customized control again that should follow android UI specifications which would need me to create controls for every device size, everycolor, 9 patch image, icons- which would be cost me around a week of time, its lack of time that forced me to keep it still hidden and pops up from a menu click).

Location Icons – Customized location Icons again has to be for different device density. And the location icon given to me was eye catchy though I had to use the default map icons. Icons were left anchored but my requirement was for centered gravity.

Theme with the app color : It took me a few days to find out the best theme color that suit my app. I did a lot of experiement with themes. There are still some controls, for which its hard to create theme specific controls e.g android switch !  So I am still living with the default android theme controls.

Refer : The links that I refer while creating my icons for my app / webpages.

Geo-Pulse list icons – Again the asset that he shared was awesome but I couldn’t generate icons using http://romannurik.github.io/AndroidAssetStudio/icons-generic.html link. We must generate all icons with the android studio as it ensures that we have the right size and scaled icons. But remember any given icon by a designer should be with the highest size i.e  192px/192px (if not minm should be atlest 96px / 96px) so that you can create smaller and bigger icons wihtout loosing the quality. The most important thing is any icon given by a designer should be transparent in nature without which you cant create icon for different devices using the above links. So I had to create my own icons with cliparts that collected from web which are holo and tranparent and matched the UXD’s proposals.

Luncher Icon :Luncher icon should be created from a 512px / 512px Image without which you will loose the quality again  for different devices. Just a small note, all the assets name should be in small letters and underscores (no hiphens) .


This is just for book keeping of all that I did for ZPulse which might help for an enthusiastic android programmer and ease him for beautification for his/her app.

Saturday, October 4, 2014

How to set events on EditTextPreference dialog like longpress

Spent a lot on working on the preferences settings in android google also couldn't help me at last I could do some experiement and made it work.

Goal : Open the Contacts and fill the phone number in one of the inputs for Preferences.

e.g You want to set the Number only Edit text

public class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences_activity);
        
        Preference preference = findPreference("EMERGENCY_PH_NO") ;
        EditTextPreference editTextPreference = (EditTextPreference) preference;
    }
}

now its easy just grab the handle and set the longpress event

All the code is given below

public class SettingsFragment extends PreferenceFragment {

EditText m_emergency_number = null;
final int EMERGENCY_CONTACT_PICK = 1337;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences_activity);
        
        Preference preference = findPreference("EMERGENCY_PH_NO") ;
        EditTextPreference editTextPreference = (EditTextPreference) preference;
        //TextView TextView = (TextView) editTextPreference.getEditText();
        m_emergency_number = (EditText) editTextPreference.getEditText();    
        m_emergency_number.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
openContact(EMERGENCY_CONTACT_PICK);
return true;
}
});
    }    
    
    void openContact(int who)
{
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
        startActivityForResult(intent, who);
}
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent aData) {
    // TODO Auto-generated method stub
    if (resultCode == Activity.RESULT_OK) 
    {
       Uri contactUri = aData.getData();
       //Intent intent = new Intent(Intent.ACTION_GET_CONTENT,contactData);
           //startActivityForResult(intent, 1336);
       String[] projection = {Phone.NUMBER};
       
       Cursor cursor = getActivity().getContentResolver().query(contactUri, projection, null, null, null);
            cursor.moveToFirst();

               // Retrieve the phone number from the NUMBER column
               int column = cursor.getColumnIndex(Phone.NUMBER);
               String number = cursor.getString(column);
               if(EMERGENCY_CONTACT_PICK == requestCode)
               {
                m_emergency_number.setText(number);
               }
    }
    }
}

Wednesday, September 24, 2014

android layout tricks

Merging a image with map

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

          <RelativeLayout
    android:id="@+id/rl"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <ImageButton
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:
        android:src="@drawable/star" />

</RelativeLayout>
</merge>

Actionbar theming
-------------------------
http://jgilfelt.github.io/android-actionbarstylegenerator/#name=example&compat=sherlock&theme=light&actionbarstyle=transparent&texture=0&hairline=0&neutralPressed=1&backColor=E4E4E4%2C100&secondaryColor=D6D6D6%2C100&tabColor=9c0%2C100&tertiaryColor=690%2C100&accentColor=6ad869%2C100&cabBackColor=FFFFFF%2C100&cabHighlightColor=33B5E5%2C100

Sunday, September 21, 2014

All about signing the apk and its effect in google play

  1. Generate a private key using keytool. For example:
    $ keytool -genkey -v -keystore my-release-key.keystore-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
    This example prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore. The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app.
  2. Compile your app in release mode to obtain an unsigned APK.
  3. Stand on google_play_services first then run below commands
    android update lib-project --path .
    ant clean
    ant release

    stand on your project root folder
    android update lib-project --path .
    ant clean
    ant release

    make sure your project file is updated with
    android.library.reference.2=../../Android/sdk/extras/google/google_play_services/libproject/google-play-services_lib
  4. Sign your app with your private key using jarsigner:
  5. $ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1-keystore my-release-key.keystore my_application.apk alias_name
    This example prompts you for passwords for the keystore and key. It then modifies the APK in-place to sign it. Note that you can sign an APK multiple times with different keys.
  6. Verify that your APK is signed. For example:
    $ jarsigner -verify -verbose -certs my_application.apk
  7. Align the final APK package using zipalign.
    $ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk
    zipalign ensures that all uncompressed data starts with a particular byte alignment relative to the start of the file, which reduces the amount of RAM consumed by an app
  8. How to check your details in the keystore 
  9. keytool -list -keystore .keystore
  10. keytool -list -keystore .keystore -alias foo
    1. List all info ::
    keytool -list -v -keystore android-release-key.keystore
How to find that debug SHA1 ley to be used by Android MAP key

keytool -list -v -keystore C:\Users\<username>\.android\debug.keystore
password : android

keytool -exportcert -alias androiddebugkey -keystore C:\Users\ssaho3\.android\debug.keystore -list -v

Friday, September 19, 2014

websites building references

http://www.layoutit.com/
https://bootstrapbay.com/blog/bootstrap-editors/
https://css-tricks.com/perfect-full-page-background-image/
http://nicolasgallagher.com/css-background-image-hacks/
http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-columns-of-same-height
Ready made themes
---------------------------
http://premium.wpmudev.org/blog/30-top-quality-free-minimalist-and-stunning-wordpress-themes/
http://www.wpexplorer.com/pytheas-free-wordpress-theme/
https://wordpress.org/themes/tags/one-column
http://theme.wordpress.com/themes/features/one-column/
http://www.wpexplorer.com/pytheas-free-wordpress-theme/
http://speckyboy.com/2014/05/27/free-bootstrap-3-templates/
http://speckyboy.com/2014/12/08/jquery-plugins-2014/
http://plugins.adchsm.me/slidebars/index.php#download

Plugins
------------
http://tutorialzine.com/2013/04/50-amazing-jquery-plugins/
https://css-tricks.com/text-blocks-over-image/
http://nick-jonas.github.io/windows/
http://joelb.me/scrollpath/
http://www.seanmccambridge.com/tubular/
http://buildinternet.com/project/supersized/download.html
http://vegas.jaysalvat.com/
http://tutorialzine.com/2012/06/quick-tip-fullscreen-backgrounds/

Web Color theme and pallet choosers
------------------------------
http://www.colorzilla.com/
kuler.adobe.com
http://paletton.com
http://www.google.com/design/spec/style/color.html#color-ui-color-application
http://pixabay.com/en/
http://apps.pixlr.com/editor/

Logo : 250/100 px
http://ocpsoft.org/tutorials/regular-expressions/java-visual-regex-tester/
http://ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-1/
http://www.mobyaffiliates.com/blog/how-to-promote-your-ios-and-android-mobile-apps/

For android
-------------
http://romannurik.github.io/AndroidAssetStudio/index.html
http://jgilfelt.github.io/android-actionbarstylegenerator/
http://android-holo-colors.com/
https://developer.android.com/distribute/tools/promote/device-art.html
http://www.norio.be/android-feature-graphic-generator/
http://www.cs.dartmouth.edu/~campbell/cs65/lecture24/lecture24.html

Theming a searchview's autocomplete is tricky as it looks black !! from Theme.Holo.Light.DarkActionBar
This is what you need to do

<!-- this style is only referenced in a Light.DarkActionBar based theme -->
    <style name="Theme.Zpulse.Widget" parent="@android:style/Theme.Holo">
        <item name="android:popupMenuStyle">@style/PopupMenu.Zpulse</item>
        <item name="android:dropDownListViewStyle">@style/DropDownListView.Zpulse</item>
        <item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextViewAppTheme</item>
    </style>

 <style name="AutoCompleteTextViewAppTheme" parent="android:Widget.Holo.Light.AutoCompleteTextView">
      <item name="android:dropDownSelector">@drawable/apptheme_list_selector_holo_light</item>
   <item name="android:background">@drawable/apptheme_edit_text_holo_light</item>
  </style>

Promote:
On launch date, you can also consider submitting your press release to sites like PRWeb  There’s no shortage of Press Release submission websites but definitely go for quality, not quantity.
http://www.rahuljiresal.com/2014/02/user-location-on-android/

LogoDesign
--------------
http://www.logogarden.com/

Saturday, September 6, 2014

Integrating php-mailgun for auth user

Follow : https://github.com/mailgun/mailgun-php


Install curl php as below
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
restrat the apache server.
sudo service apache2 restart



Github Most frequent command

git push origin master
git tag -a v1.4 -m 'my version 1.4'
git push origin --tags

Go back to last version
git reset --hard HEAD

Thursday, July 3, 2014

Compatibility chart for java script libaries

BackBone

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>

Sunday, June 15, 2014

How to read phonebook with phonegap from android

                function queryPhoneBook()
                {
// find all contacts field
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var fields = ["name", "phoneNumbers"];
navigator.contacts.find(fields, onSuccess, onError, options);
                }

                function onSuccess(contacts) {
                //navigator.notification.alert(contacts.length);
                var j = 0;
                $.mobile.showPageLoadingMsg(true);
                //$("#userList").html('');
                for(var i=0; i < contacts.length ; i++)
                {
if( contacts[i].phoneNumbers == null )
continue;
                if(contacts[i].phoneNumbers.length > 0)
                {
                //navigator.notification.alert(contacts[i]);
                //var temp = contacts[i].displayName + "" + contacts[i].phoneNumbers[0].value;
        //navigator.notification.alert(temp);

var htmlData = '<li id="'+j+'"><a href="#"><h2>'+contacts[i].displayName+'</h2><p class="ui-li-aside">'+contacts[i].phoneNumbers[0].value+'</p></a></li>';
$("#userList").append(htmlData).listview('refresh');
j++;
        }
        }
        $.mobile.changePage($("#index"), { transition : "slide"});
$.mobile.hidePageLoadingMsg();
}

Thursday, June 5, 2014

Playing with digital Ocean

amazon ec2 seemed to be complecated though not so difficlut but I am trying didgital ocean now for all my home based research here is what i did today to setup a new instance of droplet and installed Lamp


passwd
adduser sandeep

visudo

# User privilege specification
root    ALL=(ALL:ALL) ALL
demo    ALL=(ALL:ALL) ALL

nano /etc/ssh/sshd_config
Port 4444

PermitRootLogin no
AllowUsers sandeep

sudo apt-get update
sudo apt-get install apache2

sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
sudo mysql_install_db
sudo /usr/bin/mysql_secure_installation

sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt

sudo nano /etc/apache2/mods-enabled/dir.conf 
change index.php

https://www.digitalocean.com/community/tutorials/how-to-set-up-multiple-wordpress-sites-using-multisite

Get the Mysql password

tail -1 /root/.my.cnf | awk -F'=' '{print $2}'
Setting Up Java

sudo apt-get install default-jre
sudo apt-get install default-jdk
sudo nano /etc/environment and append this line
JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
source /etc/environment
echo $JAVA_HOME

Installing SFTP/ProFtp

sudo apt-get update && sudo apt-get install proftpd
apt-get install openbsd-inetd
lrwxrwxrwx   1 root root    16 Sep 23 15:34 openlibs -> /opt/GLOBAL/libs
lrwxrwxrwx   1 root root    20 Sep 23 15:34 openservices -> /opt/GLOBAL/services


00 12 * * sat /home/root/monitoring/config/start/procmon.sh
00 12 * * sat /home/root/monitoring/config/stop/procmon.sh

CLASSPATH="/usr/java/bin:/home/s_gcm/gcmserver:/home/s_gcm/gcmserver/libs"
https://www.digitalocean.com/community/tutorials/how-to-configure-proftpd-to-use-sftp-instead-of-ftp
Setting up Smack library in Ubuntu
wget http://www.java2s.com/Code/JarDownload/xmlpull/xmlpull-xpp3-1.1.4c.jar.zip
http://www.java2s.com/Code/JarDownload/xmlpull/xmlpull-xpp3-1.1.4c.jar.zip
Setting up two domain names with DO
https://www.digitalocean.com/community/tutorials/how-to-set-up-multiple-wordpress-sites-on-a-single-ubuntu-vps

Setting up a subdomain e.g <blog> in this case


Lets say subdomain name is blog on zoogaru.com



sudo mkdir -p /var/www/blog.zoogaru.com/public_html
sudo chown -R www-data:www-data /var/www/blog.zoogaru.com/public_html
sudo chmod -R 755 /var/www

put all content with an index file at 
/var/www/blog.zoogaru.com/public_html/

cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/blog.zoogaru.com.conf
vi /etc/apache2/sites-available/blog.zoogaru.com.conf

update ServerAdmin blog@zoogaru.com
add ServerName blog.zoogaru.com
update DocumentRoot /var/www/blog.zoogaru.com/public_html

last and final step:
sudo a2ensite blog.zoogaru.com
sudo service restart apache2
or
/etc/init.d/apache2 restart

create a CNAME record in your owned domain as
* => @ 
give 20-30 minutes to zone file to be propagated.

Using filters on JSON
$scope.selectedTransporter = $filter('filter')($rootScope.CACHE['TRANSPORTER'], $scope.record.transporter_id);

phpmyadmin upgrade =>

sudo add-apt-repository ppa:nijel/phpmyadmin;
sudo apt-get update;
sudo apt-get install phpmyadmin;

Sunday, February 23, 2014

Integrating Google ads for mobile into an android app

makesure you have ant debug/release runs well with your application root folder with google-play-services-lib and you have creted the adUnitID for Banners/InterstitialAd with an account for your android app to monitize (to show google ads in your app and make money)

Now in your application main file the class which is the etry point of your Activity or which extends CordovaACtivity you should (not necessarily true always) implement the Banners/InterstitialAd.

How to implement Banners


import the following packages

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

declare variables to hold the objects

private static final String AdMob_banner_Ad_Unit = "GOOGLE_ADMOB_BANNER_ID";
private AdView m_adView; 

in  public void onCreate(Bundle savedInstanceState) function 
write the below code

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
                
        // Set by <content src="index.html" /> in config.xml
        super.loadUrl(Config.getStartUrl());
        //super.loadUrl("file:///android_asset/www/index.html")
        
        m_adView = new AdView(this);
        m_adView.setAdUnitId(AdMob_banner_Ad_Unit);
        m_adView.setAdSize(AdSize.BANNER);
         
        LinearLayout layout = super.root;
        layout.addView(m_adView); 
        AdRequest request1 = new AdRequest.Builder().build();
        m_adView.loadAd(request1);
}

also update the other override methods as

    @Override
    public void onPause() {
    m_adView.pause();
      super.onPause();
    }

    @Override
    public void onResume() {
      super.onResume();
      m_adView.resume();
    }

    @Override
    public void onDestroy() {
    m_adView.destroy();
      super.onDestroy();
    }


To Implement InterstitialAd

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

declare variables to hold the objects

private InterstitialAd m_interstitial;
private static final String AdMob_interstitial_Ad_Unit = "GOOGLE_ADDMOB_INTERSTITIAL_UNIT_ID";

in  public void onCreate(Bundle savedInstanceState) function 
write the below code

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
        super.loadUrl(Config.getStartUrl());
        
        // Create the interstitial.
        m_interstitial = new InterstitialAd(this);
        m_interstitial.setAdUnitId(AdMob_interstitial_Ad_Unit);
        
        m_interstitial.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                //super.onAdLoaded();
                displayInterstitial();
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                //super.onAdFailedToLoad(errorCode);
            }
        });

     // Create ad request.
        AdRequest adRequest2 = new AdRequest.Builder()
        .build();

        // Begin loading your interstitial.
        m_interstitial.loadAd(adRequest2);         
}

 // Invoke displayInterstitial() when you are ready to display an interstitial.
    public void displayInterstitial() {
      if (m_interstitial.isLoaded()) {
     m_interstitial.show();
      }
    }

integrating google_play_service with phone gap android application

It was even very painful foe me while integrating the Google Admobs which requires google_play_services to be integrated ! here is my share of tricks how I solved the play services Build problem.

When you try to publish an app you have to create a release build for which either you have to create release build with below command

  • ant release
  • cordova build --release

If you have not built anytime the play service with ant
You get the following error !

D:\workspace\HTML5\Wordizy>ant debug/release
Buildfile: build.xml does not exist!
Build failed

to fix this (ant must have been setup)
copy the whole google-play-services_lib folder from ANDROID_SDK_PATH\extras\google\google_play_services\libproject\to your project root directory.
copy
build.xml
local.properties
project.properties
files from root folder/Cordova lib folder to google-play-services_lib folder

Change the project.properties file's project target to the right target (very important)

split.density=false
# Project target.
target=android-19 (important)
android.library=true

change android.library.reference.2=google-play-services_lib in your root/project project.properties file

Stand on the google-play-services-lib and in the cmd editor supply
android update project -p . (dot=current folder) you should not be getting any error
then supply the command
ant debug success
ant release success

Now you are done !

You can also call cordova build --release command at the root folder of the application and it should create a unsigned-release.apk file.