Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Friday, 14 October 2016

Getting Started with Android Wearable App Development - Basics

The wearable device is really useful where you need to check updates on the go without unlocking your phone and swiping the notification at regular interval. But one may claim that it's too much to have a wearable and getting notifications instead checking your phone. The design and way it syncs with your handheld device are awesome and even more awesome when apps respond you based on contexts like location, temperature and other conditions.

Getting Started with Android Wearable App Development - Basics

Scope :

Android wearable application development is really a broad topic where as it's growing drastically. Even now recently Google announced inbuilt android play store, the keyboard for wearable and last year they introduced emoji and WiFi support for wearable apps. we will see about basics of Android wearable development and types to support existing apps.

Prerequisites : 

1) Knowledge on Basics of Android development

Design for wearable API :

Wearable is meant for checking updates on the go and quick replies. It's not same as your handheld device to show all available information to the user. It must be optimised to show the relevant and Updated data to the user in regular intervals.

For example : consider the Weather app, which shows you weather details for next seven days in single activity and it's data structure will be like 
  • Min temperature
  • Max temperature
  • Type of weather condition ( cloudy, sunny, rainy or moderate )
  • Atmospheric Pressure details
But your wearable app doesn't need such amount of data to be displayed on that small screen. so choose wisely which is more relevant data for the user to adapt Round or square wearable devices. In my opinion what I'll choose is
  • Today's Min Temperature
  • Today's Max Temperature
  • Type of Weather condition as Drawable ( Bitmap )
with time and date.

So, It's important to focus more on design and relevant data to the end user based on context.

Getting Started with Android Wearable App Development - Basics

Types of Wearable Development 

Basically, whenever your app shows notification in your handheld device it will automatically push to the wearable device at no cost of coding it. But when you need to support it extensively with actions, paging additional information as slider you should support it via notification App compat support library.

1) Notifications App compat support library.
2) Watch Face design and Data communication and syncing.
3) Extensively designing UI and installing an app in wearable.

Notification App compat : 

Notification App compat is all about extending support for existing notification in wearable devices without writing additional code for wearable. with notification app compat library you can simply create a notification for your device and wearable devices with additional options such as Actions, Quick reply intents etc.

Watch Face Design : 

Basically, watch face is nothing but just like your home screen with widgets but it can run only one app at a time, showing multiple data such as temperature, steps your while jogging, the heartbeat can be obtained through content providers or sensors. There are tonnes of watch face in play store. Watch face is considered as a home screen where you can check regular and frequent updates.

It has two modes namely ,

1) Ambient Mode
2) Normal Mode

In the Ambient mode, your watch tries to save battery by not allowing to update the screen frequently. you will get the chance to get updates in minutes basis. Most specifically your watch face should use Black and white pixel colour while in the Ambient mode to save energy by repainting the view now and then. you can't able to update second hand in the clock where it requires every second update.

In normal mode, you are allowed to use colours and drawable but that doesn't require high resource and frequent updates that make your watch face unresponsive sometimes.

When the user is using we can switch over to normal mode, where other times wearable will be going automatically to ambient mode after the speicific interval of time.( checked in Moto 360) 

Designing UI for wearable :

Designing extensively for Android wearable using layouts such box inset layout, grid view pager, Watch view stubs and a variety of layout is supported by support libraries. Data communication API, Message API is available with Wearable API that comes under google play services, which delivers and sync data between the handheld device and a wearable device.


So we just covered the basics of Android Wearable App development which is different from app development in terms of Design and types to support your app. I'll soon publish the post on these types to designing and work with these API for wearable apps.

Recently Google announced that Wearable major update 2.0 preview that doesn't require a phone to be connected always. you can use it wherever you go and sync via the cloud. we're eagerly waiting for stable SDK support and watch yet to be released early 2017. For now preview 2.0 is available at official Android developer site.

For bugs, hugs just comment below. in case any doubts drop me a mail, or chat wiht me in G+/ Facebook. share is care.

Friday, 7 October 2016

Facebook Account Kit Tutorial - Backend Verification using Node.js

