Subversion Repositories SmartDukaan

Rev

Rev 23185 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.saholic.profittill.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.firebase.iid.FirebaseInstanceId;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import com.saholic.profittill.Constants.ProfitTillConstants;
import com.saholic.profittill.R;
import com.saholic.profittill.Utils.UtilityFunctions;
import com.testin.agent.TestinAgent;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
    public GoogleApiClient mGoogleApiClient;
    String scope = "oauth2:" + Scopes.PLUS_LOGIN +" " +Scopes.PLUS_ME + " " + Scopes.EMAIL;
    private boolean mIntentInProgress;
    private boolean mSignInClicked;
    private ConnectionResult mConnectionResult;
    private static final int RC_SIGN_IN = 0;
    public static final int REQUEST_CODE_TOKEN_AUTH =1;

    ArrayList<NameValuePair> nameValuePairsGcm;
    SharedPreferences userData;
    SharedPreferences apiData;
    SharedPreferences.Editor inviteDataEditor;
    SharedPreferences inviteData;
    boolean FLAG=false;
    SharedPreferences.Editor userDataEditor;
    SharedPreferences.Editor apiSettingsEditor;
    SharedPreferences inviteD;
    SharedPreferences.Editor inviteDEditor;
    ImageButton googlelogin;
    String mobile;
    MixpanelAPI mixpanel;
    FirebaseInstanceId fcm;
    Context context;
    String regId;
    String msg = "";
    public static final int   READ_Token_PERMISSION=101;
    static final String TAG = "Register Activity";
    private boolean PermissionIngranted=false;
    @Override

    protected void onCreate(Bundle savedInstanceState) {

        context = getApplicationContext();
        mixpanel= MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        TestinAgent.init(this);
        getSupportActionBar().hide();
        requestToken();
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
        userDataEditor = userData.edit();
        apiSettingsEditor = apiData.edit();
        inviteData = context.getSharedPreferences("Invite_Data", Context.MODE_PRIVATE);
        inviteDataEditor = inviteData.edit();
        inviteD = getApplicationContext().getSharedPreferences("Invite", MODE_PRIVATE);
        inviteDEditor = inviteD.edit();
        googlelogin =(ImageButton)findViewById(R.id.google_login_button);
        if(getIntent().getAction()=="Login"){
            nameValuePairsGcm = new ArrayList<>();
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
            nameValuePairsGcm.add(new BasicNameValuePair("result","login"));
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp",UtilityFunctions.notificationDate()));
            getIntent().getExtras().remove("cid");
            new NotificationOpenedData().execute(nameValuePairsGcm);
        }

        else if(getIntent().getAction()=="31"){
            String emailURL = String.valueOf(getIntent().getData());
            Uri url = Uri.parse(emailURL);
            String campaignId = url.getQueryParameter("campaign");
            if(url.getQueryParameter("intent_type").equalsIgnoreCase("url")) {
                Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                        GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Message/Email")
                        .setAction("Message/Email Opened For User Id " + UtilityFunctions.campaignUserId(url))
                        .setLabel("Campaign Id " + campaignId)
                        .build());
                nameValuePairsGcm = new ArrayList<>();
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", UtilityFunctions.campaignUserId(url)));
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
                new NotificationOpenedData().execute(nameValuePairsGcm);
            }
            else{
                nameValuePairsGcm = new ArrayList<>();
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id","")));
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
                new NotificationOpenedData().execute(nameValuePairsGcm);
            }
        }
        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
        t.setScreenName("Login Screen");
        t.send(new HitBuilders.ScreenViewBuilder().build());

        MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
        JSONObject props = new JSONObject();
        try {
            props.put("Screen", "Login Screen");
            mixpanel.track("Login Page", props);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        googlelogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isInternetOn()) {
                    if (TextUtils.isEmpty(regId)) {
                        regId = registerGCM();
                        Log.d("RegisterActivity", "GCM RegId: " + regId);
                    } else {
                    }
                    signInWithGplus();
                }
                else{
                    Toast.makeText(getApplicationContext(),"Sorry your internet is not working. Please check again",Toast.LENGTH_SHORT).show();
                }
            }
        });


        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();
    }
    public void requestToken(){
        try{
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.GET_ACCOUNTS)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(LoginActivity.this,
                            new String[]{Manifest.permission.GET_ACCOUNTS},
                            READ_Token_PERMISSION);
                } else {
                    PermissionIngranted = true;
                }
            } else {
                PermissionIngranted = true;
            }

        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    private void signInWithGplus() {
        if (!mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * Method to resolve any signin errors
     * */
    private void resolveSignInError() {
        if (mConnectionResult != null) {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            }
            catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
                TestinAgent.uploadException(this,"Exception in Resolve sign in error", new Exception());
                mIntentInProgress = false;
                mGoogleApiClient.connect();
                revokeGplusAccess();
            }
        }
    }}

    /**
     * Revoking access from google
     * */
    private void revokeGplusAccess() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                    .setResultCallback(new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status arg0) {
                            Log.e(TAG, "User access revoked!");
                            mGoogleApiClient.connect();
                            //updateUI(false);
                        }

                    });
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();

        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,0).show();
            return;
        }

        if (!mIntentInProgress) {
            mConnectionResult = result;
            if (mSignInClicked) {
                resolveSignInError();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int responseCode,
                                    Intent intent) {
        if (requestCode == RC_SIGN_IN) {
            if (responseCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
        else if (requestCode==REQUEST_CODE_TOKEN_AUTH &&responseCode==RESULT_OK){
            getAccessToken();
        }
    }

    private void getAccessToken() {
        new getToken().execute();

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }
    @Override
    public void onConnected(Bundle arg0) {
        mSignInClicked=false;
        getAccessToken();
    }
    private void showProgressDialog()
    {
        pDlg = new ProgressDialog(LoginActivity.this);
        pDlg.setMessage("Logging In");
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDlg.setCancelable(false);
        pDlg.show();

    }
    private ProgressDialog pDlg = null;
    class getToken extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }
        @Override
        protected String doInBackground(String... params) {
            String registered=null;
            String googletoken = null;
            Bundle appActivities = new Bundle();
          //  appActivities.putString(GoogleAuthUtil.,"MainActivity");
            try {
                googletoken = GoogleAuthUtil.getToken(
                        LoginActivity.this,
                        Plus.AccountApi.getAccountName(mGoogleApiClient),
                        scope,appActivities);
                if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                    HttpClient httpclient = new DefaultHttpClient();
                    String json = "";
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "GOOGLE");
                    jsonObject.put("token", googletoken);
                    json = jsonObject.toString();
                    HttpPost httppost = new HttpPost(apiData.getString("Web_Api_Login","http://app.profitmandi.com/apis/user/googleLogin"));

                 //   HttpPost httppost = new HttpPost("http://192.168.120.52:8080/profitmandi-web/user/googleLogin");
                    StringEntity se = new StringEntity(json);
                    httppost.setEntity(se);
                    httppost.setHeader("Content-type", "application/json");
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
                    JSONObject jobj= jObjGmail.getJSONObject("response");
                    registered=jobj.getString("registered");
                    if(!registered.equalsIgnoreCase(null)) {
                        String token = jobj.getString("token");
                        Log.d("token",token);
                        userDataEditor.putString("token", token);
                        userDataEditor.putString("email", Plus.AccountApi.getAccountName(mGoogleApiClient));
                        userDataEditor.putString("registered", registered);
                        userDataEditor.putString("type", "google");
                        userDataEditor.commit();
                    }
                    else{

                    }
                }
                else{
                    return "failure";
                }
            }
            catch (IOException transientEx) {
                Log.e("InputOutput", transientEx.toString());

            }
            catch (UserRecoverableAuthException e) {
                Log.d("Here","Here " + e.getMessage());
                Intent recover = e.getIntent();
                startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
            }
            catch (GoogleAuthException authEx) {
                Log.e("AuthEX", authEx.toString());
            }
            catch (Exception e) {
                Log.e("Exception main", e.toString());
            }

            return registered;
        }
        @Override
        protected void onPostExecute(String result){
            super.onPostExecute(result);

            try {
                if (userData.getString("registered",null) == null)  {
                    if(mGoogleApiClient.isConnected()) {
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                        mGoogleApiClient.disconnect();
                        userDataEditor.clear().commit();
                    }
                    else{
                        userDataEditor.clear().commit();
                    }
                    if(pDlg!=null){
                        pDlg.dismiss();
                    }
                }
                else{
                    new AuthTokenChange().execute();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }}
     class AuthTokenChange extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(apiData.getString("Web_Api_Tokendetail","http://app.profitmandi.com/apis/user/detail/token"));
                //HttpGet httpget = new HttpGet("http://192.168.120.52:8080/profitmandi-web/user/detail/token");
                httpget.setHeader("Auth-Token", userData.getString("token", ""));
                HttpResponse response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                int status = response.getStatusLine().getStatusCode();
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
                Log.d("Json",String.valueOf(jObjGmail));
                return String.valueOf(jObjGmail);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONObject jobj=jsonObject.getJSONObject("response");
                String userStatus=jobj.getString("userStatus");
                userDataEditor.putString("userStatus",userStatus);
                userDataEditor.commit();
                if(!(userData.getString("userStatus","").equals("notRegistered"))) {
                    String user_id = jobj.getString("userId");
                    userDataEditor.putString("id", user_id);
                    userDataEditor.commit();
                    if(!(userData.getString("id", "").equals(""))){
                        UtilityFunctions utf = new UtilityFunctions();
                        new pushApkData().execute(utf.getDeviceInformation(getApplicationContext()));
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
                        i.putExtra("displayView","0");
                        startActivity(i);
                    }
                    else{
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
                        i.putExtra("displayView","0");
                        startActivity(i);
                    }
                }
                else{
                    Intent i = new Intent(LoginActivity.this,MainActivity.class);
                    i.putExtra("displayView","0");
                    startActivity(i);
                }

            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    boolean doubleBackToExitPressedOnce = false;
    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setIcon(R.drawable.exitsymbol)
                .setTitle("Exit!")
                .setMessage("Are you sure you want to close?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
                        startMain.addCategory(Intent.CATEGORY_HOME);
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(startMain);
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }

    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {

                if (fcm == null) {
                    regId =FirebaseInstanceId.getInstance().getToken();
                    Log.d("RegisterActivity", "registerInBackground - regId: "
                            + regId);
                    msg = "Device registered";
                }
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
            }
        }.execute(null, null, null);
    }

    public String registerGCM() {
        regId = getRegistrationId(context);
        registerInBackground();
        return regId;
    }

    private String getRegistrationId(Context context) {

        String registrationId = userData.getString("gcm_regid", "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        return registrationId;
    }

    class gcmPushData extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
            MixpanelAPI.People people = mixpanel.getPeople();
            JSONObject props = new JSONObject();
            try {
                mixpanel.identify(userData.getString("id",null));
                people.identify(userData.getString("id",null));
                props.put("Screen", "Logged In");
                people.set("$last_login",new Date());
                people.set("user_id" , userData.getString("id",null));
                mixpanel.track("Successfully Logged In", props);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
            t.set("&uid",userData.getString("id",null));
            t.send(new HitBuilders.EventBuilder()
                    .setCategory("Login ")
                    .setAction("Login Successful")
                    .setLabel("Successful for User" +userData.getString("id",null))
                    .build());
        }

        @SuppressLint("MissingPermission")
        @Override
        protected String doInBackground(String... arg0) {
            String id=null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url","http://api.profittill.com/gcm_users/add"));
                //HttpPost httppost = new HttpPost(ProfitTillConstants.gcm_url);
                nameValuePairsGcm = new ArrayList<>();
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid",regId));
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
                nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id", null)));
                nameValuePairsGcm.add(new BasicNameValuePair("notification_type","fcm"));
                nameValuePairsGcm.add(new BasicNameValuePair("device_message",arg0[0]));
                nameValuePairsGcm.add(new BasicNameValuePair("androidid",UtilityFunctions.androidId(LoginActivity.this)));
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                int status = response.getStatusLine().getStatusCode();

                if(status == 200){
                    Log.d("ResponseCode GCM",status+"");
                    userDataEditor.putString("fcm_token_sent", "true");
                    userDataEditor.commit();
                } else {
                    Log.d("ResponseCode GCM",status+"");
                }

                nameValuePairsGcm.clear();
                Log.e("pass 1", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 1", e.toString());

            }
            return id;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(pDlg!=null){
                pDlg.dismiss();
            }
            userDataEditor.putString("gcm_regid", regId);
            userDataEditor.commit();

            String check = userData.getString("message","");
            /* if(userData.getString("docsSubmitted","").equalsIgnoreCase("true")){
               // Intent i = new Intent(LoginActivity.this, PendingActivity.class);
               // startActivity(i);
            }
            else  if(userData.getString("referralCodeRequired","").equalsIgnoreCase("true")){
                Log.d("In if","in if" +inviteD.getString("referrerCode","").equalsIgnoreCase("") + inviteD  .getString("referrerCode","") );
                //Intent i = new Intent(LoginActivity.this, BasicInformation.class);
                 //startActivity(i);
            }
            else if(check.equalsIgnoreCase("true")){
                    Log.d("In if","in else");
                    //Intent i = new Intent(LoginActivity.this, MobileNumber.class);
                   // i.putExtra("displayView", "7");
                   // startActivity(i);
            }
            else{*/

        }
    }


    public final boolean isInternetOn() {

        ConnectivityManager connection =
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);

        if ( connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {

            return true;

        } else if (
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {

            return false;
        }
        return false;
    }
    class NotificationOpenedData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
            t.send(new HitBuilders.EventBuilder()
                    .setCategory("Notification")
                    .setAction("Notification Opened Login")
                    .setLabel("For User Id " + userData.getString("id","0"))
                    .build());
        }

        @Override
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(apiData.getString("notication.data.url","http://api.profittill.com/pushnotifications/add"));
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                int status = response.getStatusLine().getStatusCode();

                if(status == 200){
                    Log.d("Notification Opened","Notication opened and sent to server");
                    Log.d("ResponseCode GCM ",status+"");
                } else {
                    Log.d("ResponseCode GCM ",status+"");
                }

                nameValuePairsGcm.clear();
                Log.e("pass 1", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 1", e.toString());

            }
            return "success";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.d("Notification Opened","Notication opened and login page");
        }
    }

    class pushApkData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(apiData.getString("devices_info","http://api.profittill.com/devices/add"));
             //   HttpPost httppost = new HttpPost("http://192.168.120.52:8080/profitmandi-web/devices/add");
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                int status = response.getStatusLine().getStatusCode();
                if(status == 200){
                    return "success";
                } else {
                    return "failure";
                }
            }
            catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(userData.getString("fcm_token_sent","false").equalsIgnoreCase("false")){
                new gcmPushData().execute(msg);
            }

        }
    }
}