Wednesday, 30 October 2013

Check for Wifi and see whether internet is reachable or not

package com.example.checkinternetconnection;

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
   
   
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.setThreadPolicy(policy);
        ConnectivityManager cm =
                (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
       
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                              activeNetwork.isConnectedOrConnecting();
        System.out.println("internet connection is "+isConnected);
       
       
         boolean isReachable = false;
       
         if (activeNetwork != null && activeNetwork.isConnected()) {
                // Some sort of connection is open, check if server is reachable
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setRequestProperty("User-Agent", "Android Application");
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(30 * 1000);
                    urlc.connect();
                    isReachable = (urlc.getResponseCode() == 200);
                    System.out.println("internet reachable true");
                } catch (IOException e) {
              
                   
                      System.out.println("internet reachable false"+e.getMessage());
                    Log.e("internet", e.getMessage());
                }
            }
       
       
       
       
       
           
       
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}


Manifest Changes :
-----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.checkinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.checkinternetconnection.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest>

Monday, 21 October 2013

Export Jar File In java



Push Notifications

Introduction

Sample App which registers with GCM and receives device token from it 

GCM Service Class

import android.app.Notification;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

    private static String TAG = GCMIntentService.class.getName();
    /**
     * Intent used to display a message in the screen.
     */
    public static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE";

    /**
     * Intent's extra that contains the message to be displayed.
     */
    public static final String EXTRA_MESSAGE = "message";

    public GCMIntentService() {
        super("project no");
    }

    @Override
    protected void onError(Context context, String errorId) {
        Log.i(TAG, "Received message " + errorId);
    }

    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        // String message = getString(R.string.gcm_message);
        String message = intent.getExtras().getString("message");
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Device registered: regId = " + registrationId);
    }

    @Override
    protected void onUnregistered(Context context, String registrationId) {
        // TODO Auto-generated method stub

    }

    private void displayMessage(Context context, String message) {
        Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
        intent.putExtra(EXTRA_MESSAGE, message);
        context.sendBroadcast(intent);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {

        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);
        String title = context.getString(R.string.app_name);
        Intent notificationIntent = new Intent(context, TimerScreen.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);

    }
}


BroadCast Receiver

package com.example.responsetest;

import android.app.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class TimerScreen extends Activity {
    /**
     * Intent's extra that contains the message to be displayed.
     */
    public static final String EXTRA_MESSAGE = "message";

    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        }
    };

}


MainActivity

package com.example.responsetest;

import com.google.android.gcm.GCMRegistrar;


import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // Make sure the device has the proper dependencies.
                GCMRegistrar.checkDevice(this);

                // Automatically registers application on startup.
                GCMRegistrar.register(this, "projectno");

                final String regId = GCMRegistrar.getRegistrationId(this);
                Log.d("GCMIntentService", "GCMIntentService " + regId);
               
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Client Jar

GCM Client jar is needed

Thursday, 17 October 2013

java handling string and splitting it in key-value



public class StringSplit {
            public static void main(String[] args) {

                        String assetClasses = "name = Gold: price = Stocks:icome = Fixed :********";
                        assetClasses.replace("*", "");
                        String[] splits = assetClasses.split(":");
                        HashMap<String, String> hash = new HashMap<String, String>();

                        System.out.println("splits.size: " + splits.length);
                        for (String asset : splits) {
                                    if (asset.indexOf("=") != -1) {
                                                String[] splitstwo = asset.split("=");

                                                //if ((splitstwo.length == 2))
                                                            hash.put(splitstwo[0], splitstwo[1]);

                                                for (String splitasset : splitstwo) {

                                                            System.out.println(splitasset);
                                                }
                                    }
                                    System.out.println(asset);
                                    System.out.println(hash);
                        }

            }

}

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...