Wednesday 23 July 2014

HB Blog 5: How to send sms programmatically using phonegap and android?

The mobile application development landscape is filled with many ways to build a mobile app.
Among the most popular are:

    Native iOS,
    Native Android,
    PhoneGap,
    PhoneGap Android Cordova Library,
    Appcelerator Titanium.

1)PhoneGap Android Cordova Library:-

 Refer the below link for starting with phonegap:-

    http://docs.phonegap.com/en/2.0.0/guide_getting-started_android_index.md.html

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File



 Few important snippets for sms:-

   MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class MainActivity extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // Set by <content src="index.html" /> in config.xml
        super.loadUrl(Config.getStartUrl());
        //super.loadUrl("file:///android_asset/www/index.html")
    }
}
  
  smsplugin.js
1
2
3
4
5
6
7
var SmsPlugin = function () {};
SmsPlugin.prototype.send = function (phone, message, method, successCallback, failureCallback) {   
    return PhoneGap.exec(successCallback, failureCallback, 'SmsPlugin', "SendSMS", [phone, message, method]);
};
PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin("sms", new SmsPlugin());
});
  
  index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<script type="text/javascript">
         $(document).ready(function() {
             //leave empty for sending sms using default intent
             $("#btnDefaultSMS").click(function(){
                 var number = $("#numberTxt").val();
                 var message = $("#messageTxt").val();
                SmsPlugin.prototype.send(number, message, '',
                    function () {
                       alert('Message sent successfully'); 
                    },
                    function (e) {
                        alert('Message Failed:' + e);
                    }
                );              
             });
         });
      </script>
2)Native Android:-

 Refer the below link for starting with android:-

   https://developer.android.com/training/index.html

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File



 Few important snippets for sms:-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public void sendSMS(String phoneNumber,String message) {
        SmsManager smsManager = SmsManager.getDefault();
         String SENT = "SMS_SENT";
         String DELIVERED = "SMS_DELIVERED";
            SmsManager sms = SmsManager.getDefault();
            ArrayList<String> parts = sms.divideMessage(message);
            int messageCount = parts.size();        
     Log.i("Message Count", "Message Count: " + messageCount);    
         ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();
            ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(); 
            PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
            PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
            for (int j = 0; j < messageCount; j++) {
                sentIntents.add(sentPI);
                deliveryIntents.add(deliveredPI);
            }
            // ---when the SMS has been sent---
            registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
            }, new IntentFilter(SENT));

            // ---when the SMS has been delivered---
            registerReceiver(new BroadcastReceiver() {
               @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
            }, new IntentFilter(DELIVERED));         
            smsManager.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
           /* sms.sendMultipartTextMessage(phoneNumber, null, parts, sentIntents, deliveryIntents); */
    }

Monday 21 July 2014

HB Blog 4: View pager animation using page transformation for Android.

Viewpager:-

 Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.
ViewPager is most often used in conjunction with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

For more information regarding view pager follow below link:-
 http://developer.android.com/reference/android/support/v4/view/ViewPager.html

View pager animation for pages transition using page transformation:-

It is pretty simple,

1)Create viewpager and its pager adapter.Follow below code snippet  or refer above viewpager link.


1
2
3
4
5
//view pager instance...
final ViewPager viewPager = (ViewPager)findViewById(R.id.myViewPager);
viewPager.setAdapter(pageAdapter);
//your page adapter instance...
MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager()
2)Now, just attach a PageTransformer to the ViewPage.


1
2
3
4
5
6
7
viewPager.setPageTransformer(false, new PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                        // do transformation here
            }
        });
    } 
3)Find out few below examples.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//For Alpha Transformation:-

 viewPager.setPageTransformer(false, new PageTransformer() {
 @Override
            public void transformPage(View page, float position) {
                /**ALPHA TRANSFORMATION**/
                final float normalizedposition = Math.abs(Math.abs(position) - 1);
                page.setAlpha(normalizedposition);
            }
        });

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
//For Scaling Transformation:-

 viewPager.setPageTransformer(false, new PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                /**SCALING TRANSFORMATION**/
                final float normalizedposition = Math.abs(Math.abs(position) - 1);
                page.setScaleX(normalizedposition / 2 + 0.5f);
                page.setScaleY(normalizedposition / 2 + 0.5f);
            }
        });


1
2
3
4
5
6
7
8
9
//For Rotation Transformation:-

viewPager.setPageTransformer(false, new PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                /**ROATAION TRANSFORMATION**/
                page.setRotationY(position * -30);
            }
        });


4)Happy coding :)

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File 

Thursday 17 July 2014

HB Blog 3: LinkedIn Integration for Android.

This source code consist of all basic functionalities that one can do with LinkedIn Api for Android...Happy coding....:)

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File

Authentication

Overview

Follow the few easy steps below to make your first LinkedIn API call using OAuth 2.0.
We expect most new developers will prefer using OAuth 2.0 to implement authorization with LinkedIn APIs. Compared to its predecessor, OAuth 1.0a, the protocol is simpler and much easier to implement. However, for those applications that still need to support it, we do continue to provide legacy support for OAuth 1.0a.

Steps to Authenticate User

Step 1. Register your application
Register your application with LinkedIn. Specify a list of OAuth 2 redirect URLs by submitting a comma separated list of absolute URLs for your redirections else your requests to generate OAuth 2 tokens (Step 3 below) will fail. We strongly encourage using HTTPS. For more details please see our FAQs.

Step 2. Save your API Key and Secret Key
After registration, you will receive a unique API Key and a Secret Key. API Key helps us identify your application and lets you make API calls. For the safety of your application please do not share your Secret Key.

Step 3. Get an access token
Access token is unique to a user and an API Key. You need access tokens in order to make API calls to LinkedIn on behalf of the user who authorized your application. Follow the two steps below to get one:
a. Generate Authorization Code by redirecting user to LinkedIn's authorization dialog
Redirect https://www.linkedin.com/uas/oauth2/authorization?response_type=code
                                           &client_id=YOUR_API_KEY
                                           &scope=SCOPE
                                           &state=STATE
                                           &redirect_uri=YOUR_REDIRECT_URI
Make sure that you are using https for the request or you will get an error.
Parameter Description Possible Errors
response_type Required. Value is always code Passed a value other than code; Passed an empty value; Missing the parameter.
client_id Required. Value of your API Key given when you registered your application with LinkedIn Invalid client id; Passed multiple client ids; Passed an empty value; Missing the parameter
scope Optional. Use it to specify a list of member permissions that you need and these will be shown to the user on LinkedIn's authorization form. If not passed, defaults to r_ basicprofile. Specify multiple scopes by adding a space between different parameters. Remember to URL encode your spaces! Example: scope=r_fullprofile%20r_emailaddress%20r_network. Not spelled correctly or Invalid Value; Repeated scope values.
state Required. A unique string value of your choice that is difficult to guess. It should not contain any private information. This parameter will be returned to the specified redirect_url to validate the response and prevent CSRF. Example: state=DCEEFWF45453sdffef424 Passed an empty value; Missing the parameter
redirect_uri Required. URI in your app where users will be sent after authorization. URI can use http or https. Example: http://www.mycoolsite.com Passed an invalid value; Passed an empty or blank value; Missing the parameter
If you see error "Invalid redirect_uri. This value must match a URL registered with the API Key.", then register your OAuth 2 redirect URLs as explained in Step 1.

If the user authorizes your application they will be redirected to the redirect_uri that you specified in your request above along with a temporary authorization_code and the same state that you passed in the request above.
Upon successful authorization, the redirected URL should look like:
YOUR_REDIRECT_URI/?code=AUTHORIZATION_CODE&state=STATE
Ensure that the state parameter in this response matches the one you passed in the authorization request above. If the state does not match, that means the request may be a result of CSRF and must be rejected.
If the user does not allow authorization to your application, redirection to the redirect_uri still occurs, with query parameters indicating the user canceled authorization and a short description of the error:
YOUR_REDIRECT_URI/?error=access_denied&error_description=the+user+denied+your+
request&state=STATE
b. Request Access Token by exchanging the authorization_code for it
POST https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code
                                           &code=AUTHORIZATION_CODE
                                           &redirect_uri=YOUR_REDIRECT_URI
                                           &client_id=YOUR_API_KEY
                                           &client_secret=YOUR_SECRET_KEY
Make sure that you are using https for the request or you will get an error.
Parameter Description Possible Errors
grant_type Required. Value is always authorization_code Passed a value other than authorization_code; Passed an empty or blank value; Missing the parameter
code Required. Value of authorization_code that you got in the previous step. Passed invalid value; Authorization code expired; Passed an empty value; Missing the parameter
redirect_uri Required. Same redirect_uri that you passed in the previous step. Different redirect_uri than used during authorization code generation; Passed an invalid value; Passed an empty or blank value; Missing the parameter
client_id Required. Value of your API Key given when you registered your application with LinkedIn Different client-id than used during authorization code generation; Invalid client id; Passed multiple client ids; Passed an empty or blank value; Missing the parameter
client_secret Required. Value of your secret key given when you registered your application with LinkedIn Passed invalid value; Passed an empty value; Missing the parameter
The response will be a JSON object:
{"expires_in":5184000,
"access_token":"AQXdSP_W41_UPs5ioT_t8HESyODB4FqbkJ8LrV_5mff4gPODzOYR"}
The value of parameter expires_in is the number of seconds from now that this access_token will expire in (5184000 seconds is 60 days). Please ensure to keep the user access tokens secure, as agreed upon in our APIs Terms of Use.
Step 4. Make the API calls
You can now use this access_token to make API calls on behalf of this user by appending "oauth2_access_token=access_token" at the end of the API call that you wish to make.
GET https://api.linkedin.com/v1/people/~?oauth2_access_token=AQXdSP_W41_UPs5ioT_t8HESyODB4FqbkJ8LrV_5mff4gPODzOYR
Access tokens have a life span of 60 days. You should have a mechanism in your code to refresh the tokens before they expire in order to continue using the same access tokens. Otherwise you'll need to go through the authorization steps again. More details on how to handle expired tokens are explained on the next page.

Granting Member Permissions to Your Application