Recently I have been developing secure production app using Facebook account kit for seamless authentication across mobile and web platform. Account kit is widely used in many apps such as Saavn and many other. I found that backend verification in Account kit for every request from mobile/ SPA should be handled manually by developers and no libraries available till date. so, I'm writing this post for Indie Game and mobile developers as a reference guide.

So what's Facebook Account kit all about ? 

It's seamless authentication method via OTP way to verify the user with Mobile Number and login into App without any passwords. Whereas it provides access token to verify the authenticated user in backend server without worrying about the access token generation, revocation logics. It's all about securing the access token and using it over HTTPS connection while connecting between your app and backend.

Facebook Account Kit Tutorial - Backend Verification using Node.js
Facebook Account Kit Tutorial - Backend Verification using Node.js

Prerequisites :

In this tutorial, we'll solely concentrate on Backend verification and authorising the legal request made by the apps.
  • Facebook Developer Account 
  • Good Knowledge on Node.js routeing
  • Rest API client
  • Good logical error handling skill

How Does Account Kit works ?

When the user signup using his mobile number, he would receive the OTP via SMS Carrier from facebook server. after authenticating OTP password, the account kit sdk gives you the long live Access token or Client side temporary exchange token(this depends on application).

  • With the received access token, securely post it your Mobile backend server (probably HTTPS to avoid man-in-the-middle attack)
  • with that access token you can call the Account Kit API end point to check that the access token is valid as well it provides you mobile number or E-mail
  • As response contains mobile number, you can identify the user and provide the user with the service appropriately.
  • Most important thing is you should pass the access token everytime from the client to the server in order to verify the authenticity of the user.

Getting Started :

You should have good knowledge in routeing technique since we are going to concentrate on Express.js, if you're beginner check out this link to learn more.

Concept :

Since we need to authenticate every request from the app that comes along with access token and others data we could write a middleware to authenticate the every request in the beginning before it executes the API code.

Middleware is nothing but a piece of code which is executed before each and every request entering our express routes. probably we need to write the Account kit verification code here and if it is a success we can make the request to propagate to the corresponding the function else just terminate the live request with authentication errors spitting.

Sample code : 

here is sample code to authenticate your mobile backend API end points. we use request module to send a get request to account kit server by providing the accesstoken in url param while if it responds with 200 status code, we are going to extract the mobile number else we are going to consider the request as failed on and informing to the client as error message. before trying this source code, in Facebook Developer dashboard turn off the App-secret required option and enable client access token flow.


That's it. this is base tutorial on verifying the backend for facebook account kit integrated development.
for any bugs/hugs comment below. For detailed source code and other information just comment below or mail me, chat with me in Google+ or facebook.share is care.

Wednesday, 31 August 2016

P1 Popular Movies App - Udacity Android Nanodegree Recap and Review

Recently, became Udacity project reviewer where I would be reviewing Android Nanodegree Basics Course student project works.so, Continuing exciting the Nanodegree journey with Udacity, the second project was building popular movies application.This was challenging one to build because we need to use the same source-code to build for the next upcoming project which concentrates on extending the user interface for tablets too.so,let's see what we learnt and implemented as project.
P1 Popular Movies App - Udacity Android Nanodegree Recap and Review
Project Repo : link 

Scope of this project :

To understand & implement themoviedb.org api and performing networking operations in AsyncTask (background thread) and updating UI(main) thread.

Process and Concepts :

The ultimate aim of this project is

  • Connect mobile app with Cloud
  • Performing Network operations in background thread
  • loading images from Internet and deciding optimised sizes for corresponding views.
  • Clear understanding with RecyclerView or ListView working
  • Intents to navigate between activities 
  • Concentrating more on SavedInstance State Bundle

Concepts demystified :

We'll look into the above mentioned concepts with few lines and reference links which i've used to learn while building the App.

Connect mobile app with Cloud :

The first thing about android app it should fetch data from cloud or API or server with updated details and making sure it works offline by caching it in Sqlite database or sharedpreferences.This Google I/O session is the best session ever made to understand the networking operations coding approach while you build your app for the next billion users coming over online.


