Subversion Repositories SmartDukaan

Rev

Rev 22381 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
22131 rajender 1
package com.saholic.profittill.main;
2
 
3
import android.Manifest;
4
import android.app.AlertDialog;
5
import android.app.ProgressDialog;
6
import android.content.Context;
7
import android.content.DialogInterface;
8
import android.content.Intent;
9
import android.content.IntentSender;
10
import android.content.SharedPreferences;
11
import android.content.pm.PackageManager;
12
import android.content.res.Configuration;
13
import android.net.ConnectivityManager;
14
import android.net.Uri;
15
import android.os.AsyncTask;
16
import android.os.Build;
17
import android.os.Bundle;
18
import android.support.v4.app.ActivityCompat;
19
import android.support.v4.content.ContextCompat;
20
import android.support.v7.app.ActionBarActivity;
21
import android.telephony.TelephonyManager;
22
import android.text.TextUtils;
23
import android.util.Log;
24
import android.view.Menu;
25
import android.view.MenuItem;
26
import android.view.View;
27
import android.widget.ImageButton;
28
import android.widget.Toast;
29
 
30
import com.google.android.gms.analytics.HitBuilders;
31
import com.google.android.gms.analytics.Tracker;
32
import com.google.android.gms.auth.GoogleAuthException;
33
import com.google.android.gms.auth.GoogleAuthUtil;
34
import com.google.android.gms.auth.UserRecoverableAuthException;
35
import com.google.android.gms.common.ConnectionResult;
36
import com.google.android.gms.common.GooglePlayServicesUtil;
37
import com.google.android.gms.common.Scopes;
38
import com.google.android.gms.common.api.GoogleApiClient;
39
import com.google.android.gms.common.api.ResultCallback;
40
import com.google.android.gms.common.api.Status;
41
import com.google.android.gms.plus.Plus;
42
import com.google.firebase.iid.FirebaseInstanceId;
43
import com.mixpanel.android.mpmetrics.MixpanelAPI;
44
import com.saholic.profittill.Constants.ProfitTillConstants;
45
import com.saholic.profittill.R;
46
import com.saholic.profittill.Utils.UtilityFunctions;
47
import com.testin.agent.TestinAgent;
48
 
49
import org.apache.http.HttpEntity;
50
import org.apache.http.HttpResponse;
51
import org.apache.http.NameValuePair;
52
import org.apache.http.client.HttpClient;
53
import org.apache.http.client.entity.UrlEncodedFormEntity;
54
import org.apache.http.client.methods.HttpGet;
55
import org.apache.http.client.methods.HttpPost;
56
import org.apache.http.entity.StringEntity;
57
import org.apache.http.impl.client.DefaultHttpClient;
58
import org.apache.http.message.BasicNameValuePair;
59
import org.apache.http.util.EntityUtils;
60
import org.json.JSONException;
61
import org.json.JSONObject;
62
 
63
import java.io.IOException;
64
import java.io.UnsupportedEncodingException;
65
import java.util.ArrayList;
66
import java.util.Date;
67
 
68
public class LoginActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
69
    public GoogleApiClient mGoogleApiClient;
70
    String scope = "oauth2:" + Scopes.PLUS_LOGIN +" " +Scopes.PLUS_ME + " " + Scopes.EMAIL;
71
    private boolean mIntentInProgress;
72
    private boolean mSignInClicked;
73
    private ConnectionResult mConnectionResult;
74
    private static final int RC_SIGN_IN = 0;
75
    public static final int REQUEST_CODE_TOKEN_AUTH =1;
76
    ArrayList<NameValuePair> nameValuePairs;
77
    ArrayList<NameValuePair> nameValuePairsGcm;
78
    SharedPreferences userData;
79
    SharedPreferences apiData;
80
    SharedPreferences.Editor inviteDataEditor;
81
    SharedPreferences inviteData;
82
    boolean FLAG=false;
83
    SharedPreferences.Editor userDataEditor;
84
    SharedPreferences.Editor apiSettingsEditor;
85
    SharedPreferences inviteD;
86
    SharedPreferences.Editor inviteDEditor;
87
    ImageButton googlelogin;
88
    String mobile;
89
    MixpanelAPI mixpanel;
90
    FirebaseInstanceId fcm;
91
    Context context;
92
    String regId;
93
    String msg = "";
94
    public static final int   READ_Token_PERMISSION=101;
95
    public static final String REG_ID = "regId";
96
    private static final String APP_VERSION = "appVersion";
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.hasResolution()) {
248
            try {
249
                mIntentInProgress = true;
250
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
251
            } catch (IntentSender.SendIntentException e) {
252
                e.printStackTrace();
253
                TestinAgent.uploadException(this,"Exception in Resolve sign in error", new Exception());
254
                mIntentInProgress = false;
255
                //mGoogleApiClient.connect();
256
                revokeGplusAccess();
257
            }
258
        }
259
    }
260
 
261
    /**
262
     * Revoking access from google
263
     * */
264
    private void revokeGplusAccess() {
265
        if (mGoogleApiClient.isConnected()) {
266
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
267
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
268
                    .setResultCallback(new ResultCallback<Status>() {
269
                        @Override
270
                        public void onResult(Status arg0) {
271
                            Log.e(TAG, "User access revoked!");
272
                            mGoogleApiClient.connect();
273
                            //updateUI(false);
274
                        }
275
 
276
                    });
277
        }
278
    }
279
 
280
    @Override
281
    public void onConfigurationChanged(Configuration newConfig) {
282
        super.onConfigurationChanged(newConfig);
283
    }
284
 
285
    protected void onStart() {
286
        super.onStart();
287
        mGoogleApiClient.connect();
288
    }
289
 
290
    protected void onStop() {
291
        super.onStop();
292
        if (mGoogleApiClient.isConnected()) {
293
            mGoogleApiClient.disconnect();
294
 
295
        }
296
    }
297
 
298
    @Override
299
    public void onConnectionFailed(ConnectionResult result) {
300
        if (!result.hasResolution()) {
301
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,0).show();
302
            return;
303
        }
304
 
305
        if (!mIntentInProgress) {
306
            mConnectionResult = result;
307
            if (mSignInClicked) {
308
                resolveSignInError();
309
            }
310
        }
311
    }
312
 
313
    @Override
314
    protected void onActivityResult(int requestCode, int responseCode,
315
                                    Intent intent) {
316
        if (requestCode == RC_SIGN_IN) {
317
            if (responseCode != RESULT_OK) {
318
                mSignInClicked = false;
319
            }
320
 
321
            mIntentInProgress = false;
322
 
323
            if (!mGoogleApiClient.isConnecting()) {
324
                mGoogleApiClient.connect();
325
            }
326
        }
327
        else if (requestCode==REQUEST_CODE_TOKEN_AUTH &&responseCode==RESULT_OK){
328
            getAccessToken();
329
        }
330
    }
331
 
332
    private void getAccessToken() {
333
        new getToken().execute();
334
 
335
    }
336
 
337
    @Override
338
    public void onConnectionSuspended(int arg0) {
339
        mGoogleApiClient.connect();
340
    }
341
    @Override
342
    public void onConnected(Bundle arg0) {
343
        mSignInClicked=false;
344
        getAccessToken();
345
    }
346
    private void showProgressDialog()
347
    {
348
        pDlg = new ProgressDialog(LoginActivity.this);
349
        pDlg.setMessage("Logging In");
350
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
351
        pDlg.setCancelable(false);
352
        pDlg.show();
353
 
354
    }
355
    private ProgressDialog pDlg = null;
356
    class getToken extends AsyncTask<String, Integer, String> {
357
 
358
        @Override
359
        protected void onPreExecute() {
360
            showProgressDialog();
361
        }
362
        @Override
363
        protected String doInBackground(String... params) {
364
            String registered=null;
365
            String googletoken = null;
366
            Bundle appActivities = new Bundle();
367
            appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,"MainActivity");
368
            try {
369
                googletoken = GoogleAuthUtil.getToken(
370
                        LoginActivity.this,
371
                        Plus.AccountApi.getAccountName(mGoogleApiClient),
372
                        scope,appActivities);
373
                if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
374
                    HttpClient httpclient = new DefaultHttpClient();
375
                    String json = "";
376
                    JSONObject jsonObject = new JSONObject();
377
                    jsonObject.put("type", "GOOGLE");
378
                    jsonObject.put("token", googletoken);
379
                    json = jsonObject.toString();
380
                    HttpPost httppost = new HttpPost(apiData.getString("Web_Api","http://shop2020.in:8080/profitmandi-web")+"/user/googleLogin");
381
                    //HttpPost httppost = new HttpPost(ProfitTillConstants.Web_Api+"/user/googleLogin");
382
                    StringEntity se = new StringEntity(json);
383
                    httppost.setEntity(se);
384
                    httppost.setHeader("Content-type", "application/json");
385
                    HttpResponse response = httpclient.execute(httppost);
386
                    HttpEntity entity = response.getEntity();
387
                    JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
388
                    JSONObject jobj= jObjGmail.getJSONObject("response");
389
                    registered=jobj.getString("registered");
390
                    if(!registered.equalsIgnoreCase(null)) {
391
                        String token = jobj.getString("token");
392
                        Log.d("token",token);
393
                        String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
394
                        userDataEditor.putString("token", token);
395
                        userDataEditor.putString("email", email);
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","http://shop2020.in:8080/profitmandi-web")+"/user/token-info");
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
                    }
501
                    else{
502
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
503
                        i.putExtra("displayView","0");
504
                        startActivity(i);
505
                    }
506
                }
507
                else{
508
                    Intent i = new Intent(LoginActivity.this,MainActivity.class);
509
                    i.putExtra("displayView","0");
510
                    startActivity(i);
511
                }
512
 
513
            }
