Sunday, May 31, 2015

Android Listening for SMS intents

Basically, need to create a Broadcast receiver. Some of the devices, we may need to also give the priority so that the message is received. 

public class SmsListener extends BroadcastReceiver{
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
            for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                String messageBody = smsMessage.getMessageBody();
            }
        }
    }
}

Below need to be added in the manifest file 

".listener.SmsListener">
"2147483647">
"android.provider.Telephony.SMS_RECEIVED" />

Also, below permission should be given in the manifest file. 

"android.permission.RECEIVE_SMS" />

References:

SAML- based SSO for Google Apps - Detailed steps

Google documentation has given a detailed overall process involved login to a hosted Google Application through a partner operated SAML_based SSO service. Just writing down main points got from this below. 

Before everything has to take place, the Partner must provide Google with the SSO service URL as well as the public key Google should use to verify the SAML responses. 

1. The user attempts to reach a hosted Google Application, such as gmail, start pages, or another Google service

2. Google generates a SAML authentication request. The SAML request is encoded and embedded into the URL for partners SSO service. The RelayState parameter containing the encoded URL of the Google application that the user is trying to reach is also embedded in the SSO URL. This relayState parameter is meant to be opaque identifier that is passed back without any modification or inspection. 

3. Google sends a redirect to the users browser. The redirect URL includes the encoded SAML authentication request that should be submitted to the partners SSO service. 

4. The parter decodes the SAML request and extracts the URL for both the ACL (Assertion Consumer Service) and the users destination (RelayState parameter). The parterre then authenticate the user. Patterns could authenticate users by either asking for a valid login credentials or by checking for valid session cookies. 

5. The Partner generates the SAML Response that contains the authenticated user’s user name. In accordance with the SAML 2.0 spec, the response is digitally singed with the partners public and private DSA/RSA keys. 

6.The partner encodes the SAML response and RelayState parameter and returned that information to the users browser The Parter provides a mechanism so that the browser can forward that info to the Google’s ACS. 

7. Google’s ACS verifies the SAML response using the parters public key. If the response is successfully verified, ACS redirects the user to the destination URL. 

8. The user has been redirected to the destination URL and is logged in to the Google Apps. 

References:

Android Bound Services

A bound service is the server in the client-server interface. A Bound service allows a component such as Activities to bind a service, send requests, receive responses, and even perform interprocess communication (IPC). A Bound service typically lives only while it serves another application component and does not run in the background indefinitely. 

Below are the basics of it. 

Bind Service is an implementation of Service class. The subclass should implement the onBind callback method. It should return Binder object that defines programming interface that clients can use to communicate with the service. 

Clients can call bindService to bind to service, when it calls this method, it should provide a ServiceConnection implementation. When the Android system creates the service, it calls back the onServiceConnected method on the ServiceConnection to deliver the IBinder object. 


Multiple Clients can connect to the same service, however, how many ever connections, it will return same Binder object.

When the last client unbinds the service, the service get destroyed by the system. 

When creating a service that provides binding, the service must provide and Binder that provides programming interface that clients can use to interact with the service. There are three ways an IBinder can be created

1. Extending the Binder class 

If the Service is local to the application, then Service can create an Binder object which is extended from Binder class. The clients can call the public methods available on this Binder object to perform tasks. 

This is a preferred technique, if the service is merely the background worker for the application, 

2. Using a Messenger 

If the purpose is to work across different process, one can create interface for the service with Messenger. In this manner, service defines a Handler that responds to different types of Message objects. The handler is basis for a messenger that can share an IBinder with the client, allowing the client to send commands to the service using Message objects. Additionally the client can define a messenger of its own so the service can send message back. 

3. Using AIDL.

Messegener technique is based on AIDL, The Messenger creates queue of all the client requests in a single thread, so the service receives requests one at a time. However, if we want to service to handle multiple requests simultaneously, then AIDL can be used. In this case, service must be capable to handling multiple threads and built thread safe. Most of the apps should not use the AIDL. 



References:

What is SAML (Part I Introduction)

Security Assertion Markup language is an XML based open standard data format for exchanging authentication and authorization data between parties in particular, between an identity provider and a service provider. SAML is a product of the OASIS security services technical Committee.



Google Apps offer a SAML based SSO service that provides partner companies with full control over the authorization and authentication of hosted user accounts that can access web based applications such as Gmail or Google calendar. Using SAML model, Google acts as a Service provider and provides services such as gmail and start pages Google Partners acts as Identity provider and control usernames passwords and other information used to identify , authenticate, and authorize users for web applications that Google hosts. There are a number of existing open source and commercial identity provider solutions that can help developer to implement SSO with Google apps. 

The Google SSO service is based on the SAML v2.0 specifications. SAML 2.0 is supported by several widely known vendors. 

References:

Saturday, May 30, 2015

What is Pioneer AppRadio

App Radio Mode brings car entertainment to a whole new level. With over 30 compatible smartphone apps specifically designed for the AppRadio mode, support for both iOS and Android, and more than 15 compatible car entertainment devices, one can easily find fit for the needs.  



Pioneer was the first market with third party CarPlay-compatible systems. Some facts below 

- Apple Car play works with iPhone , not with iPads or other iOS devices
- Bluetooth call audio uses wideband Speech profile, which delivers better speech quality
- Bluetooth Audio uses AVCRP 1.4, for data viewing / searching and control all without being tethered. 
  
Pioneer app radios is also compatible with the Android Smartphones. The entire list of Android products those were tested with Pioneer AppRadio is given in the link in references. 


The newer product lines also seems to be working with the Bluetooth. The devices have a capability to wirelessly stream audio and track meta data to the unit with basic control from the device. 

- A2DP profile for streaming 
- AVCRP profile for audio control (track metadata available on 2013 and 2012 AVIC and AVH models with ACRCP 1.3) 
- SPP (Serial Port Profile) for full on screen control of Pandora internet radio and Aha Radio apps when installed on Android device. 

References:

Monday, May 25, 2015

Java refreshing a bit of tips

To package a Java file into a jar file either for direct executable or for purpose of just packaging everything


jar -cf graphmaker.jar ./ 

This assumes that everything to be packaged is under the current directory. 

to execute the file from command line, below command can be used

java -cp graphmaker.jar GraphMaker log_1.txt  "word to scan in the file"

References:
https://docs.oracle.com/javase/tutorial/deployment/jar/

Sunday, May 24, 2015

What is Node.js ?

Node.js is a platform built on Chrome’s Javascript runtime for easily building fast, scalable network applications. Node.js uses an event driven, non blocking I/O model that makes it lightweight and efficient, perfect for data intensive real-time applications that run across distributed devices. 

Excited by the features, as per the documentation, below is the only lines of code that to be written to create a web server it seems! 

var http = require (‘http’);
http.createServer(function(req,res))
{
res.writeHead(200,{‘Content-Type’ : ‘text/plain’});
res.end(‘Hello World!’);
}).listen(1337,’127.0.0.1’);
console.log(‘Server running!’);

To run the server, one need to put the code into a file example.js and execute it with the node program from command line. 

%node example.js 

If we want to create a socket server, that is also easy. 

var net = require(‘net’);

