Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
23410 tejbeer 1
package com.saholic.profittill.main;
2
 
3
import android.Manifest;
4
import android.annotation.SuppressLint;
5
import android.app.AlertDialog;
6
import android.app.FragmentManager;
7
import android.app.ProgressDialog;
8
import android.content.Context;
9
import android.content.DialogInterface;
10
import android.content.Intent;
11
import android.content.IntentSender;
12
import android.content.SharedPreferences;
13
import android.content.pm.PackageManager;
14
import android.content.res.Configuration;
15
import android.net.ConnectivityManager;
16
import android.net.Uri;
17
import android.os.AsyncTask;
18
import android.os.Build;
19
import android.os.Bundle;
20
import android.support.v4.app.ActivityCompat;
21
import android.support.v4.content.ContextCompat;
22
import android.support.v7.app.ActionBarActivity;
23
import android.telephony.TelephonyManager;
24
import android.text.TextUtils;
25
import android.util.Log;
26
import android.view.Menu;
27
import android.view.MenuItem;
28
import android.view.View;
29
import android.widget.ImageButton;
30
import android.widget.Toast;
31
 
32
import com.google.android.gms.analytics.HitBuilders;
33
import com.google.android.gms.analytics.Tracker;
34
import com.google.android.gms.auth.GoogleAuthException;
35
import com.google.android.gms.auth.GoogleAuthUtil;
36
import com.google.android.gms.auth.UserRecoverableAuthException;
37
import com.google.android.gms.common.ConnectionResult;
38
import com.google.android.gms.common.GooglePlayServicesUtil;
39
import com.google.android.gms.common.Scopes;
40
import com.google.android.gms.common.api.GoogleApiClient;
41
import com.google.android.gms.common.api.ResultCallback;
42
import com.google.android.gms.common.api.Status;
43
import com.google.android.gms.plus.Plus;
44
import com.google.firebase.iid.FirebaseInstanceId;
45
import com.mixpanel.android.mpmetrics.MixpanelAPI;
46
import com.saholic.profittill.Constants.ProfitTillConstants;
47
import com.saholic.profittill.R;
48
import com.saholic.profittill.Utils.UtilityFunctions;
49
import com.testin.agent.TestinAgent;
50
 
51
import org.apache.http.HttpEntity;
52
import org.apache.http.HttpResponse;
53
import org.apache.http.NameValuePair;
54
import org.apache.http.client.HttpClient;
55
import org.apache.http.client.entity.UrlEncodedFormEntity;
56
import org.apache.http.client.methods.HttpGet;
57
import org.apache.http.client.methods.HttpPost;
58
import org.apache.http.entity.StringEntity;
59
import org.apache.http.impl.client.DefaultHttpClient;
60
import org.apache.http.message.BasicNameValuePair;
61
import org.apache.http.util.EntityUtils;
62
import org.json.JSONException;
63
import org.json.JSONObject;
64
 
65
import java.io.IOException;
66
import java.io.UnsupportedEncodingException;
67
import java.net.URL;
68
import java.util.ArrayList;
69
import java.util.Date;
70
 
71
public class LoginActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
72
    public GoogleApiClient mGoogleApiClient;
73
    String scope = "oauth2:" + Scopes.PLUS_LOGIN +" " +Scopes.PLUS_ME + " " + Scopes.EMAIL;
74
    private boolean mIntentInProgress;
75
    private boolean mSignInClicked;
76
    private ConnectionResult mConnectionResult;
77
    private static final int RC_SIGN_IN = 0;
78
    public static final int REQUEST_CODE_TOKEN_AUTH =1;
79
    ArrayList<NameValuePair> nameValuePairsGcm;
80
    SharedPreferences userData;
81
    SharedPreferences apiData;
82
    SharedPreferences.Editor inviteDataEditor;
83
    SharedPreferences inviteData;
84
    boolean FLAG=false;
85
    SharedPreferences.Editor userDataEditor;
86
    SharedPreferences.Editor apiSettingsEditor;