514
            catch (JSONException e) {
515
                e.printStackTrace();
516
            }
517
        }
518
    }
519
    boolean doubleBackToExitPressedOnce = false;
520
    @Override
521
    public void onBackPressed() {
522
        new AlertDialog.Builder(this)
523
                .setIcon(R.drawable.symbol)
524
                .setTitle("Exit!")
525
                .setMessage("Are you sure you want to close?")
526
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
527
                {
528
                    @Override
529
                    public void onClick(DialogInterface dialog, int which) {
530
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
531
                        startMain.addCategory(Intent.CATEGORY_HOME);
532
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
533
                        startActivity(startMain);
534
                    }
535
                })
536
                .setNegativeButton("No", null)
537
                .show();
538
    }
539
 
540
    private void registerInBackground() {
541
        new AsyncTask<Void, Void, String>() {
542
            @Override
543
            protected String doInBackground(Void... params) {
544
 
545
                if (fcm == null) {
546
                    regId =FirebaseInstanceId.getInstance().getToken();
547
                    Log.d("RegisterActivity", "registerInBackground - regId: "
548
                            + regId);
549
                    msg = "Device registered";
550
                }
551
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
552
                return msg;
553
            }
554
 
555
            @Override
556
            protected void onPostExecute(String msg) {
557
            }
558
        }.execute(null, null, null);
559
    }
560
 
561
    public String registerGCM() {
562
        regId = getRegistrationId(context);
563
        registerInBackground();
564
        return regId;
565
    }
566
 
567
    private String getRegistrationId(Context context) {
568
 
569
        String registrationId = userData.getString("gcm_regid", "");
570
        if (registrationId.isEmpty()) {
571
            Log.i(TAG, "Registration not found.");
572
            return "";
573
        }
574
        return registrationId;
575
    }
576
 
577
    class gcmPushData extends AsyncTask<String, Integer, String> {
578
 
579
        @Override
580
        protected void onPreExecute() {
581
            super.onPreExecute();
582
            MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
583
            MixpanelAPI.People people = mixpanel.getPeople();
584
            JSONObject props = new JSONObject();
585
            try {
586
                mixpanel.identify(userData.getString("id",null));
587
                people.identify(userData.getString("id",null));
588
                props.put("Screen", "Logged In");
589
                people.set("$last_login",new Date());
590
                people.set("user_id" , userData.getString("id",null));
591
                mixpanel.track("Successfully Logged In", props);
592
            } catch (JSONException e) {
593
                e.printStackTrace();
594
            }
595
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
596
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
597
            t.set("&uid",userData.getString("id",null));
598
            t.send(new HitBuilders.EventBuilder()
599
                    .setCategory("Login ")
600
                    .setAction("Login Successful")
601
                    .setLabel("Successful for User" +userData.getString("id",null))
602
                    .build());
603
        }
604
 
605
        @Override
606
        protected String doInBackground(String... arg0) {
607
            String id=null;
608
            try {
609
                HttpClient httpclient = new DefaultHttpClient();
610
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url",null));
611
                //HttpPost httppost = new HttpPost(ProfitTillConstants.gcm_url);
612
                nameValuePairsGcm = new ArrayList<>();
613
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
614
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid",regId));
615
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
616
                nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id", null)));
617
                nameValuePairsGcm.add(new BasicNameValuePair("notification_type","fcm"));
618
                nameValuePairsGcm.add(new BasicNameValuePair("device_message",arg0[0]));
619
                nameValuePairsGcm.add(new BasicNameValuePair("androidid",UtilityFunctions.androidId(LoginActivity.this)));
620
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
621
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
622
                HttpResponse response = httpclient.execute(httppost);
623
                HttpEntity entity = response.getEntity();
624
                int status = response.getStatusLine().getStatusCode();
625
 
626
                if(status == 200){
627
                    Log.d("ResponseCode GCM",status+"");
628
                    userDataEditor.putString("fcm_token_sent", "true");
629
                    userDataEditor.commit();
630
                } else {
631
                    Log.d("ResponseCode GCM",status+"");
632
                }
633
 
634
                nameValuePairsGcm.clear();
635
                Log.e("pass 1", "connection success ");
636
            } catch (Exception e) {
637
                Log.e("Fail 1", e.toString());
638
 
639
            }
640
            return id;
641
        }
642
 
643
        @Override
644
        protected void onPostExecute(String result) {
645
            super.onPostExecute(result);
646
            if(pDlg!=null){
647
                pDlg.dismiss();
648
            }
649
            userDataEditor.putString("gcm_regid", regId);
650
            userDataEditor.commit();
651
 
652
            String check = userData.getString("message","");
653
            /* if(userData.getString("docsSubmitted","").equalsIgnoreCase("true")){
654
               // Intent i = new Intent(LoginActivity.this, PendingActivity.class);
655
               // startActivity(i);
656
            }
657
            else  if(userData.getString("referralCodeRequired","").equalsIgnoreCase("true")){
658
                Log.d("In if","in if" +inviteD.getString("referrerCode","").equalsIgnoreCase("") + inviteD  .getString("referrerCode","") );
659
                //Intent i = new Intent(LoginActivity.this, BasicInformation.class);
660
                 //startActivity(i);
661
            }
662
            else if(check.equalsIgnoreCase("true")){
663
                    Log.d("In if","in else");
664
                    //Intent i = new Intent(LoginActivity.this, MobileNumber.class);
665
                   // i.putExtra("displayView", "7");
666
                   // startActivity(i);
667
            }
668
            else{*/
669
            Intent i = new Intent(LoginActivity.this,MainActivity.class);
670
            i.putExtra("displayView","0");
671
            startActivity(i);
672
        }
673
    }
