Subversion Repositories SmartDukaan

Rev

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;
22831 rajender 5
import android.app.FragmentManager;
22131 rajender 6
import android.app.ProgressDialog;
7
import android.content.Context;
8
import android.content.DialogInterface;
9
import android.content.Intent;
10
import android.content.IntentSender;
11
import android.content.SharedPreferences;
12
import android.content.pm.PackageManager;
13
import android.content.res.Configuration;
14
import android.net.ConnectivityManager;
15
import android.net.Uri;
16
import android.os.AsyncTask;
17
import android.os.Build;
18
import android.os.Bundle;
19
import android.support.v4.app.ActivityCompat;
20
import android.support.v4.content.ContextCompat;
21
import android.support.v7.app.ActionBarActivity;
22
import android.telephony.TelephonyManager;
23
import android.text.TextUtils;
24
import android.util.Log;
25
import android.view.Menu;
26
import android.view.MenuItem;
27
import android.view.View;
28
import android.widget.ImageButton;
29
import android.widget.Toast;
30
 
31
import com.google.android.gms.analytics.HitBuilders;
32
import com.google.android.gms.analytics.Tracker;
33
import com.google.android.gms.auth.GoogleAuthException;
34
import com.google.android.gms.auth.GoogleAuthUtil;
35
import com.google.android.gms.auth.UserRecoverableAuthException;
36
import com.google.android.gms.common.ConnectionResult;
37
import com.google.android.gms.common.GooglePlayServicesUtil;
38
import com.google.android.gms.common.Scopes;
39
import com.google.android.gms.common.api.GoogleApiClient;
40
import com.google.android.gms.common.api.ResultCallback;
41
import com.google.android.gms.common.api.Status;
42
import com.google.android.gms.plus.Plus;
43
import com.google.firebase.iid.FirebaseInstanceId;
44
import com.mixpanel.android.mpmetrics.MixpanelAPI;
45
import com.saholic.profittill.Constants.ProfitTillConstants;
46
import com.saholic.profittill.R;
47
import com.saholic.profittill.Utils.UtilityFunctions;
48
import com.testin.agent.TestinAgent;
49
 
50
import org.apache.http.HttpEntity;
51
import org.apache.http.HttpResponse;
52
import org.apache.http.NameValuePair;
53
import org.apache.http.client.HttpClient;
54
import org.apache.http.client.entity.UrlEncodedFormEntity;
55
import org.apache.http.client.methods.HttpGet;
56
import org.apache.http.client.methods.HttpPost;
57
import org.apache.http.entity.StringEntity;
58
import org.apache.http.impl.client.DefaultHttpClient;
59
import org.apache.http.message.BasicNameValuePair;
60
import org.apache.http.util.EntityUtils;
61
import org.json.JSONException;
62
import org.json.JSONObject;
63
 
64
import java.io.IOException;
65
import java.io.UnsupportedEncodingException;
22831 rajender 66
import java.net.URL;
22131 rajender 67
import java.util.ArrayList;
68
import java.util.Date;
69
 
70
public class LoginActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
71
    public GoogleApiClient mGoogleApiClient;
72
    String scope = "oauth2:" + Scopes.PLUS_LOGIN +" " +Scopes.PLUS_ME + " " + Scopes.EMAIL;
73
    private boolean mIntentInProgress;
74
    private boolean mSignInClicked;
75
    private ConnectionResult mConnectionResult;
76
    private static final int RC_SIGN_IN = 0;
77
    public static final int REQUEST_CODE_TOKEN_AUTH =1;
78
    ArrayList<NameValuePair> nameValuePairsGcm;
79
    SharedPreferences userData;
80
    SharedPreferences apiData;
81
    SharedPreferences.Editor inviteDataEditor;
82
    SharedPreferences inviteData;
83
    boolean FLAG=false;
84
    SharedPreferences.Editor userDataEditor;
85
    SharedPreferences.Editor apiSettingsEditor;
86
    SharedPreferences inviteD;
87
    SharedPreferences.Editor inviteDEditor;
88
    ImageButton googlelogin;
89
    String mobile;
90
    MixpanelAPI mixpanel;
91
    FirebaseInstanceId fcm;