87
    SharedPreferences inviteD;
88
    SharedPreferences.Editor inviteDEditor;
89
    ImageButton googlelogin;
90
    String mobile;
91
    MixpanelAPI mixpanel;
92
    FirebaseInstanceId fcm;
93
    Context context;
94
    String regId;
95
    String msg = "";
96
    public static final int   READ_Token_PERMISSION=101;
97
    static final String TAG = "Register Activity";
98
    private boolean PermissionIngranted=false;
99
    @Override
100
 
101
    protected void onCreate(Bundle savedInstanceState) {
102
 
103
        context = getApplicationContext();
104
        mixpanel= MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
105
        super.onCreate(savedInstanceState);
106
        setContentView(R.layout.activity_login);
107
        TestinAgent.init(this);
108
        getSupportActionBar().hide();
109
        requestToken();
110
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
111
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
112
        userDataEditor = userData.edit();
113
        apiSettingsEditor = apiData.edit();
114
        inviteData = context.getSharedPreferences("Invite_Data", Context.MODE_PRIVATE);
115
        inviteDataEditor = inviteData.edit();
116
        inviteD = getApplicationContext().getSharedPreferences("Invite", MODE_PRIVATE);
117
        inviteDEditor = inviteD.edit();
118
        googlelogin =(ImageButton)findViewById(R.id.google_login_button);
119
        if(getIntent().getAction()=="Login"){
120
            nameValuePairsGcm = new ArrayList<>();
121
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
122
            nameValuePairsGcm.add(new BasicNameValuePair("result","login"));
123
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp",UtilityFunctions.notificationDate()));
124
            getIntent().getExtras().remove("cid");
125
            new NotificationOpenedData().execute(nameValuePairsGcm);
126
        }
127
 
128
        else if(getIntent().getAction()=="31"){
129
            String emailURL = String.valueOf(getIntent().getData());
130
            Uri url = Uri.parse(emailURL);
131
            String campaignId = url.getQueryParameter("campaign");
132
            if(url.getQueryParameter("intent_type").equalsIgnoreCase("url")) {
133
                Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
134
                        GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
135
                t.send(new HitBuilders.EventBuilder()
136
                        .setCategory("Message/Email")
137
                        .setAction("Message/Email Opened For User Id " + UtilityFunctions.campaignUserId(url))
138
                        .setLabel("Campaign Id " + campaignId)
139
                        .build());
140
                nameValuePairsGcm = new ArrayList<>();
141
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", UtilityFunctions.campaignUserId(url)));
142
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
143
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
144
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
145
                new NotificationOpenedData().execute(nameValuePairsGcm);
146
            }
147
            else{
148
                nameValuePairsGcm = new ArrayList<>();
149
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id","")));
150
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
151
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
152
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
153
                new NotificationOpenedData().execute(nameValuePairsGcm);
154
            }
155
        }
156
        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
157
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
158
        t.setScreenName("Login Screen");
159
        t.send(new HitBuilders.ScreenViewBuilder().build());
160
 
161
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
162
        JSONObject props = new JSONObject();
163
        try {
164
            props.put("Screen", "Login Screen");
165
            mixpanel.track("Login Page", props);
166
        } catch (JSONException e) {
167
            e.printStackTrace();
168
        }
169
        googlelogin.setOnClickListener(new View.OnClickListener() {
170
            @Override
171
            public void onClick(View v) {
172
                if(isInternetOn()) {
173
                    if (TextUtils.isEmpty(regId)) {
174
                        regId = registerGCM();
175
                        Log.d("RegisterActivity", "GCM RegId: " + regId);
176
                    } else {
177
                    }
178
                    signInWithGplus();
179
                }
180
                else{
181
                    Toast.makeText(getApplicationContext(),"Sorry your internet is not working. Please check again",Toast.LENGTH_SHORT).show();
182
                }
183
            }
184
        });
185
 
186
 
187
        mGoogleApiClient = new GoogleApiClient.Builder(this)
188
                .addConnectionCallbacks(this)
189
                .addOnConnectionFailedListener(this).addApi(Plus.API)
190
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();
191
    }