With the LinkedIn API, you have the ability to specify which permissions you want users to grant your application.
Member permissions provide the following:
  • Basic Profile default: When no permissions are specified, the basic profile permission will be used by default. Consider this to represent the current user’s ‘digital business card’.
  • All or None Grant: Members will need to accept all permissions requested by the application. Selection of individual permissions by the user is not supported.
  • Optimized for 3 Permissions: The user experience has been optimized for applications requesting 3 permissions. Requesting additional permissions are allowed, but not encouraged.
  • Re-Auth on Permission changes:A new login dialog will be presented to the user if different permissions are requested than what they initially granted.
Permission Scope Parameters
Requesting permissions from the user is straight forward. Pass the scopes you need granted as query parameters when redirecting the user to the /authorization endpoint. The following example asks for basic profile and email address permissions:
Alternatively, you may choose to specify which member permissions your application requests from the user without passing query parameters during authorization. You can easily configure this for your API key by visiting your application settings page and specify which scopes will be defaulted to the user in the Default scope section:

When the user is presented with the login dialog, LinkedIn shows the user the specific permissions you're asking for:

Below is a list of all member permissions
Permission Description Scope Primary Endpoints
Your Profile Overview Name, photo, headline, and current positions r_basicprofile GET /people/~
*see person field list
Your Full Profile Full profile including experience, education, skills, and recommendations r_fullprofile GET /people/~
*see person field list
Your Email Address The primary email address you use for your LinkedIn account r_emailaddress GET /people/~/email-address
Your Connections Your 1st and 2nd degree connections r_network GET /people/~/connections

GET /people/~/people-search
Your Contact Info Address, phone number, and bound accounts r_contactinfo GET /people/~

*see person field list
Network Updates Retrieve and post updates to LinkedIn as you rw_nus GET /people/~/network/updates

POST /people/~/shares
Company Page & Analytics Edit company pages for which I am an Admin and post status updates on behalf of those companies rw_company_admin POST /companies/{id}/shares

GETcompanies/{id}/company-statistics
Group Discussions Retrieve and post group discussions as you rw_groups GET & POST /groups

GET & POST /posts

GET & POST /people/~/group-memberships
Invitations and Messages Send messages and invitations to connect as you w_messages POST /people/~/mailbox

Migrating from OAuth 1.0a to OAuth 2.0

If you're already happy with your current OAuth 1.0a solution, a migration to OAuth 2.0 isn't necessary. However, if you do decide to make the change, your current users who have already authorized your application won't need to be authorized again. As long as these users are already logged into LinkedIn:
  1. Your previously authorized user goes through the OAuth 2.0 flow as described above
  2. LinkedIn determines that this user has previously authorized your application and returns an auth code
  3. Since user has already authorized, a redirect isn't required. Instead, simply upgrade the auth code for an access token
  4. Your application now has a valid OAuth 2.0 access token
Provided that the user is already logged into LinkedIn, this flow provides you with a simple way of obtaining a valid OAuth 2.0 access token without forcing your user to authorize your application again

Thursday 10 July 2014

HB Blog 2: How To Update the Google Play Store on your Android without an APK




It’s usually best to be on the latest version of the Google Play store app on your Android device since from time to time Google releases bug fixes, updates the UI and packs in even more new features.

Most people either wait until the newest version hits their device or downloads an APK from somewhere on the Internet, but there’s a much simpler way and it requires no downloading APKs and sideloading the app. 
Here is what to do:
  1. Open the Google Play Store app
  2. Open the side slide-out menu by clicking the three lines at the top left
  3. Select “Settings”
  4. Scroll down until you see “Build version”
  5. Click on “Build version”
If a new build of the Play Store is available, you will be prompted to download and install it. If it’s already the latest, you will get a message that reads, “Google Play Store is up to date,” as you can see in the photo above.

Friday 4 July 2014

HB Blog 1: ART android runtime Ahead-of-time (AOT) compilation.

Ahead-of-time (AOT) compilation

ART introduces ahead-of-time (AOT) compilation, which can improve app performance. ART also has tighter install-time verification than Dalvik.
At install time, ART compiles apps using the on-device dex2oat tool. This utility accepts DEX files as input and generates a compiled app executable for the target device. The utility should be able to compile all valid DEX files without difficulty. However, some post-processing tools produce invalid files that may be tolerated by Dalvik but cannot be compiled by ART. For more information, see Addressing Garbage Collection Issues.

Improved garbage collection

Garbage collection (GC) can impair an app's performance, resulting in choppy display, poor UI responsiveness, and other problems. ART improves garbage collection in several ways:
  • One GC pause instead of two
  • Parallelized processing during the remaining GC pause
  • Collector with lower pause time for the special case of cleaning up recently-allocated, short-lived objects
  • Improved garbage collection ergonomics, making concurrent garbage collections more timely, which makes GC_FOR_ALLOC events extremely rare in typical use cases
ART currently does not use compacting GC, but this feature is under development in the Android Open Source Project (AOSP). In the meantime, don't perform operations that are incompatible with compacting GC, such as storing pointers to object fields. For more information, see Addressing Garbage Collection Issues.