674
 
675
 
676
    public final boolean isInternetOn() {
677
 
678
        ConnectivityManager connection =
679
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);
680
 
681
        if ( connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
682
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
683
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
684
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
685
 
686
            return true;
687
 
688
        } else if (
689
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
690
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
691
 
692
            return false;
693
        }
694
        return false;
695
    }
696
    class NotificationOpenedData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
697
 
698
        @Override
699
        protected void onPreExecute() {
700
            super.onPreExecute();
701
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
702
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
703
            t.send(new HitBuilders.EventBuilder()
704
                    .setCategory("Notification")
705
                    .setAction("Notification Opened Login")
706
                    .setLabel("For User Id " + userData.getString("id","0"))
707
                    .build());
708
        }
709
 
710
        @Override
711
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
712
 
713
            try {
714
                HttpClient httpclient = new DefaultHttpClient();
715
                HttpPost httppost = new HttpPost(apiData.getString("notication.data.url","http://api.profittill.com/pushnotifications/add"));
716
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
717
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
718
                HttpResponse response = httpclient.execute(httppost);
719
                HttpEntity entity = response.getEntity();
720
                int status = response.getStatusLine().getStatusCode();
721
 
722
                if(status == 200){
723
                    Log.d("Notification Opened","Notication opened and sent to server");
724
                    Log.d("ResponseCode GCM ",status+"");
725
                } else {
726
                    Log.d("ResponseCode GCM ",status+"");
727
                }
728
 
729
                nameValuePairsGcm.clear();
730
                Log.e("pass 1", "connection success ");
731
            } catch (Exception e) {
732
                Log.e("Fail 1", e.toString());
733
 
734
            }
735
            return "success";
736
        }
737
 
738
        @Override
739
        protected void onPostExecute(String result) {
740
            super.onPostExecute(result);
741
            Log.d("Notification Opened","Notication opened and login page");
742
        }
743
    }
744
 
745
    class pushApkData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
746
 
747
        @Override
748
        protected void onPreExecute() {
749
            super.onPreExecute();
750
        }
751
 
752
        @Override
753
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
754
            try {
755
                HttpClient httpclient = new DefaultHttpClient();
756
                HttpPost httppost = new HttpPost("http://api.profittill.com/devices/add");
757
                //HttpPost httppost = new HttpPost(ProfitTillConstants.Push_Url);
758
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
759
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
760
                HttpResponse response = httpclient.execute(httppost);
761
                HttpEntity entity = response.getEntity();
762
                int status = response.getStatusLine().getStatusCode();
763
                if(status == 200){
764
                    return "success";
765
                } else {
766
                    return "failure";
767
                }
768
            }
769
            catch (Exception e) {
770
                e.printStackTrace();
771
                return null;
772
            }
773
        }
774
        @Override
775
        protected void onPostExecute(String result) {
776
            super.onPostExecute(result);
777
            if(userData.getString("fcm_token_sent","false").equalsIgnoreCase("false")){
778
                new gcmPushData().execute(msg);
779
            }
780
 
781
        }
782
    }
783
}
784