92
    Context context;
93
    String regId;
94
    String msg = "";
95
    public static final int   READ_Token_PERMISSION=101;
96
    static final String TAG = "Register Activity";
97
    private boolean PermissionIngranted=false;
98
    @Override
99
 
100
    protected void onCreate(Bundle savedInstanceState) {
101
 
102
        context = getApplicationContext();
103
        mixpanel= MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
104
        super.onCreate(savedInstanceState);
105
        setContentView(R.layout.activity_login);
106
        TestinAgent.init(this);
107
        getSupportActionBar().hide();
108
        requestToken();
109
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
110
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
111
        userDataEditor = userData.edit();
112
        apiSettingsEditor = apiData.edit();
113
        inviteData = context.getSharedPreferences("Invite_Data", Context.MODE_PRIVATE);
114
        inviteDataEditor = inviteData.edit();
115
        inviteD = getApplicationContext().getSharedPreferences("Invite", MODE_PRIVATE);
116
        inviteDEditor = inviteD.edit();
117
        googlelogin =(ImageButton)findViewById(R.id.google_login_button);
118
        if(getIntent().getAction()=="Login"){
119
            nameValuePairsGcm = new ArrayList<>();
120
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
121
            nameValuePairsGcm.add(new BasicNameValuePair("result","login"));
122
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp",UtilityFunctions.notificationDate()));
123
            getIntent().getExtras().remove("cid");
124
            new NotificationOpenedData().execute(nameValuePairsGcm);
125
        }
126
 
127
        else if(getIntent().getAction()=="31"){
128
            String emailURL = String.valueOf(getIntent().getData());
129
            Uri url = Uri.parse(emailURL);
130
            String campaignId = url.getQueryParameter("campaign");
131
            if(url.getQueryParameter("intent_type").equalsIgnoreCase("url")) {
132
                Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
133
                        GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
134
                t.send(new HitBuilders.EventBuilder()
135
                        .setCategory("Message/Email")
136
                        .setAction("Message/Email Opened For User Id " + UtilityFunctions.campaignUserId(url))
137
                        .setLabel("Campaign Id " + campaignId)
138
                        .build());
139
                nameValuePairsGcm = new ArrayList<>();
140
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", UtilityFunctions.campaignUserId(url)));
141
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
142
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
143
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
144
                new NotificationOpenedData().execute(nameValuePairsGcm);
145
            }
146
            else{
147
                nameValuePairsGcm = new ArrayList<>();
148
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id","")));
149
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
150
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
151
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
152
                new NotificationOpenedData().execute(nameValuePairsGcm);
153
            }
154
        }
155
        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
156
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
157
        t.setScreenName("Login Screen");
158
        t.send(new HitBuilders.ScreenViewBuilder().build());
159
 
160
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
161
        JSONObject props = new JSONObject();
162
        try {
163
            props.put("Screen", "Login Screen");
164
            mixpanel.track("Login Page", props);
165
        } catch (JSONException e) {
166
            e.printStackTrace();
167
        }
168
        googlelogin.setOnClickListener(new View.OnClickListener() {
169
            @Override
170
            public void onClick(View v) {
171
                if(isInternetOn()) {
172
                    if (TextUtils.isEmpty(regId)) {
173
                        regId = registerGCM();
174
                        Log.d("RegisterActivity", "GCM RegId: " + regId);
175
                    } else {
176
                    }
177
                    signInWithGplus();
178
                }
179
                else{
180
                    Toast.makeText(getApplicationContext(),"Sorry your internet is not working. Please check again",Toast.LENGTH_SHORT).show();
181
                }
182
            }
183
        });
184
 
185
 
186
        mGoogleApiClient = new GoogleApiClient.Builder(this)
187
                .addConnectionCallbacks(this)
188
                .addOnConnectionFailedListener(this).addApi(Plus.API)
189
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();
190
    }