Developer reference : link

Loading Images from internet :

One of the major nightmare of mobile developer is out of memory error in java,it means you have consumed the Heap memory in VM and having strong reference to the objects created.since, we have created strong reference to the object GC can't collect it to free the VM Heap memory.especially, when you're about to load Bitmap through JPEG image into the memory it's really nightmare for developers to manage the memory. 

So, here comes Jake Wharton to help us with his image loading library named as Picasso and it also supports cache,recycling the images,animations and effects.
there are few other libraries named Glide,Fresco from facebook.

Developer reference : link

Clear understanding of ListView & Recyclerview :

Listview & Recyclerview is useful view for developers from google engineers is to show large homogeneous data in our mobile device.Consider you have 1000's of contacts in your contacts app where you need to show them all on demand, you can't load all the contacts in to memory at once where you may lead to Out of Memory error very soon.
Obviously, some Algorithmic students may claim  that we could use binary search algorithm to view the contacts, but in real life is the user is going to type and search contacts every time ? That will be a bad User Experience.
so,how does the listview or recyclerview works ?
yes we've learnt in our concepts of operating system namely Paging concept.when the listview gets initialise it measures the height of the layout and decides the number of list to be shown in the view and loads the particular count of data from adapter to the view, it also prefetches few data set front and back to manage stagger less scrolling.it uses the same object and recycles for other data set and inflates the view into the Listview.Note that Recyclerview is enhanced version of Listview.

difference between Listview and Recyclerview - Stackoverflow Link

Developer Reference : link

What the Hell is savedInstanceState bundle ?

before understanding the saving the instance state of View in android, you must be aware of the lifecycle of android application such as onCreate, onStop, onResume, onPause and even more for handling orientation and configuration changes.one of the best video to understand why we need concentrate more on Activity lifecycle.


so, when the apps move foreground and background we need to save our current state of the app so that it, can be resumed when the user once again visits the application.we need to manage this smoothly without any lag while recovering the state of the application.

consider the scenario :

when you type important whatsapp message to your friends/crush, all of a sudden you receive phone call from someone continuing you get facebook message from friend after replying back you come back to  whatsapp what if whole message has been destroyed which you have typed already ? It hurts User Experience so,here comes savedinstance state to guarantee you to save some text/image/serializable object for you in background to recover you back when user renters the app.

so, by default activity lifecycle callbacks such as onCreate, onResume , OnPause,onConfigurationChanged passes you bundle to save the state of the current activity before the lifecycle event happens.

Most popular guide for fragments and activity : inthecheesefactoy guide for savedinstancestate

Developer Reference : link 

That's it.These were the main challenges I faced and learnt during the Project 2 Android Nanodegree.hope the above resource will be helpful to get started with Android development.

My Screencast of the Project :

Next Project Preview :

The next project was awesome, it's all about using the same source code to optimize the android app to work for Tablet user Interface consuming large amount of user space and handling the orientation changes.

for bugs,hugs and comments just comment below or mail me.Chat with me in G+/Facebook for help and improved version of this article.Share is care.

Friday, 8 July 2016

P0 Android Basics - Udacity Android Nanodegree Recap and Review

Udacity with Google has done excellent job in delivering standard and updated courses via Udacity android development courses with variety of categories such as Games,Beginners,Building App with Google API's and even more.They are also about to provide Associate Android Developer certificates by taking few test as projects over online as announced in Google I/O 2016.Me and My friends +venkat raman , Ajay are in track with Android Nanodegree course and projects.The course objective is to master basic Android concepts and adapt to future changes in design,coding style and updates.I'll try to reproduce the concept i learnt and applied during the project and passed reviews in this post.


Project Repo : Link

Process & Concepts :

The first project was just to build a mere Android app with specified layout,buttons and Onclick listeners implementations.(you can check my code).The goal was to ensure that users are able to work with Android studio and produce results from those by running it in emulator or phone.Luckily I have latest Android Smartphone with latest updates from Google.(6.0.1).

