Subversion Repositories SmartDukaan

Rev

Rev 22131 | Rev 22831 | Go to most recent revision | Details | Compare with Previous | 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();
22381 rajender 380
                    HttpPost httppost = new HttpPost(apiData.getString("Web_Api_Login","http://api.profitmandi.com:8080/profitmandi-web/user/googleLogin"));
22131 rajender 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
                        userDataEditor.putString("token", token);
22381 rajender 394
                        userDataEditor.putString("email", Plus.AccountApi.getAccountName(mGoogleApiClient));
22131 rajender 395
                        userDataEditor.putString("registered", registered);
396
                        userDataEditor.putString("type", "google");
397
                        userDataEditor.commit();
398
                    }
399
                    else{
400
 
401
                    }
402
                }
403
                else{
404
                    return "failure";
405
                }
406
            }
407
            catch (IOException transientEx) {
408
                Log.e("InputOutput", transientEx.toString());
409
 
410
            }
411
            catch (UserRecoverableAuthException e) {
412
                Log.d("Here","Here " + e.getMessage());
413
                Intent recover = e.getIntent();
414
                startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
415
            }
416
            catch (GoogleAuthException authEx) {
417
                Log.e("AuthEX", authEx.toString());
418
            }
419
            catch (Exception e) {
420
                Log.e("Exception main", e.toString());
421
            }
422
 
423
            return registered;
424
        }
425
        @Override
426
        protected void onPostExecute(String result){
427
            super.onPostExecute(result);
428
 
429
            try {
430
                if (userData.getString("registered",null) == null)  {
431
                    if(mGoogleApiClient.isConnected()) {
432
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
433
                        mGoogleApiClient.disconnect();
434
                        userDataEditor.clear().commit();
435
                    }
436
                    else{
437
                        userDataEditor.clear().commit();
438
                    }
439
                    if(pDlg!=null){
440
                        pDlg.dismiss();
441
                    }
442
                }
443
                else{
444
                    new AuthTokenChange().execute();
445
                }
446
            }
447
            catch (Exception e){
448
                e.printStackTrace();
449
            }
450
        }}
22381 rajender 451
     class AuthTokenChange extends AsyncTask<String, Integer, String> {
22131 rajender 452
 
453
        @Override
454
        protected void onPreExecute() {
455
 
456
            super.onPreExecute();
457
        }
458
 
459
        @Override
460
        protected String doInBackground(String... params) {
461
            try {
462
                HttpClient httpclient = new DefaultHttpClient();
22381 rajender 463
                HttpGet httpget = new HttpGet(apiData.getString("Web_Api_Tokeninfo","http://api.profitmandi.com:8080/profitmandi-web/user/token-info"));
22131 rajender 464
                //HttpGet httpget = new HttpGet(ProfitTillConstants.Web_Api + "/user/token-info");
465
                httpget.setHeader("Auth-Token", userData.getString("token", ""));
466
                HttpResponse response = httpclient.execute(httpget);
467
                HttpEntity entity = response.getEntity();
468
                int status = response.getStatusLine().getStatusCode();
469
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
470
                Log.d("Json",String.valueOf(jObjGmail));
471
                return String.valueOf(jObjGmail);
472
 
473
            } catch (UnsupportedEncodingException e) {
474
                e.printStackTrace();
475
            } catch (IOException e) {
476
                e.printStackTrace();
477
            } catch (JSONException e) {
478
                e.printStackTrace();
479
            }
480
            return null;
481
        }
482
 
483
        @Override
484
        protected void onPostExecute(String result) {
485
            super.onPostExecute(result);
486
            try {
487
                JSONObject jsonObject = new JSONObject(result);
488
                JSONObject jobj=jsonObject.getJSONObject("response");
489
                String userStatus=jobj.getString("userStatus");
490
                userDataEditor.putString("userStatus",userStatus);
491
                userDataEditor.commit();
492
                if(!(userData.getString("userStatus","").equals("notRegistered"))) {
493
                    String user_id = jobj.getString("userId");
494
                    userDataEditor.putString("id", user_id);
495
                    userDataEditor.commit();
496
                    if(!(userData.getString("id", "").equals(""))){
497
                        UtilityFunctions utf = new UtilityFunctions();
498
                        new pushApkData().execute(utf.getDeviceInformation(getApplicationContext()));
499
                    }
500
                    else{
501
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
502
                        i.putExtra("displayView","0");
503
                        startActivity(i);
504
                    }
505
                }
506
                else{
507
                    Intent i = new Intent(LoginActivity.this,MainActivity.class);
508
                    i.putExtra("displayView","0");
509
                    startActivity(i);
510
                }
511
 
512
            }
513
            catch (JSONException e) {
514
                e.printStackTrace();
515
            }
516
        }
517
    }