191
    public void requestToken(){
192
        try{
193
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
194
                if (ContextCompat.checkSelfPermission(this,
195
                        Manifest.permission.GET_ACCOUNTS)
196
                        != PackageManager.PERMISSION_GRANTED) {
197
                    ActivityCompat.requestPermissions(LoginActivity.this,
198
                            new String[]{Manifest.permission.GET_ACCOUNTS},
199
                            READ_Token_PERMISSION);
200
                } else {
201
                    PermissionIngranted = true;
202
                }
203
            } else {
204
                PermissionIngranted = true;
205
            }
206
 
207
        }
208
        catch (Exception e){
209
            e.printStackTrace();
210
        }
211
    }
212
 
213
    private void signInWithGplus() {
214
        if (!mGoogleApiClient.isConnecting()) {
215
            mSignInClicked = true;
216
            resolveSignInError();
217
        }
218
    }
219
 
220
    @Override
221
    public boolean onCreateOptionsMenu(Menu menu) {
222
        // Inflate the menu; this adds items to the action bar if it is present.
223
        getMenuInflater().inflate(R.menu.menu_login, menu);
224
        return true;
225
    }
226
 
227
    @Override
228
    public boolean onOptionsItemSelected(MenuItem item) {
229
        // Handle action bar item clicks here. The action bar will
230
        // automatically handle clicks on the Home/Up button, so long
231
        // as you specify a parent activity in AndroidManifest.xml.
232
        int id = item.getItemId();
233
 
234
        //noinspection SimplifiableIfStatement
235
        if (id == R.id.action_settings) {
236
            return true;
237
        }
238
 
239
        return super.onOptionsItemSelected(item);
240
    }
241
 
242
    /**
243
     * Method to resolve any signin errors
244
     * */
245
    private void resolveSignInError() {
23185 rajender 246
        if (mConnectionResult != null) {
22131 rajender 247
        if (mConnectionResult.hasResolution()) {
248
            try {
249
                mIntentInProgress = true;
250
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
22831 rajender 251
            }
252
            catch (IntentSender.SendIntentException e) {
22131 rajender 253
                e.printStackTrace();
254
                TestinAgent.uploadException(this,"Exception in Resolve sign in error", new Exception());
255
                mIntentInProgress = false;
22831 rajender 256
                mGoogleApiClient.connect();
22131 rajender 257
                revokeGplusAccess();
258
            }
259
        }
23185 rajender 260
    }}
22131 rajender 261
 
262
    /**
263
     * Revoking access from google
264
     * */
265
    private void revokeGplusAccess() {
266
        if (mGoogleApiClient.isConnected()) {
267
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
268
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
269
                    .setResultCallback(new ResultCallback<Status>() {
270
                        @Override
271
                        public void onResult(Status arg0) {
272
                            Log.e(TAG, "User access revoked!");
273
                            mGoogleApiClient.connect();
274
                            //updateUI(false);
275
                        }
276
 
277
                    });
278
        }
279
    }
280
 
281
    @Override
282
    public void onConfigurationChanged(Configuration newConfig) {
283
        super.onConfigurationChanged(newConfig);
284
    }
285
 
286
    protected void onStart() {
287
        super.onStart();
288
        mGoogleApiClient.connect();
289
    }
290
 
291
    protected void onStop() {
292
        super.onStop();
293
        if (mGoogleApiClient.isConnected()) {
294
            mGoogleApiClient.disconnect();
295
 
296
        }
297
    }
298
 
299
    @Override
300
    public void onConnectionFailed(ConnectionResult result) {
301
        if (!result.hasResolution()) {
302
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,0).show();
303
            return;
304
        }
305
 
306
        if (!mIntentInProgress) {
307
            mConnectionResult = result;
308
            if (mSignInClicked) {
309
                resolveSignInError();
310
            }
311
        }
312
    }
313
 
314
    @Override
315
    protected void onActivityResult(int requestCode, int responseCode,
316
                                    Intent intent) {
317
        if (requestCode == RC_SIGN_IN) {
318
            if (responseCode != RESULT_OK) {
319
                mSignInClicked = false;
320
            }
321
 
322
            mIntentInProgress = false;
323
 
324
            if (!mGoogleApiClient.isConnecting()) {
325
                mGoogleApiClient.connect();
326
            }
327
        }
328
        else if (requestCode==REQUEST_CODE_TOKEN_AUTH &&responseCode==RESULT_OK){
329
            getAccessToken();
330
        }
331
    }
332
 
333
    private void getAccessToken() {
334
        new getToken().execute();
335
 
336
    }
337
 
338
    @Override
339
    public void onConnectionSuspended(int arg0) {
340
        mGoogleApiClient.connect();
341
    }
342
    @Override
343
    public void onConnected(Bundle arg0) {
344
        mSignInClicked=false;
345
        getAccessToken();
346
    }
347
    private void showProgressDialog()
348
    {
349
        pDlg = new ProgressDialog(LoginActivity.this);
350
        pDlg.setMessage("Logging In");
351
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
352
        pDlg.setCancelable(false);
353
        pDlg.show();
354
 
355
    }
356
    private ProgressDialog pDlg = null;
357
    class getToken extends AsyncTask<String, Integer, String> {
358
 
359
        @Override
360
        protected void onPreExecute() {
361
            showProgressDialog();
362
        }
363
        @Override
364
        protected String doInBackground(String... params) {
365
            String registered=null;
366
            String googletoken = null;
367
            Bundle appActivities = new Bundle();
368
            appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,"MainActivity");
369
            try {
370
                googletoken = GoogleAuthUtil.getToken(
371
                        LoginActivity.this,
372
                        Plus.AccountApi.getAccountName(mGoogleApiClient),
373
                        scope,appActivities);
374
                if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
375
                    HttpClient httpclient = new DefaultHttpClient();
376
                    String json = "";
377
                    JSONObject jsonObject = new JSONObject();
378
                    jsonObject.put("type", "GOOGLE");
379
                    jsonObject.put("token", googletoken);
380
                    json = jsonObject.toString();
22831 rajender 381
                    HttpPost httppost = new HttpPost(apiData.getString("Web_Api_Login","http://app.profitmandi.com/apis/user/googleLogin"));
22131 rajender 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();
22831 rajender 463
                HttpGet httpget = new HttpGet(apiData.getString("Web_Api_Tokendetail","http://app.profitmandi.com/apis/user/detail/token"));
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()));
22831 rajender 499
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
500
                        i.putExtra("displayView","0");
501
                        startActivity(i);
22131 rajender 502
                    }
503
                    else{
504
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
505
                        i.putExtra("displayView","0");
506
                        startActivity(i);
507
                    }
508
                }
509
                else{
510
                    Intent i = new Intent(LoginActivity.this,MainActivity.class);
511
                    i.putExtra("displayView","0");
512
                    startActivity(i);
513
                }
514
 
515
            }
516
            catch (JSONException e) {
517
                e.printStackTrace();
518
            }
519
        }
520
    }
521
    boolean doubleBackToExitPressedOnce = false;
522
    @Override
523
    public void onBackPressed() {
524
        new AlertDialog.Builder(this)
525
                .setIcon(R.drawable.symbol)
526
                .setTitle("Exit!")
527
                .setMessage("Are you sure you want to close?")
528
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
529
                {
530
                    @Override
531
                    public void onClick(DialogInterface dialog, int which) {
532
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
533
                        startMain.addCategory(Intent.CATEGORY_HOME);
534
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
535
                        startActivity(startMain);
536
                    }
537
                })
538
                .setNegativeButton("No", null)
539
                .show();
540
    }
541
 
542
    private void registerInBackground() {
543
        new AsyncTask<Void, Void, String>() {
544
            @Override
545
            protected String doInBackground(Void... params) {
546
 
547
                if (fcm == null) {
548
                    regId =FirebaseInstanceId.getInstance().getToken();
549
                    Log.d("RegisterActivity", "registerInBackground - regId: "
550
                            + regId);
551
                    msg = "Device registered";
552
                }
553
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
554
                return msg;
555
            }
556
 
557
            @Override
558
            protected void onPostExecute(String msg) {
559
            }
560
        }.execute(null, null, null);
561
    }
562
 
563
    public String registerGCM() {
564
        regId = getRegistrationId(context);
565
        registerInBackground();
566
        return regId;
567
    }
568
 
569
    private String getRegistrationId(Context context) {
570
 
571
        String registrationId = userData.getString("gcm_regid", "");
572
        if (registrationId.isEmpty()) {
573
            Log.i(TAG, "Registration not found.");
574
            return "";
575
        }
576
        return registrationId;
577
    }
578
 
579
    class gcmPushData extends AsyncTask<String, Integer, String> {
580
 
581
        @Override
582
        protected void onPreExecute() {
583
            super.onPreExecute();
584
            MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
585
            MixpanelAPI.People people = mixpanel.getPeople();
586
            JSONObject props = new JSONObject();
587
            try {
588
                mixpanel.identify(userData.getString("id",null));
589
                people.identify(userData.getString("id",null));
590
                props.put("Screen", "Logged In");
591
                people.set("$last_login",new Date());
592
                people.set("user_id" , userData.getString("id",null));
593
                mixpanel.track("Successfully Logged In", props);
594
            } catch (JSONException e) {
595
                e.printStackTrace();
596
            }
597
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
598
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
599
            t.set("&uid",userData.getString("id",null));
600
            t.send(new HitBuilders.EventBuilder()
601
                    .setCategory("Login ")
602
                    .setAction("Login Successful")
603
                    .setLabel("Successful for User" +userData.getString("id",null))
604
                    .build());
605
        }
606
 
607
        @Override
608
        protected String doInBackground(String... arg0) {
609
            String id=null;
610
            try {
611
                HttpClient httpclient = new DefaultHttpClient();
22831 rajender 612
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url","http://api.profittill.com/gcm_users/add"));
22131 rajender 613
                //HttpPost httppost = new HttpPost(ProfitTillConstants.gcm_url);
614
                nameValuePairsGcm = new ArrayList<>();
615
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
616
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid",regId));
617
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
618
                nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id", null)));
619
                nameValuePairsGcm.add(new BasicNameValuePair("notification_type","fcm"));
620
                nameValuePairsGcm.add(new BasicNameValuePair("device_message",arg0[0]));
621
                nameValuePairsGcm.add(new BasicNameValuePair("androidid",UtilityFunctions.androidId(LoginActivity.this)));
622
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
623
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
624
                HttpResponse response = httpclient.execute(httppost);
625
                HttpEntity entity = response.getEntity();
626
                int status = response.getStatusLine().getStatusCode();
627
 
628
                if(status == 200){
629
                    Log.d("ResponseCode GCM",status+"");
630
                    userDataEditor.putString("fcm_token_sent", "true");
631
                    userDataEditor.commit();
632
                } else {
633
                    Log.d("ResponseCode GCM",status+"");
634
                }
635
 
636
                nameValuePairsGcm.clear();
637
                Log.e("pass 1", "connection success ");
638
            } catch (Exception e) {
639
                Log.e("Fail 1", e.toString());
640
 
641
            }
642
            return id;
643
        }
644
 
645
        @Override
646
        protected void onPostExecute(String result) {
647
            super.onPostExecute(result);
648
            if(pDlg!=null){
649
                pDlg.dismiss();
650
            }
651
            userDataEditor.putString("gcm_regid", regId);
652
            userDataEditor.commit();
653
 
654
            String check = userData.getString("message","");
655
            /* if(userData.getString("docsSubmitted","").equalsIgnoreCase("true")){
656
               // Intent i = new Intent(LoginActivity.this, PendingActivity.class);
657
               // startActivity(i);
658
            }
659
            else  if(userData.getString("referralCodeRequired","").equalsIgnoreCase("true")){
660
                Log.d("In if","in if" +inviteD.getString("referrerCode","").equalsIgnoreCase("") + inviteD  .getString("referrerCode","") );
661
                //Intent i = new Intent(LoginActivity.this, BasicInformation.class);
662
                 //startActivity(i);
663
            }
664
            else if(check.equalsIgnoreCase("true")){
665
                    Log.d("In if","in else");
666
                    //Intent i = new Intent(LoginActivity.this, MobileNumber.class);
667
                   // i.putExtra("displayView", "7");
668
                   // startActivity(i);
669
            }
670
            else{*/
22831 rajender 671
 
22131 rajender 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();
22831 rajender 756
                HttpPost httppost = new HttpPost(apiData.getString("devices_info","http://api.profittill.com/devices/add"));
22131 rajender 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