What I've Concentrated ?

  • Making my Java code readable one :D 
  • Concentrating on strings.xml file organising and not hard coding it.
    Though it was tough in beginning when you move forward and app grows in many countries and your user may expect in different languages,this technique will be scalable approach and managing it in one place.
  • writing reusable code in java - link
  • Few patient in testing in emulator,device.
Accomplishment of P0 - udacity android nanodegree





The next part was basics of Android such as components,form factors and do's and don't in the development process.with those installation and Android jargon such as Android API levels and Numbers,SDK levels,Compile version,Minimum and maximum SDK target levels and few more publishing techniques too.

Next Video Lectures :

The first section video consist of Android Studio tutorials,drag and drop widget tutorials and connecting the xml design file with java code and maintaining their lifecycle,connecting the app to the cloud with network code(http) and few views such ListView to handle huge amount of homogeneous data types.This leads to next level project as Popular Movies app by consuming themoviedb.org API to display popular movies running in nearby theatres.Mean while check out my Github repo and try practising it. 

Results : 

That's it and i've passed the project 0 with flying colours within a hour of starting the course :D with my friends +venkat raman and ajay.

Subscribe the blog for next upcoming recap and reviews.chat with me in G+/fb.for more discussion just leave a comment below.Thanks for reading.share is care.


Thursday, 2 June 2016

Top 100 motivational Quotes - MotiveTown - Motivational App

Recently Launched Mobile & web app based on concept of motivating others using inspiring pictures and quotes from various sources such as simpleremainders,spiritofscience & Motivational guides.combining all resource and categorizing the quotes and images,generated a unified format to form a web service.Additional to this we've optimized the Image using opensource tools such as Imagemagick and few shell scripts to automate the process.We named the App as MotiveTown - Motivational App So,let's see about the various features implemented in mobile app below.



Download From Playstore | Download from Amazon Store - Rate and review the app at playstore/amazonstore

Why this App ?

Everyone needs motivation in some point of life either letting-go or to chase their dream,this makes us to search to read books,quotes,inspiring videos,lectures even in soundcloud for audio speech.Some peoples watch movies,videos where others check out magazines,daily.And targeting this fragmented categories,we decided to bring unified platform with personalized newsfeed contents with videos,audio and quotes with images via simple Mobile App.Thus as a result we were able to publish first version of this app with limited contents of news,images and quotes and features.

Why Ads ? 

We need to provide you reliable backend service without outages and crash.so, we rented a economy server package and customized backend to adapt daily updates.we too optimized several hundred KB image files to less than 100 KB JPG compressed files with automated scripts and Imagemagick opensource tools.so,to keep running these operations smooth and more faster we adopted ads to generate some amount to maintain hosting.

Categories - MotiveTown App

We have Daily updated 23+ categories of Motivational quotes 
• Achieving Gratitude
• Daily Inspiration
• Business Leadership
• Changing the World
• Community Thoughts
• Conquer Negativity
• Walking in Faith
• Various Saying
• Uplifting Music
• Success Secrets
• Staying Motivated
• Relationship Dynamics
• Recover and Loss
• Positive Thinking
• Overcoming Fear
• New Awakenings
• Mindful Living
• Letting Go
• Law of Attraction
• Impact Media
• Healthy Living
• Forgiveness
• Exploring Thoughts
About 23+ categories and 3000+ images,quotes,articles and videos combined we're making a unified platform for everyone to engage and get the benefits out of it.Download the MotiveTown - Motivational App from Playstore.

App description :

MotiveTown App Provides various categories of motivational quotes,images and text poems.Motivation is the Key point for everyone and that can act as turning point in their life.Push them Ahead with spirit in their mind to succeed and compete with others.It also providesMotivational quotes for success in Tamil,English and even more supported languages.Start your day with motivational quotes everyday category to get some random quotes and you can customize your own news feed for Motivational Quotes for Daily inspiration.Share quotes,images directly with your friends from the motivational quotes by great persons.

Screenshots :

check it out in playstore : Link


To Become Beta tester,developing for other platforms,exposing API's and join with me for further development drop me a mail : s.shivasurya@gmail.com or chat with me in G+ hangouts/Facebook.Don't forget to rate the App in Playstore.

Saturday, 25 April 2015

App Invites For Android & iOS Apps - Facebook Friends To Mobile App

Recently I got a Notification from my Close friend in Facebook suggesting me to try a Android App.I too Eagerly clicked over that and installed from Google Play.
And the next day i was asking her how did you invite me via Facebook ? or just spammy Notification just like another Candy Crush Saga :D.Then she shown this page to me App-invites - Facebook Developers page.I was Wondering how could i invite From My App(Android) and checked out the Documentation  About the App invites and it was Quite confusing first,however after lot of Searching over Stackoverflow,reading the Documentation thrice i could build a Simple Invite System from My Android App to Invite and Suggest the App in Facebook to Engage to Download or to open the app.

App Invites For Android & iOS Apps -  Facebook Friends To Mobile App

Refernce : Download Code from GitHub 

A Drift from Web App to Mobile App : 

Once Upon a time i could remember working with implementing the invite system with Javascript with Facebook,and Now i consider this is as a Major Drift Change from web app to Mobile apps replacing it.This invite system can increase the User engagement to the user at higher levels,since you're personally inviting your friend,sweetheart :D to try those Apps.

Prerequisites : 

Here we're developing a Simple Android App that has invite button and directs to invite popup and invite our friends in facebook.
  • Android Studio With Recent SDK installed (Preferable for Dependency Adding).
  • Facebook Developer Account.
  • Register A Facebook App with Key Hash and Package Name.
  • Android Phone with facebook App Logined
  • Little patience to Debug the App via logcat.
  • A little Knowledge About Developing Android Apps and Java.
Before Writing this post,I have created a small App which made me many troubles such as App crashing,Low speed internet Connectivity(My Fate :D ) and Some Exceptions.here i will completely write my experience and exception and how i handled them.If anything apart from this let's discuss in Comments or over Email.

Creating Facebook Application - Developer console :

here we can discuss about creating Facebook App and obtaining APP ID and Secret keys for our app,and providing platform as Android,Adding key hash and package name.

  • visit here and Create new App - Link - Facebook Developers Console.
  • select the Platform As Android > and provide a Name for Your app corresponding to your android app.
  • Choose a Best category that fits your App(Most recommended by facebook to Rank your app).
  • Provide the package name to facebook and Launcher Activity too as java package name.(be cautious about package name or else it wont works :D)
  • Provide your necessary app info and move on to key hashes(will see it later how to add it)
  • At the top right of the Page click skip the Quick start and you will be redirected to App dashboard which you have created.
  • go to app > settings > provide a namespace for your app(mandatory)
  • Add contact email also and save it.
  • Now,at below add platform > select Web app and give your website address(if it available)
  • if you have website and added the platform then,Add your domain in Domain Field and Save the info.(Don't worry if you don't have any websites just skip to next step)
  • Get your APP ID and make your App live for production in status & review > toggle the button to enter in to Production mode.
  • And finally We need to Add Key hashes to our Facebook App console.(see below)

How to Generate Key Hash and Add to Developer Console :

just with your onCreate method add this code and replace with your package name correctly and run your app in Debug method(by Default it would be) and check your Logcat for the keyHash : XXXXXXXXXXXXX. Just copy it and visit your app in facebook Developer Account > Settings > in the Android Section (Which you have already created with package name) in the key Hash Field add it over and enable single-signon(may be useful for apps with login) and save the app settings.

Note : this is preferable method which i have created the key added to my Account.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"REPLACE WITH YOUR PACKAGE NAME HERE",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md
.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {

} catch (NoSuchAlgorithmException e) {

}

Android Studio Project and Facebook SDK Setup :

I just love Android Studio mainly because it automatically adds the dependency with one line in app gradle.However i'm not expert in Working of Gradle system! however i know how to use it projects to add dependency without any pain unlike Eclipse you have to Add it and point the locations and export while you're building it finally.
  • Open You Android Studio(i hope you have installed latest SDK and tools installed).
  • create new project with a Empty Blank Activity.