518
    boolean doubleBackToExitPressedOnce = false;
519
    @Override
520
    public void onBackPressed() {
521
        new AlertDialog.Builder(this)
522
                .setIcon(R.drawable.symbol)
523
                .setTitle("Exit!")
524
                .setMessage("Are you sure you want to close?")
525
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
526
                {
527
                    @Override
528
                    public void onClick(DialogInterface dialog, int which) {
529
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
530
                        startMain.addCategory(Intent.CATEGORY_HOME);
531
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
532
                        startActivity(startMain);
533
                    }
534
                })
535
                .setNegativeButton("No", null)
536
                .show();
537
    }
538
 
539
    private void registerInBackground() {
540
        new AsyncTask<Void, Void, String>() {
541
            @Override
542
            protected String doInBackground(Void... params) {
543
 
544
                if (fcm == null) {
545
                    regId =FirebaseInstanceId.getInstance().getToken();
546
                    Log.d("RegisterActivity", "registerInBackground - regId: "
547
                            + regId);
548
                    msg = "Device registered";
549
                }
550
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
551
                return msg;
552
            }
553
 
554
            @Override
555
            protected void onPostExecute(String msg) {
556
            }
557
        }.execute(null, null, null);
558
    }
559
 
560
    public String registerGCM() {
561
        regId = getRegistrationId(context);
562
        registerInBackground();
563
        return regId;
564
    }
565
 
566
    private String getRegistrationId(Context context) {
567
 
568
        String registrationId = userData.getString("gcm_regid", "");
569
        if (registrationId.isEmpty()) {
570
            Log.i(TAG, "Registration not found.");
571
            return "";
572
        }
573
        return registrationId;
574
    }
575
 
576
    class gcmPushData extends AsyncTask<String, Integer, String> {
577
 
578
        @Override
579
        protected void onPreExecute() {
580
            super.onPreExecute();
581
            MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
582
            MixpanelAPI.People people = mixpanel.getPeople();
583
            JSONObject props = new JSONObject();
584
            try {
585
                mixpanel.identify(userData.getString("id",null));
586
                people.identify(userData.getString("id",null));
587
                props.put("Screen", "Logged In");
588
                people.set("$last_login",new Date());
589
                people.set("user_id" , userData.getString("id",null));
590
                mixpanel.track("Successfully Logged In", props);
591
            } catch (JSONException e) {
592
                e.printStackTrace();
593
            }
594
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
595
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
596
            t.set("&uid",userData.getString("id",null));
597
            t.send(new HitBuilders.EventBuilder()
598
                    .setCategory("Login ")
599
                    .setAction("Login Successful")
600
                    .setLabel("Successful for User" +userData.getString("id",null))
601
                    .build());
602
        }
603
 
604
        @Override
605
        protected String doInBackground(String... arg0) {
606
            String id=null;
607
            try {
608
                HttpClient httpclient = new DefaultHttpClient();
609
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url",null));
610
                //HttpPost httppost = new HttpPost(ProfitTillConstants.gcm_url);
611
                nameValuePairsGcm = new ArrayList<>();
612
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
613
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid",regId));
614
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
615
                nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id", null)));
616
                nameValuePairsGcm.add(new BasicNameValuePair("notification_type","fcm"));
617
                nameValuePairsGcm.add(new BasicNameValuePair("device_message",arg0[0]));
618
                nameValuePairsGcm.add(new BasicNameValuePair("androidid",UtilityFunctions.androidId(LoginActivity.this)));
619
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
620
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
621
                HttpResponse response = httpclient.execute(httppost);
622
                HttpEntity entity = response.getEntity();
623
                int status = response.getStatusLine().getStatusCode();
624
 
625
                if(status == 200){
626
                    Log.d("ResponseCode GCM",status+"");
627
                    userDataEditor.putString("fcm_token_sent", "true");
628
                    userDataEditor.commit();
629
                } else {
630
                    Log.d("ResponseCode GCM",status+"");
631
                }
632
 
633
                nameValuePairsGcm.clear();
634
                Log.e("pass 1", "connection success ");
635
            } catch (Exception e) {
636
                Log.e("Fail 1", e.toString());
637
 
638
            }
639
            return id;
640
        }
641
 
642
        @Override
643
        protected void onPostExecute(String result) {
644
            super.onPostExecute(result);
645
            if(pDlg!=null){
646
                pDlg.dismiss();
647
            }
648
            userDataEditor.putString("gcm_regid", regId);
649
            userDataEditor.commit();
650
 
651
            String check = userData.getString("message","");
652
            /* if(userData.getString("docsSubmitted","").equalsIgnoreCase("true")){
653
               // Intent i = new Intent(LoginActivity.this, PendingActivity.class);
654
               // startActivity(i);
655
            }
656
            else  if(userData.getString("referralCodeRequired","").equalsIgnoreCase("true")){
657
                Log.d("In if","in if" +inviteD.getString("referrerCode","").equalsIgnoreCase("") + inviteD  .getString("referrerCode","") );
658
                //Intent i = new Intent(LoginActivity.this, BasicInformation.class);
659
                 //startActivity(i);
660
            }
661
            else if(check.equalsIgnoreCase("true")){
662
                    Log.d("In if","in else");
663
                    //Intent i = new Intent(LoginActivity.this, MobileNumber.class);
664
                   // i.putExtra("displayView", "7");
665
                   // startActivity(i);
666
            }
667
            else{*/
668
            Intent i = new Intent(LoginActivity.this,MainActivity.class);
669
            i.putExtra("displayView","0");
670
            startActivity(i);
671
        }
672
    }