192
    public void requestToken(){
193
        try{
194
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
195
                if (ContextCompat.checkSelfPermission(this,
196
                        Manifest.permission.GET_ACCOUNTS)
197
                        != PackageManager.PERMISSION_GRANTED) {
198
                    ActivityCompat.requestPermissions(LoginActivity.this,
199
                            new String[]{Manifest.permission.GET_ACCOUNTS},
200
                            READ_Token_PERMISSION);
201
                } else {
202
                    PermissionIngranted = true;
203
                }
204
            } else {
205
                PermissionIngranted = true;
206
            }
207
 
208
        }
209
        catch (Exception e){
210
            e.printStackTrace();
211
        }
212
    }
213
 
214
    private void signInWithGplus() {
215
        if (!mGoogleApiClient.isConnecting()) {
216
            mSignInClicked = true;
217
            resolveSignInError();
218
        }
219
    }
220
 
221
    @Override
222
    public boolean onCreateOptionsMenu(Menu menu) {
223
        // Inflate the menu; this adds items to the action bar if it is present.
224
        getMenuInflater().inflate(R.menu.menu_login, menu);
225
        return true;
226
    }
227
 
228
    @Override
229
    public boolean onOptionsItemSelected(MenuItem item) {
230
        // Handle action bar item clicks here. The action bar will
231
        // automatically handle clicks on the Home/Up button, so long
232
        // as you specify a parent activity in AndroidManifest.xml.
233
        int id = item.getItemId();
234
 
235
        //noinspection SimplifiableIfStatement
236
        if (id == R.id.action_settings) {
237
            return true;
238
        }
239
 
240
        return super.onOptionsItemSelected(item);
241
    }
242
 
243
    /**
244
     * Method to resolve any signin errors
245
     * */
246
    private void resolveSignInError() {
247
        if (mConnectionResult != null) {
248
        if (mConnectionResult.hasResolution()) {
249
            try {
250
                mIntentInProgress = true;
251
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
252
            }
253
            catch (IntentSender.SendIntentException e) {
254
                e.printStackTrace();
255
                TestinAgent.uploadException(this,"Exception in Resolve sign in error", new Exception());
256
                mIntentInProgress = false;
257
                mGoogleApiClient.connect();
258
                revokeGplusAccess();
259
            }
260
        }
261
    }}
262
 
263
    /**
264
     * Revoking access from google
265
     * */
266
    private void revokeGplusAccess() {
267
        if (mGoogleApiClient.isConnected()) {
268
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
269
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
270
                    .setResultCallback(new ResultCallback<Status>() {
271
                        @Override
272
                        public void onResult(Status arg0) {
273
                            Log.e(TAG, "User access revoked!");
274
                            mGoogleApiClient.connect();
275
                            //updateUI(false);
276
                        }
277
 
278
                    });
279
        }
280
    }
281
 
282
    @Override
283
    public void onConfigurationChanged(Configuration newConfig) {
284
        super.onConfigurationChanged(newConfig);
285
    }
286
 
287
    protected void onStart() {
288
        super.onStart();
289
        mGoogleApiClient.connect();
290
    }
291
 
292
    protected void onStop() {
293
        super.onStop();
294
        if (mGoogleApiClient.isConnected()) {
295
            mGoogleApiClient.disconnect();
296
 
297
        }
298
    }
299
 
300
    @Override
301
    public void onConnectionFailed(ConnectionResult result) {
302
        if (!result.hasResolution()) {
303
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,0).show();
304
            return;
305
        }
306
 
307
        if (!mIntentInProgress) {
308
            mConnectionResult = result;
309
            if (mSignInClicked) {
310
                resolveSignInError();
311
            }
312
        }
313
    }
314
 
315
    @Override