Now just open your app gradle file and add the entries to resolve the dependencies via maven repository.

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}
 and just sync your gradle or rebuild your project.

Note : Mainly this Dependency support from API 9 and above.just change minSDK as 9 and higher till Android API 22 or L (your choice).

Adding the Code : 

lets just first see about setting permissions and adding entries in Manifest file regarding Facebook SDK setup.
  • I have added a default activity to be launched and shown in launcher.
  • then added facebook activity (may be useful for apps used for login/share with facebook)
  • added meta-data content containing facebook app id as string from xml file.
    don't just hardcode your APP ID, it may create exceptions,it is recommended by facebook to use as String from xml string.
  • Finally add Permission for internet appropriately since we are doing network based operation in our app and facebook needs it. 
        

<uses-permission android:name="android.permission.INTERNET" />
<application ...>
<activity
android:name=".facebook"
android:icon="@mipmap/ic_launcher"
android:label="@string/title_activity_facebook" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

</intent-filter>


</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />

<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
</application>

So just use this example to add your manifest file,and check that you have added facebook activity in your manifest file too.

MainActivity - Activity to initiate App invites :

Here we are initializing the App with facebook library and set the view as XML layout and then simply add a link and preview image preferably a large image is recommended.
get your App links from facebook to launch the activity from facebook or web or some other apps.learn more about app links here in my previous article.
create App link from here
  • select the created facebook app for android
  • Select android platform and scroll down
  • in the Android section , Add your package name for launching the app if it is present in the particular device or else just as fallback it may be moving into playstore.
  • Enter your playstore package name(must be equivalent to your android app project package name)
  • If you have website just add it,check that you have app links in the head section of the website and the domain should be already added in the App> settings > domain(when web platform is enabled )
  • Create a new Applink and just copy it.
Just replace with your app link in the code given below,and chenge your imageurl too(must be high resolution image).
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

FacebookSdk.sdkInitialize(getApplicationContext());

setContentView(R.layout.activity_facebook);

String appLinkUrl, previewImageUrl;

appLinkUrl = "https://fb.me/493857950766025";
previewImageUrl = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFlJx_QbYwpbLkqo-tZkSl4waIjKo5IUbe0eM32WgGCX-poInzLWegKE9-0mGdUi5faoK3NCt4rjGYzZu4LObVeCOJZubSnRem1FdxqAKHwGWuDAqmb2Kglv9i3vzi_Pfx7csGgCnOvBlr/s1600/appscripts.png";

AppInviteContent content = new AppInviteContent.Builder()
.setApplinkUrl(appLinkUrl)
.setPreviewImageUrl(previewImageUrl)
.build();
AppInviteDialog.show(this, content);

}
Thus while Opening your app this will default invoke to app invite activity of facebook.
Here facebook verifies the user has installed however latest facebook app in device or else as fallback it opens as webview facebook.You must be logined in the facebook Native app or Webview already will be fine for testing.

Main Note:

This Invite Feature doesnt need any Login With Facebook Feature,This just Simply enables you to invite your friends when you're logined with facebook app.

Errors which i came across:

  • null pointer Exception for not Adding Facebook App ID in manifest file.
  • null pointer Exception for Hardcoding the APP ID in manifest File.
  • Facebook App canvas Error for not adding key hash mismatch.
  • Facebook App canvas Error for App in development mode(switch to Production mode)
  • Null pointer Exception for not initializing Facebook SDK before setcontentView method.
However if you didnt find any error if you come across,comment below lets discuss it and resolve and make this post more usable.

My Screenshot : 



For hugs/bugs/errors/help/suggestions just comment below or mail me to s.shivasurya@gmail.com or chat with me in Facebook/G+ or tweet me in twitter.Share is care.

Saturday, 21 February 2015

App Indexing API For Google Search - Mobile Application Development