673
 
674
 
675
    public final boolean isInternetOn() {
676
 
677
        ConnectivityManager connection =
678
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);
679
 
680
        if ( connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
681
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
682
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
683
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
684
 
685
            return true;
686
 
687
        } else if (
688
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
689
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
690
 
691
            return false;
692
        }
693
        return false;
694
    }
695
    class NotificationOpenedData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
696
 
697
        @Override
698
        protected void onPreExecute() {
699
            super.onPreExecute();
700
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
701
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
702
            t.send(new HitBuilders.EventBuilder()
703
                    .setCategory("Notification")
704
                    .setAction("Notification Opened Login")
705
                    .setLabel("For User Id " + userData.getString("id","0"))
706
                    .build());
707
        }
708
 
709
        @Override
710
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
711
 
712
            try {
713
                HttpClient httpclient = new DefaultHttpClient();
714
                HttpPost httppost = new HttpPost(apiData.getString("notication.data.url","http://api.profittill.com/pushnotifications/add"));
715
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
716
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
717
                HttpResponse response = httpclient.execute(httppost);
718
                HttpEntity entity = response.getEntity();
719
                int status = response.getStatusLine().getStatusCode();
720
 
721
                if(status == 200){
722
                    Log.d("Notification Opened","Notication opened and sent to server");
723
                    Log.d("ResponseCode GCM ",status+"");
724
                } else {
725
                    Log.d("ResponseCode GCM ",status+"");
726
                }
727
 
728
                nameValuePairsGcm.clear();
729
                Log.e("pass 1", "connection success ");
730
            } catch (Exception e) {
731
                Log.e("Fail 1", e.toString());
732
 
733
            }
734
            return "success";
735
        }
736
 
737
        @Override
738
        protected void onPostExecute(String result) {
739
            super.onPostExecute(result);
740
            Log.d("Notification Opened","Notication opened and login page");
741
        }
742
    }
743
 
744
    class pushApkData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
745
 
746
        @Override
747
        protected void onPreExecute() {
748
            super.onPreExecute();
749
        }
750
 
751
        @Override
752
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
753
            try {
754
                HttpClient httpclient = new DefaultHttpClient();
755
                HttpPost httppost = new HttpPost("http://api.profittill.com/devices/add");
756
                //HttpPost httppost = new HttpPost(ProfitTillConstants.Push_Url);
757
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
758
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
759
                HttpResponse response = httpclient.execute(httppost);
760
                HttpEntity entity = response.getEntity();
761
                int status = response.getStatusLine().getStatusCode();
762
                if(status == 200){
763
                    return "success";
764
                } else {
765
                    return "failure";
766
                }
767
            }
768
            catch (Exception e) {
769
                e.printStackTrace();
770
                return null;
771
            }
772
        }
773
        @Override
774
        protected void onPostExecute(String result) {
775
            super.onPostExecute(result);
776
            if(userData.getString("fcm_token_sent","false").equalsIgnoreCase("false")){
777
                new gcmPushData().execute(msg);
778
            }
779
 
780
        }
781
    }
782
}
783