316
    protected void onActivityResult(int requestCode, int responseCode,
317
                                    Intent intent) {
318
        if (requestCode == RC_SIGN_IN) {
319
            if (responseCode != RESULT_OK) {
320
                mSignInClicked = false;
321
            }
322
 
323
            mIntentInProgress = false;
324
 
325
            if (!mGoogleApiClient.isConnecting()) {
326
                mGoogleApiClient.connect();
327
            }
328
        }
329
        else if (requestCode==REQUEST_CODE_TOKEN_AUTH &&responseCode==RESULT_OK){
330
            getAccessToken();
331
        }
332
    }
333
 
334
    private void getAccessToken() {
335
        new getToken().execute();
336
 
337
    }
338
 
339
    @Override
340
    public void onConnectionSuspended(int arg0) {
341
        mGoogleApiClient.connect();
342
    }
343
    @Override
344
    public void onConnected(Bundle arg0) {
345
        mSignInClicked=false;
346
        getAccessToken();
347
    }
348
    private void showProgressDialog()
349
    {
350
        pDlg = new ProgressDialog(LoginActivity.this);
351
        pDlg.setMessage("Logging In");
352
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
353
        pDlg.setCancelable(false);
354
        pDlg.show();
355
 
356
    }
357
    private ProgressDialog pDlg = null;
358
    class getToken extends AsyncTask<String, Integer, String> {
359
 
360
        @Override
361
        protected void onPreExecute() {
362
            showProgressDialog();
363
        }
364
        @Override
365
        protected String doInBackground(String... params) {
366
            String registered=null;
367
            String googletoken = null;
368
            Bundle appActivities = new Bundle();
369
            appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,"MainActivity");
370
            try {
371
                googletoken = GoogleAuthUtil.getToken(
372
                        LoginActivity.this,
373
                        Plus.AccountApi.getAccountName(mGoogleApiClient),
374
                        scope,appActivities);
375
                if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
376
                    HttpClient httpclient = new DefaultHttpClient();
377
                    String json = "";
378
                    JSONObject jsonObject = new JSONObject();
379
                    jsonObject.put("type", "GOOGLE");
380
                    jsonObject.put("token", googletoken);
381
                    json = jsonObject.toString();
382
                    HttpPost httppost = new HttpPost(apiData.getString("Web_Api_Login","http://app.profitmandi.com/apis/user/googleLogin"));
383
                    StringEntity se = new StringEntity(json);
384
                    httppost.setEntity(se);
385
                    httppost.setHeader("Content-type", "application/json");
386
                    HttpResponse response = httpclient.execute(httppost);
387
                    HttpEntity entity = response.getEntity();
388
                    JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
389
                    JSONObject jobj= jObjGmail.getJSONObject("response");
390
                    registered=jobj.getString("registered");
391
                    if(!registered.equalsIgnoreCase(null)) {
392
                        String token = jobj.getString("token");
393
                        Log.d("token",token);
394
                        userDataEditor.putString("token", token);
395
                        userDataEditor.putString("email", Plus.AccountApi.getAccountName(mGoogleApiClient));
396
                        userDataEditor.putString("registered", registered);
397
                        userDataEditor.putString("type", "google");
398
                        userDataEditor.commit();
399
                    }
400
                    else{
401
 
402
                    }
403
                }
404
                else{
405
                    return "failure";
406
                }
407
            }
408
            catch (IOException transientEx) {
409
                Log.e("InputOutput", transientEx.toString());
410
 
411
            }
412
            catch (UserRecoverableAuthException e) {
413
                Log.d("Here","Here " + e.getMessage());
414
                Intent recover = e.getIntent();
415
                startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
416
            }
417
            catch (GoogleAuthException authEx) {
418
                Log.e("AuthEX", authEx.toString());
419
            }
420
            catch (Exception e) {
421
                Log.e("Exception main", e.toString());
422
            }
423
 
424
            return registered;
425
        }
426
        @Override