var server = net.createServer(function(socket){
socket.write(‘Echo server\r\n’);
socket.pipe(socket);
}

Still need to get real hands on this, this is just a beginning of exploration.

References:

Glympse SDK

Glimpse is a fast, free, and simple way to share your location in real time with the people one trust. 

Send a Glimpse to friends to let them know that one is on the way. Request a Glympse of friend who is always running late. Create a group for a family reunion. 

Set a duration, pick a destination, choose the recipients and hit send. Glimpse will take care of the rest. 

It is flexible that Glimpse can be received anywhere, whether it is Mobile, tablet or desktop, anyone can receive a Glimpse - No software or setup is required. 

Glimpse is safe in the sense that user can set who can see one and for how long making it secure for families. 

Glympse is simple and faster than a phone call or a text message. Just select a contact, set a duration and hit send.  

References:

Creating an OAUTH server

Aim was to explore the tasks involved in creating a three-legged OAUTH server. For e.g. Create OWN secure API which can be released publiclyaly. 

The Common practice for implementing OAuth is two-legged or three-legged OAuth server. The major difference between these two is that two legged doesn’t involve another user. For e.g. if one want to access a user’s specific information, then consume three-legged server because an access token must be generated for the user in the application. 

For practical real world use, one should focus on the three-legged variety since its more practical for real-world use. 

The following is the simplified flow 

- The Consumer requests a token from the server
- The consumer then directs the user to a login page, passing the token with them 
- The user logs in and is redirected to the consumer with an access token
- The consumer takes the access token and requests the OAuth token to use with the future secure requests. 
- The OAuth token is retrieved, and the developer can now make secure requests by passing the token for validation. 

There are some reference code / samples available at https://code.google.com/p/oauth-php/ 

Below are the steps involved in setting up the OAuth server

- Setting up the database
- Creating OAuth Server
- Allowing registration 
- Generating request token
- Exchanging Request token for an Access token
- Validating a request
- Testing OAuth server


References:

Friday, May 22, 2015

Homebrew Installation on MAC

To install the home brew, below command can be used 

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

The above command tried to install, however resulted in permission errors. The git hub link in the references section was giving good info. there are two options

1, chmod -R 775 Library

2. cd /usr/local
# Moving old stuff out of the way.
sudo mv -v Library Library.old
# Now run Homebrew install script again.

After installing the package installations can be done by the following sample commands

$ brew install wget

References:

http://mxcl.github.com/homebrew/

What is Mosquitto?

Mosquito is an open source message broker that implements the MQTT version 3.1. The server listens on port 1883, 8883, 8884, and 8885. Port 1883 is standard unencrypted MQTT port and can be used with any MQTT client. Port 8883 and 8884 use certificate based SSL/TLS encryption (TLS 1.1, TLS 1.2) and client support to connect. In the TLS cases, one should use the certificate authority file mosquitto.org.crt to verify the server connection. Port 8883 allows unrestricted connection. Port 8884 requires clients to provide their own certificate to authenticate their connection.  

The binaries and source code for this can be downloaded from the web page given in the references. There are installation files that can be installed on Windows, MAC and a variety of other OSs. There is a client side lib file that libmosquitto that can be included in the iPhone application as well. 

References:

Thursday, May 21, 2015

iOS & Android Model Mapping

Android and iOS device model mapping,

Often the device model names are almost encrypted from the device APIs.

For iPhone it is something like this iPhone7,2
For Android phones it is something like SM-G900T

To get an actual model detail from these strings, below are few links that can be used

Below is a short summary of iPhones,


http://www.everymac.com/ultimate-mac-lookup/?search_keywords=iPad3,1 

Just replace the keyword with the appropriate model numebrs. 


For Android, below link can be used. 

https://storage.googleapis.com/support-kms-prod/DAC06E7D1302B790429AF6E84696FCFAB20B

Good to see all the devices in this list. Its in pages. 

References:
https://storage.googleapis.com/support-kms-prod/DAC06E7D1302B790429AF6E84696FCFAB20B
http://www.everymac.com/ultimate-mac-lookup/?search_keywords=iPad3,1

Wednesday, May 20, 2015

MQTT message format - Part I

MQTT contains a mandatory fixed-length header (2 bytes) and an optional message specific variable length header and message payload. 

Optional fields usually complicate the message processing. However, MQTT is optimized for bandwidth constrained unreliable networks (typically wireless networks), so optional fields are used to reduce data transmission as much as possible. 

MQTT uses network byte and bit ordering. 



References:

FOSSology

FOSSology

FOSSology is an open source analyze tool. The mission of this is to build a community that facilitates the study of free and open source software by providing free and open source data analysis tools. However, this tool has been evolved to be a set of tools to assist open source governance. Today, the predominent use of FOSSology to scan files for copyrights and licenses. 

the installation files can be checked out from the link http://www.fossology.org/releases/ 
there are debian, Fedora, RHEL, ubuntu variants of the software. 

Once the setup is done, just can give the files to analyze or the SVN url of the target project to analyze and the report will be generated by scanning the files and giving the Licenes used the in the app. This tool tell the licensing used in various sources included in the application. Whether or not they to be corrected, is unto the developer. 

References:

IBM Bluemix - A high level understanding

IBM bluemix is an  open standards, cloud platform for building, running and managing applications. With Bluemix, developers can focus on building excellent user experiences with flexible compute options, choice of DevOps tooling, and a power full set of IBM third party APIs and services. 


Bluemix works in the below way. 

When an app is deployed on bluemix, developer needs to configure it with enough information. 

For a mobile app, Bluemix contains an artifact that represents the mobile apps backend, such as the services that are used by the mobile app to communicate with the server. 

For Web App, developer must ensure the information about the proper runtime and framework is communicated to bluemix, so that it can set up the proper execution environment to run the app. 

Each execution environment, including both mobile and web, is isolated from the execution environment of other apps. The execution environments are isolated even though they are not same physical machine. The following figure shows the basic flow of how bluemix manages the deployment of apps. 

When an app is deployed in to Bluemix, the environment determines an appropriate virtual machine to which the app or artifacts that the app represents is sent. For mobile apps, a mobile backend projection is created on Bluemix. Any code for the mobile app running in the cloud eventually runs in the bluemix environment. For a web app, the code running in the cloud is the app itself that the developer deploys the the bluemix. 

The VM of Bluemix is knows an Droplet Execution Agent (DEA). 


Picture courtesy, IBM 

When the app is deployed, if it has a web interface (as for a Java web app,) or other REST based services (such as mobile services exposed publicly to the mobile app) users of the app can communicate with it by using normal HTTP requests. 

Each app can have one or more URLS associated with it. But all of them must point to the Bluemix endpoint. When a request comes in, Bluemix examines the request, determines which app is intended for and then selects one of the instances of the app to receive the request.   

references:

Sunday, May 17, 2015

Few Jargons - Google Fiber, Project Fi

Google Fiber:
- Google Fiber is is about Super fast internet. This is Fiber-to-the premises service in the US providing broadband internet and cable television to a small and slowly increasing number of locations. As of March 2015, it had 27000 TV subscribers 



Project Fi 
Project Fi is a program to deliver fast, easy Wireless experience in close partnership with leading carriers , hardware makers, and Google users. 



Project Fi uses new technology to give users fast speed in more places and better connections to WiFi. Project Fi makes it easy to communicate in more places and use user’s  number with all his devices
Call and text can be made over WiFi for more coverage. 

Calls transition seamlessly between Wifi and cellular networks. 

To use phone number on any device, Connect any device that supports Google hangouts to the number then talk and text with anyone. The device can be Android , iOS, windows Mac OR Chromebook 

references:
https://fi.google.com/

Monday, May 11, 2015

MQTT on constrained devices - Part III

MQTT is designed for constrained devices. 
- Protocol comprised of bit-wise headers and variable length fields. 
- Smaller possible packet size is 2 bytes 
- Asynchronous bidirectional “push” delivery of messages to applications (no polling)
- Supports always connected and sometimes-connected models 
- Provides session awareness
- Configurable keep alive providing granual session awayreness 
- Last will and testament enable applications to know when a client goes offline abnormally.
- Typically utilises TCP based networks e.g. web sockets . The Http protocol can be upgraded as web sockets  
- Tested on many networks - vsat, gprs, 2G —

This protocol provides multiple deterministic message delivery qualities of Service. 

- 0. message delivered at most once
- 1 message will be delivered but may be duplicated 
- 2 - once and once only delivery
- QOS maintained over fragile network even if connection breaks. 

The protocol is suited for applications . devices that may have limited resources available 
- 8 bit controllers and upwards 
- Battery constrained devices 

There are multiple MQTT client implementations are available in many form factors / languages 
- Tiny footprint MQTT client and server libraries e.g. a C client lin in 30Kn and Java lib in 64 kb


References:

MQTT - Topics - Part II


A Topic forms the namespace. 
- Topic is  hierarchical with each “sub topic” separated by / 
- An example topic space 

A house publishes information about itself on
- / / / //energyConsumption 
- / / / / / solarEnergy 
- / / / / / alarmState
- / / / / / solarEnergy 
And it subscribes for control commands 
- / / / / / thermostat / setTemp 

A subscriber can subscribe to an absolute topic or can use wildcards. 
- Single level wildcards “+” can appear anywhere in the topic string 
- Mutli level wildcards “#” must appear at the end of the string 
- Wildcards must be next to a separator 
- Canot be used wildcards when publishing 

For example 
- India/KA/Bangalore/560100/1/energyconsumption
Energy consumption for 1 house in Bangalore
- India/KA/Bangalore/+/+/energyconsumption
Energy consumption of all houses in Bangalore
- India/KA/Bangalore/560100/# 

Details of Energy consumption, solar and alarm for all houses in 560100 

A subscription can be durable or non durable. 
Durable 
Once the subscription is in place, the broker will forward matching messages to the subscriber. 
Immediately if the subscriber is connected
If the subscriber is not connected, the messages are stored on the server/broker until the next time the subscriber connects. 
Non-Durable 
The subscription lifetime is the same as the time the subscriber is connected to the server / broker. 

A publication may be retained
- A publisher can mark a publication as retained. 
- The broker remembers the last known good message of a retained topic. 
- The broker gives the last known good message to new subscribers 

i.e. the new subscriber does not have to wait for a publisher to publish a message in order to receive its first message. 

references: 

MQTT in a Nutshell


MQTT stands for MQ Telemetry Transport. In a nutshell, it is a light weight event and message oriented protocol allowing devices to asynchronously communicate efficiently across constrained networks to remote systems. 

MQTT was invented before 13 years ago. The idea of this protocol is to get the data from the sensors, actuators, embedded controllers to a centralised data base system. Also this deals with how to get the control messages to these devices. In short, this is about connecting the traditional physical world devices to the IT infrastructure. 

Below are few design goals of MQTT 

1. To make it simple to connect the M2M (physical) world to the traditional IT world 
2. Expect and cater for frequent network disruption - built for low bandwidth, high latency, unreliable, high cost network (cost per byte) 
3. Expect client applications may have very limited resources available (8 bit controller, 256 kb ram)
4. Provide loose coupling to support dynamic system environments where high volumes of physical world messages and events needs to be made available to enterprise servers and other consumers in ways that may not have been originally anticipated. 
5. Provide multiple deterministic message delivery qualities of service to reflect tradeoffs between bandwidth, availability, and delivery gurantees
6. Capable of supporting large number of devices (10k MQTT clients) 
7. Simple for application developers and implementation of the protocol. 
8. Publish the protocol for ease of adoption by device vendors and third party client software enabling support for a proliferation of platforms, technologies and networks that are driven by very diverse equations of cost, technology and physical constraints. 
9 To be industry agnostic. 

MQTT is a publish subscribe messaging mechanism. 

A producer sends (publishes) a message (publication) on a topic (subject) 
A consumer subscribes (makes a subscription) for messages on a topic (subject) 

A message server / broker matches publications to subscriptions 
- if no matches the message is discarded 

- if one or more matches the message is delivered to each matching subscriber or consumer. 

references: 
https://www.youtube.com/watch?v=-KNPXPmx88E

Saturday, May 9, 2015

iOS VoIP Socket connections

Creating a socket connection and sending some data over the socket connection is pretty simple. 

Configuring the connection 

        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.6",5060, &readStream, &writeStream);
        
        self.inputStream = (__bridge_transfer NSInputStream *)readStream;
        self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
        [self.inputStream setProperty:NSStreamNetworkServiceTypeVoIP forKey:NSStreamNetworkServiceType];
        // Setting the self delegate in input/output stream
        [self.inputStream setDelegate:self];
        [self.outputStream setDelegate:self];
        [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        
        // Open the Connection
        [self.inputStream open];

        [self.outputStream open];


Handlign callbacks 
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {
        case NSStreamEventNone:
            break;
            
        case NSStreamEventEndEncountered:
            [self printLog:@"Stream Event End"];
            break;
            
        case NSStreamEventErrorOccurred:
            [self printLog:[NSString stringWithFormat:@"Stream error: %@", aStream.streamError]];
            break;
            
        case NSStreamEventHasBytesAvailable:
            if (aStream == self.inputStream)
            {
                uint8_t buffer[1024];
                uint8_t *pongString = (uint8_t *)"Plong!\r\n";
                NSInteger bytesRead = [self.inputStream read:buffer maxLength:1024];
                NSString *stringRead = [[NSString alloc] initWithBytes:buffer length:bytesRead encoding:NSUTF8StringEncoding];
                stringRead = [stringRead stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
                
                [self printLog:[NSString stringWithFormat:@"Received: %@", stringRead]];
                [self.outputStream write:pongString maxLength:strlen((char*)pongString)];
                
            }
            break;
            
        case NSStreamEventHasSpaceAvailable:
            if (aStream == self.outputStream)
            {
                if (aStream == self.outputStream)
                {
                    [self.outputStream write:(const uint8_t *)"Plong!\r\n" maxLength:strlen("Plong\r\n")];
                    [self printLog:@"Plong sent"];
                }
            }
            break;
            
        case NSStreamEventOpenCompleted:
            if (aStream == self.inputStream)
            {
                [self printLog:@"NSStreamEventOpenCompleted"];
            }
            break;
            
        default:
            break;
    }
}

References:


Friday, May 8, 2015

SIP call flow generator

trying to run the cmake gave the below error:

-bash: cmake: command not found 

Install the cmake using port. 

sudo port cmake

then entered cmake … 

it shown below.

-- *** Will build version 20110914-160 ***
-- Configuring done
-- Generating done
-- Build files have been written to: /Users//Desktop/r/callflow-20120624-180/build

then the below command 

sudo make install

when trying to run, it was failing with the below error. 

callflow: error: setup directory "/usr/local/callflow" does not exist
Adjust your configuration

Found the links mentioned in the reference. 

sudo mkdir /usr/local/callflow

trying to run again 

h$ callflow pre-15050101.pcap
getopt: illegal option -- l
getopt: illegal option -- g
Terminating...

gave the terminating. 


References:

Wednesday, May 6, 2015

Android Battery Charging Status and broadcast


Below code can be used to query the battery status. This uses a sticky intent concept. 

        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = registerReceiver(null, ifilter);

        // Are we charging / charged?
        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;

        Log.v(LOG_TAG,"Charging status is :"+status);
        // How are we charging?
        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

        Log.v(LOG_TAG,"Charging Via :"+chargePlug);

        Intent batteryLevelIntent = new Intent(BROADCAST_ACTION);
        batteryLevelIntent.putExtra("chargingStatus",status);
        batteryLevelIntent.putExtra("chargingVia",chargePlug);
        batteryLevelIntent.putExtra("statusQueried",true);

        LocalBroadcastManager.getInstance(AppUtils.getAppContext()).sendBroadcast(intent);


Same thing can be done inside an intent receive method. We need to add below to the AndroidManifest xml file 

android:name=".sensors.PowerConnectionReceiver">
           
                android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
                android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
           
       

References:

Tuesday, May 5, 2015

Android Battery Charging Status and broadcast


Below code can be used to query the battery status. This uses a sticky intent concept. 

        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = registerReceiver(null, ifilter);

        // Are we charging / charged?
        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;

        Log.v(LOG_TAG,"Charging status is :"+status);
        // How are we charging?
        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

        Log.v(LOG_TAG,"Charging Via :"+chargePlug);

        Intent batteryLevelIntent = new Intent(BROADCAST_ACTION);
        batteryLevelIntent.putExtra("chargingStatus",status);
        batteryLevelIntent.putExtra("chargingVia",chargePlug);
        batteryLevelIntent.putExtra("statusQueried",true);

        LocalBroadcastManager.getInstance(AppUtils.getAppContext()).sendBroadcast(intent);


References:

Monday, May 4, 2015

SIPp making REGISTER work

My Intention mainly was to test an INVITE. But after installation, found that the simulation XML was not in the test suite. 

So, created one like this 

"1.0" encoding="ISO-8859-1" ?>
"sipp.dtd">

name="REGISTER without authentication">
    
   
    request="REGISTER" />
    <![CDATA[
        
        SIP/2.0 200 OK
        [last_Via:]
        [last_From:]
        [last_To:];tag=[call_number]
        [last_Call-ID:]
        [last_CSeq:]
        Contact:
        Content-Length: 0
        Expires: 3600
        
    ]]>
   

After having the above, the SIPP was started like this below. 

./sipp -sf sipp_register_no_auth.xml -t t1

after running the client app and the REGISTER was successful. The screen showed like below. 



Tutorial in below reference section was helpful to get an idea. 

References:

Saturday, May 2, 2015

Android Detecting Screen orientation

Below code works magnificiently for detecting whether the Activity is in portrait or landscape orientation

 public static int getScreenOrientation(Activity activity) {
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int orientation = activity.getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) {
                return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            } else {
                return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            }
        }
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
                return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        }
        return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
    }