Mobile Computing and Mobile Application Development is the Future,made me to think that Mobile apps and computing,optimization is going to be the next big thing on Earth.As i have experienced Android development as well As Web Development i could correlate the things like Google Search, Mobile Views and so on.As every one knew Mobile apps search are comparatively different from Desktop search,Where we could directly visit the Websites and make purchase and move on.But, in the case of Mobile it is going to be however hurting experience for both users and Developers to maintain and interact with Webview in Smartphones.So,Google came up with Solution to show and index apps on Google search on Signed in Browser for Android and show relevant apps that can be view with Mobile apps.

So,if it is site we could submit the sitemaps to Google Bots and Crawl our contents for indexing,but in case of apps... so,here comes Indexing API to index your app contents and correlate the contents with web and mobile and Show suggestions on Google Mobile Search app.





Prerequisites :  

   Download : Code at GitHub 

We are just going to Create some content in app and try to show in Google Suggestion using Relevant Keywords.We will deal without web url in this post.
  • Android Phone with Play Account
  • Android Studio (Preferable because of Gradles )
  • Some Patience :D and Simple App to test it out.

Procedure :

As i don't write android app tuts here,Just Start Creating Simple App with main activity with some contents and title with relevant key title.You can refer the Source code from my Github Repo.There are two ways of App indexing as i have categorized with Web URL and Without Web URL.
  • With Web URL we could index the content of the app in Google Mobile Browser Search by showing your App and which will lead to open the App from native browser.
  • Without Web URL we could index the content of the app in Google Search Suggestion in Google Search App which leads to open the content of the apps.(BTW the search result display is not mentioned as far as i have read). 

Configure Your APP :

Just we have to configure your app manifest to accept the intents and make way to launch your app by other apps and receive data.Important thing in app indexing is having correct App URI and Keywords.Your app uri must be kind of,

android-app://com.example.app/<scheme>/<host>

However you can use your own custom scheme,Follow the given code below for example,


       <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>

                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="cricket"
                    android:pathPrefix="/sachin" />

            </intent-filter>
        </activity>

Test your app using adb command :

adb shell am start -a android.intent.action.VIEW -d "cricket://sachin" com.ivb.app.app_indexing
This must start the activity successfully without the errors! check out the code for manifest here.

Without Web URL : 

First of all let us assume that we have website with content and displaying in Google search results and we need to link that with our Android app.

There are two steps to set up this App indexing API :
  1. First implement the API in the Android application with few lines of code,Check out the simple Activity title to be indexed here.

Setting up Google API client :


public class MainActivity extends ActionBarActivity {
    GoogleApiClient mClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    mClient = new       GoogleApiClient.Builder(this).addApi(AppIndex.APP_INDEX_API).build();
      


using onStart method make your API call after loading your UI generally,make your web URL as null,since we don't deal with the with Web indexing now.we will deal with with web url in next post.


public void onStart(){
        super.onStart();

            mClient.connect();

            final String TITLE = "sachin tendulkar masterblaster";
            final Uri APP_URI = 
  Uri.parse("android-app://app.ivb.com.app_indexing/cricket/sachin");

            final Uri WEB_URL = null;

            PendingResult<Status> result = AppIndex.AppIndexApi.view(mClient, this,
                    APP_URI, TITLE, WEB_URL, null);

            result.setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Log.d("success", "App Indexing API: Recorded recipe view successfully.");
                    } else {
                        Log.e("error", "App Indexing API: There was an error"
                                + status.toString());
                    }
                }
            });

    }

Using onStop() method and disconnect the Client of GoogleAPI service


    
public void onStop(){
        super.onStop();

            final Uri APP_URI = 
Uri.parse("android-app://app.ivb.com.app_indexing/crciket/sachin");

            PendingResult<Status> result = AppIndex.AppIndexApi.viewEnd(mClient, this, APP_URI);

            result.setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Log.d("success", "App Indexing API: Recorded recipeview end successfully.");
                    } else {
                        Log.e("error", "App Indexing API: There was an error"
                                + status.toString());
                    }
                }
            });

            mClient.disconnect();


    }



Use this API calls wherever you want and you can make it dynamic for same activity by passing relevant uri and keywords.And main important thing here is giving Relevant Keywords for your Activity and content to be indexed in Google search and suggestion.

Note: After implementing this you can check your Google Search using Google Now/Search app Showing suggestion when you search relevant to your keywords.

My Results : Code hosted on GitHub



Well we had seen how to index our app content with keywords and APP-URI through APP-INDEXING API.However before implementing this API,Just test it the App-uri using adb tool and check whether it is resolved successfully and opening your app.

Lets implement with WEB url in next post with live App with search result indexing

For Suggestions/Help/hug/bug or projects just drop me a mail to s.shivasurya@gmail.com or chat with me in Facebook/Google+ hangout or connect with me in Twitter for recent updates.Share is care and sign up for newsletter for recent updates in blog.

Saturday, 13 September 2014

Getting Started With Ionic App - Android Application

Nowadays peoples get fascinated by using apps and even my friends review many apps from play store and share their experience with their besties :D . And recently i have attended a workshop on Mobile apps development and already working with ionic apps development.However there are lot of pitfalls in using html5 with phonegap while writing for native.The only thing is easy way to code and organize front end with backend.

Getting Started With Ionic App - Android Application


Installation :  

installing ionic in your system is very easy if you have node.js installed already and integrate it with Eclipse or any other ADT supported studio with plugins.

C:\> npm install -g ionic

Learn here to install node.js and using Eclipse IDE For android development.

Configuring on Windows :

Well i don't want to write too much of configuring steps here.all is simple short list goes below
  1. you must have installed Java and accessible Via commandline(javac and java)
  2. You must have installed ANT and accessible via commandline i.e simply specify the path till ant folder create as variable ANT_HOME
  3. You must have installed eclipse IDE(i had juno) with ADT updated with Android SDK and active emulators.
  4. now once again create ENV variable ANDROID_HOME specify the path till sdk folder
  5. Create three path variable with semicolon as terminator
    %ANT_HOME%\bin;
    %ANDROID_HOME%\tools;
    %ANDROID_HOME%\platform-tools;
Make sure everything works fine via CLI.However,this is common for both Windows/Linux.If you cant traces out wrong,similar doubts are answered in Stackoverflow forum.

Creating your first App : 

create a new directory and move into it using command prompt.here we are just creating a basic app and testing it locally on emulator installing the apk file into emulator from our ionic project.

  • C:\>ionic start demoapp tabs
    this creates demoapp folder with tabs app (previously demo files from ionic)
  • C:\>cd demoapp
  • C:\demoapp> ionic platform add android
    here we just add necessary build files for specific platform,since we are doing for android add key word android.This adds necessary bin,src config source files.
  • C:\demoapp>ionic build android
    just we are going to compile android application and create apk file from our source files.
  • C:\demoapp>ionic emulate android
    and finally this is gonna create a AVD(emulators) installing the apk file and launching the current activity on screen.
  • C:\demoapp>ionic run android
    and you can install it into android mobile if you have USB debuggin connected with internal/SD card storage under developer options in android os.
If all above steps consequently works ,then u may get compiled and ready to install the app.if any errors occurs in between,it may be fault in your path setting/installation.

Errors are going to be in Node.js exception format.you can track the errors and clear it with Stackoverflow website.

Screenshots :

Create a Demoapp folder.



Ionic start demoapp tabs command just download the starter template from github account and loads into the folder for you.


ionic platform add android : creates necessary build files for android project with java files and cardova plugins.

ionic build android : compiles the source and create necessary build files for android platform and dependencies


ionic emulate android : just creates avd for you and install apk file into the emulator and launches the main activity.


ionic run android : just deploy the android application directly into your android mobile while connecting with USB , With Unknown Source apps and USB debugging connected.look at screenshot below app on emulator.


Android Sample App running active device with installed app.




Download Demo files/install and work with project.However there are lot of disadvantages in hybrid app development.Your source codes are revealed when the apk file is decompiled :D in production.


For errors/bugs/suggestion comment below or mail me s.shivasurya@gmail.com or connect with me in Facebook/Twitter/Linkedin.Share is care.