427
        protected void onPostExecute(String result){
428
            super.onPostExecute(result);
429
 
430
            try {
431
                if (userData.getString("registered",null) == null)  {
432
                    if(mGoogleApiClient.isConnected()) {
433
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
434
                        mGoogleApiClient.disconnect();
435
                        userDataEditor.clear().commit();
436
                    }
437
                    else{
438
                        userDataEditor.clear().commit();
439
                    }
440
                    if(pDlg!=null){
441
                        pDlg.dismiss();
442
                    }
443
                }
444
                else{
445
                    new AuthTokenChange().execute();
446
                }
447
            }
448
            catch (Exception e){
449
                e.printStackTrace();
450
            }
451
        }}
452
     class AuthTokenChange extends AsyncTask<String, Integer, String> {
453
 
454
        @Override
455
        protected void onPreExecute() {
456
 
457
            super.onPreExecute();
458
        }
459
 
460
        @Override
461
        protected String doInBackground(String... params) {
462
            try {
463
                HttpClient httpclient = new DefaultHttpClient();
464
                HttpGet httpget = new HttpGet(apiData.getString("Web_Api_Tokendetail","http://app.profitmandi.com/apis/user/detail/token"));
465
                //HttpGet httpget = new HttpGet(ProfitTillConstants.Web_Api + "/user/token-info");
466
                httpget.setHeader("Auth-Token", userData.getString("token", ""));
467
                HttpResponse response = httpclient.execute(httpget);
468
                HttpEntity entity = response.getEntity();
469
                int status = response.getStatusLine().getStatusCode();
470
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
471
                Log.d("Json",String.valueOf(jObjGmail));
472
                return String.valueOf(jObjGmail);
473
 
474
            } catch (UnsupportedEncodingException e) {
475
                e.printStackTrace();
476
            } catch (IOException e) {
477
                e.printStackTrace();
478
            } catch (JSONException e) {
479
                e.printStackTrace();
480
            }
481
            return null;
482
        }
483
 
484
        @Override
485
        protected void onPostExecute(String result) {
486
            super.onPostExecute(result);
487
            try {
488
                JSONObject jsonObject = new JSONObject(result);
489
                JSONObject jobj=jsonObject.getJSONObject("response");
490
                String userStatus=jobj.getString("userStatus");
491
                userDataEditor.putString("userStatus",userStatus);
492
                userDataEditor.commit();
493
                if(!(userData.getString("userStatus","").equals("notRegistered"))) {
494
                    String user_id = jobj.getString("userId");
495
                    userDataEditor.putString("id", user_id);
496
                    userDataEditor.commit();
497
                    if(!(userData.getString("id", "").equals(""))){
498
                        UtilityFunctions utf = new UtilityFunctions();
499
                        new pushApkData().execute(utf.getDeviceInformation(getApplicationContext()));
500
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
501
                        i.putExtra("displayView","0");
502
                        startActivity(i);
503
                    }
504
                    else{
505
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
506
                        i.putExtra("displayView","0");
507
                        startActivity(i);
508
                    }
509
                }
510
                else{
511
                    Intent i = new Intent(LoginActivity.this,MainActivity.class);
512
                    i.putExtra("displayView","0");
513
                    startActivity(i);
514
                }
515
 
516
            }
517
            catch (JSONException e) {
518
                e.printStackTrace();
519
            }
520
        }
521
    }
522
    boolean doubleBackToExitPressedOnce = false;
523
    @Override
524
    public void onBackPressed() {
525
        new AlertDialog.Builder(this)
526
                .setIcon(R.drawable.exitsymbol)
527
                .setTitle("Exit!")
528
                .setMessage("Are you sure you want to close?")
529
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
530
                {
531
                    @Override
532
                    public void onClick(DialogInterface dialog, int which) {
533
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
534
                        startMain.addCategory(Intent.CATEGORY_HOME);
535
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
536
                        startActivity(startMain);
537
                    }
538
                })
539
                .setNegativeButton("No", null)
540
                .show();
541
    }
542
 
543
    private void registerInBackground() {
544
        new AsyncTask<Void, Void, String>() {
545
            @Override
546
            protected String doInBackground(Void... params) {
547
 
548
                if (fcm == null) {
549
                    regId =FirebaseInstanceId.getInstance().getToken();
550
                    Log.d("RegisterActivity", "registerInBackground - regId: "
551
                            + regId);
552
                    msg = "Device registered";
553
                }
554
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
555
                return msg;
556
            }
557
 
558
            @Override
559
            protected void onPostExecute(String msg) {
560
            }
561
        }.execute(null, null, null);
562
    }
563
 
564
    public String registerGCM() {
565
        regId = getRegistrationId(context);
566
        registerInBackground();
567
        return regId;
568
    }
569
 
570
    private String getRegistrationId(Context context) {
571
 
572
        String registrationId = userData.getString("gcm_regid", "");
573
        if (registrationId.isEmpty()) {
574
            Log.i(TAG, "Registration not found.");
575
            return "";
576
        }
577
        return registrationId;
578
    }
579
 
580
    class gcmPushData extends AsyncTask<String, Integer, String> {
581
 
582
        @Override
583
        protected void onPreExecute() {
584
            super.onPreExecute();
585
            MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
586
            MixpanelAPI.People people = mixpanel.getPeople();
587
            JSONObject props = new JSONObject();
588
            try {
589
                mixpanel.identify(userData.getString("id",null));
590
                people.identify(userData.getString("id",null));
591
                props.put("Screen", "Logged In");
592
                people.set("$last_login",new Date());
593
                people.set("user_id" , userData.getString("id",null));
594
                mixpanel.track("Successfully Logged In", props);
595
            } catch (JSONException e) {
596
                e.printStackTrace();
597
            }
598
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
599
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
600
            t.set("&uid",userData.getString("id",null));
601
            t.send(new HitBuilders.EventBuilder()
602
                    .setCategory("Login ")
603
                    .setAction("Login Successful")
604
                    .setLabel("Successful for User" +userData.getString("id",null))
605
                    .build());
606
        }
607
 
608
        @SuppressLint("MissingPermission")
609
        @Override
610
        protected String doInBackground(String... arg0) {
611
            String id=null;
612
            try {
613
                HttpClient httpclient = new DefaultHttpClient();
614
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url","http://api.profittill.com/gcm_users/add"));
615
                //HttpPost httppost = new HttpPost(ProfitTillConstants.gcm_url);
616
                nameValuePairsGcm = new ArrayList<>();
617
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
618
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid",regId));
619
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
620
                nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id", null)));
621
                nameValuePairsGcm.add(new BasicNameValuePair("notification_type","fcm"));
622
                nameValuePairsGcm.add(new BasicNameValuePair("device_message",arg0[0]));
623
                nameValuePairsGcm.add(new BasicNameValuePair("androidid",UtilityFunctions.androidId(LoginActivity.this)));
624
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
625
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
626
                HttpResponse response = httpclient.execute(httppost);
627
                HttpEntity entity = response.getEntity();
628
                int status = response.getStatusLine().getStatusCode();
629
 
630
                if(status == 200){
631
                    Log.d("ResponseCode GCM",status+"");
632
                    userDataEditor.putString("fcm_token_sent", "true");
633
                    userDataEditor.commit();
634
                } else {
635
                    Log.d("ResponseCode GCM",status+"");
636
                }
637
 
638
                nameValuePairsGcm.clear();
639
                Log.e("pass 1", "connection success ");
640
            } catch (Exception e) {
641
                Log.e("Fail 1", e.toString());
642
 
643
            }
644
            return id;
645
        }
646
 
647
        @Override
648
        protected void onPostExecute(String result) {
649
            super.onPostExecute(result);
650
            if(pDlg!=null){
651
                pDlg.dismiss();
652
            }
653
            userDataEditor.putString("gcm_regid", regId);
654
            userDataEditor.commit();
655
 
656
            String check = userData.getString("message","");
657
            /* if(userData.getString("docsSubmitted","").equalsIgnoreCase("true")){
658
               // Intent i = new Intent(LoginActivity.this, PendingActivity.class);
659
               // startActivity(i);
660
            }
661
            else  if(userData.getString("referralCodeRequired","").equalsIgnoreCase("true")){
662
                Log.d("In if","in if" +inviteD.getString("referrerCode","").equalsIgnoreCase("") + inviteD  .getString("referrerCode","") );
663
                //Intent i = new Intent(LoginActivity.this, BasicInformation.class);
664
                 //startActivity(i);
665
            }
666
            else if(check.equalsIgnoreCase("true")){
667
                    Log.d("In if","in else");
668
                    //Intent i = new Intent(LoginActivity.this, MobileNumber.class);
669
                   // i.putExtra("displayView", "7");
670
                   // startActivity(i);
671
            }
672
            else{*/
673
 
674
        }
675
    }
676
 
677
 
678
    public final boolean isInternetOn() {
679
 
680
        ConnectivityManager connection =
681
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);
682
 
683
        if ( connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
684
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
685
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
686
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
687
 
688
            return true;
689
 
690
        } else if (
691
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
692
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
693
 
694
            return false;
695
        }
696
        return false;
697
    }
698
    class NotificationOpenedData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
699
 
700
        @Override
701
        protected void onPreExecute() {
702
            super.onPreExecute();
703
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
704
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
705
            t.send(new HitBuilders.EventBuilder()
706
                    .setCategory("Notification")
707
                    .setAction("Notification Opened Login")
708
                    .setLabel("For User Id " + userData.getString("id","0"))
709
                    .build());
710
        }
711
 
712
        @Override
713
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
714
 
715
            try {
716
                HttpClient httpclient = new DefaultHttpClient();
717
                HttpPost httppost = new HttpPost(apiData.getString("notication.data.url","http://api.profittill.com/pushnotifications/add"));
718
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
719
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
720
                HttpResponse response = httpclient.execute(httppost);
721
                HttpEntity entity = response.getEntity();
722
                int status = response.getStatusLine().getStatusCode();
723
 
724
                if(status == 200){
725
                    Log.d("Notification Opened","Notication opened and sent to server");
726
                    Log.d("ResponseCode GCM ",status+"");
727
                } else {
728
                    Log.d("ResponseCode GCM ",status+"");
729
                }
730
 
731
                nameValuePairsGcm.clear();
732
                Log.e("pass 1", "connection success ");
733
            } catch (Exception e) {
734
                Log.e("Fail 1", e.toString());
735
 
736
            }
737
            return "success";
738
        }
739
 
740
        @Override
741
        protected void onPostExecute(String result) {
742
            super.onPostExecute(result);
743
            Log.d("Notification Opened","Notication opened and login page");
744
        }
745
    }
746
 
747
    class pushApkData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
748
 
749
        @Override
750
        protected void onPreExecute() {
751
            super.onPreExecute();
752
        }
753
 
754
        @Override
755
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
756
            try {
757
                HttpClient httpclient = new DefaultHttpClient();
758
                HttpPost httppost = new HttpPost(apiData.getString("devices_info","http://api.profittill.com/devices/add"));
759
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
760
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
761
                HttpResponse response = httpclient.execute(httppost);
762
                HttpEntity entity = response.getEntity();
763
                int status = response.getStatusLine().getStatusCode();
764
                if(status == 200){
765
                    return "success";
766
                } else {
767
                    return "failure";
768
                }
769
            }
770
            catch (Exception e) {
771
                e.printStackTrace();
772
                return null;
773
            }
774
        }
775
        @Override
776
        protected void onPostExecute(String result) {
777
            super.onPostExecute(result);
778
            if(userData.getString("fcm_token_sent","false").equalsIgnoreCase("false")){
779
                new gcmPushData().execute(msg);
780
            }
781
 
782
        }
783
    }
784
}
785