references:

Android speech to text Avoiding Google native Popup.

Normally, below what can be used to bring up the native speech recogniser window. 
 Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                "Say Something!");
        try {
            ((Activity)getAppContext()).startActivityForResult(intent, 100);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getAppContext(),
                    "Sorry Speech to text is not supported",
                    Toast.LENGTH_SHORT).show();
        }

However, this above brings up the native popup. To avoid this, below technique can be used 

        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(AppUtils.getAppContext());
        speechRecognizer.setRecognitionListener(new SpeechRecognizerListener());

        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"livingmobile.com.eome");

        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
        speechRecognizer.startListening(intent);


public class SpeechRecognizerListener implements RecognitionListener {
    public void onResults(Bundle results)
    {
        String str = new String();
        Log.d(LOG_TAG, "onResults " + results);
        ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < data.size(); i++)
        {
            Log.d(LOG_TAG, "result " + data.get(i));
            buffer.append(data.get(i));
            buffer.append(",");

        }
        Toast.makeText(AppUtils.getAppContext(), buffer.toString(), Toast.LENGTH_SHORT).show();
    }
}

References

Friday, May 1, 2015

Android Ambient Light Sensing


In Android, Ambient Light Sensing is pretty much straight forward. Below is the code to achieve this. Also including some of the experiences in testing this out with the real hardware , my Android One phone. 

android.hardware.SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        if(sensorManager != null) {
            Sensor lightSensor
                    = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
            if (lightSensor == null){
                Log.v(LOG_TAG,"light sensor is null!");
            }else{
                float max =  lightSensor.getMaximumRange();
                Log.v(LOG_TAG,"Max light range is :"+max);
                sensorManager.registerListener(lightSensorEventListener,
                        lightSensor,
                        SensorManager.SENSOR_DELAY_NORMAL);

            }
        }
        else
        {
            Log.v(LOG_TAG,"Sensor manager is null during create");
        }

SensorEventListener lightSensorEventListener
            = new SensorEventListener(){

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            if(event.sensor.getType()==Sensor.TYPE_LIGHT){
                final float currentReading = event.values[0];
                Log.v(LOG_TAG,"Current reading from light sensor is :"+currentReading);
            }
        }

    };


Based on experience, few points below 

- During day light, the onSensorChanged call back get called frequently with values > 70 
- When there is no light, the value becomes < 10

References: