Subversion Repositories SmartDukaan

Rev

Rev 22381 | Rev 23185 | 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() {
246
        if (mConnectionResult.hasResolution()) {
247
            try {
248
                mIntentInProgress = true;
249
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
22831 rajender 250
            }
251
            catch (IntentSender.SendIntentException e) {
22131 rajender 252
                e.printStackTrace();
253
                TestinAgent.uploadException(this,"Exception in Resolve sign in error", new Exception());
254
                mIntentInProgress = false;
22831 rajender 255
                mGoogleApiClient.connect();
22131 rajender 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();
22831 rajender 380
                    HttpPost httppost = new HttpPost(apiData.getString("Web_Api_Login","http://app.profitmandi.com/apis/user/googleLogin"));
22131 rajender 381
                    StringEntity se = new StringEntity(json);
382
                    httppost.setEntity(se);
383
                    httppost.setHeader("Content-type", "application/json");
384
                    HttpResponse response = httpclient.execute(httppost);
385
                    HttpEntity entity = response.getEntity();
386
                    JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
387
                    JSONObject jobj= jObjGmail.getJSONObject("response");
388
                    registered=jobj.getString("registered");
389
                    if(!registered.equalsIgnoreCase(null)) {
390
                        String token = jobj.getString("token");
391
                        Log.d("token",token);
392
                        userDataEditor.putString("token", token);
22381 rajender 393
                        userDataEditor.putString("email", Plus.AccountApi.getAccountName(mGoogleApiClient));
22131 rajender 394
                        userDataEditor.putString("registered", registered);
395
                        userDataEditor.putString("type", "google");
396
                        userDataEditor.commit();
397
                    }
398
                    else{
399
 
400
                    }
401
                }
402
                else{
403
                    return "failure";
404
                }
405
            }
406
            catch (IOException transientEx) {
407
                Log.e("InputOutput", transientEx.toString());
408
 
409
            }
410
            catch (UserRecoverableAuthException e) {
411
                Log.d("Here","Here " + e.getMessage());
412
                Intent recover = e.getIntent();
413
                startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
414
            }
415
            catch (GoogleAuthException authEx) {
416
                Log.e("AuthEX", authEx.toString());
417
            }
418
            catch (Exception e) {
419
                Log.e("Exception main", e.toString());
420
            }
421
 
422
            return registered;
423
        }
424
        @Override
425
        protected void onPostExecute(String result){
426
            super.onPostExecute(result);
427
 
428
            try {
429
                if (userData.getString("registered",null) == null)  {
430
                    if(mGoogleApiClient.isConnected()) {
431
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
432
                        mGoogleApiClient.disconnect();
433
                        userDataEditor.clear().commit();
434
                    }
435
                    else{
436
                        userDataEditor.clear().commit();
437
                    }
438
                    if(pDlg!=null){
439
                        pDlg.dismiss();
440
                    }
441
                }
442
                else{
443
                    new AuthTokenChange().execute();
444
                }
445
            }
446
            catch (Exception e){
447
                e.printStackTrace();
448
            }
449
        }}
22381 rajender 450
     class AuthTokenChange extends AsyncTask<String, Integer, String> {
22131 rajender 451
 
452
        @Override
453
        protected void onPreExecute() {
454
 
455
            super.onPreExecute();
456
        }
457
 
458
        @Override
459
        protected String doInBackground(String... params) {
460
            try {
461
                HttpClient httpclient = new DefaultHttpClient();
22831 rajender 462
                HttpGet httpget = new HttpGet(apiData.getString("Web_Api_Tokendetail","http://app.profitmandi.com/apis/user/detail/token"));
22131 rajender 463
                //HttpGet httpget = new HttpGet(ProfitTillConstants.Web_Api + "/user/token-info");
464
                httpget.setHeader("Auth-Token", userData.getString("token", ""));
465
                HttpResponse response = httpclient.execute(httpget);
466
                HttpEntity entity = response.getEntity();
467
                int status = response.getStatusLine().getStatusCode();
468
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
469
                Log.d("Json",String.valueOf(jObjGmail));
470
                return String.valueOf(jObjGmail);
471
 
472
            } catch (UnsupportedEncodingException e) {
473
                e.printStackTrace();
474
            } catch (IOException e) {
475
                e.printStackTrace();
476
            } catch (JSONException e) {
477
                e.printStackTrace();
478
            }
479
            return null;
480
        }
481
 
482
        @Override
483
        protected void onPostExecute(String result) {
484
            super.onPostExecute(result);
485
            try {
486
                JSONObject jsonObject = new JSONObject(result);
487
                JSONObject jobj=jsonObject.getJSONObject("response");
488
                String userStatus=jobj.getString("userStatus");
489
                userDataEditor.putString("userStatus",userStatus);
490
                userDataEditor.commit();
491
                if(!(userData.getString("userStatus","").equals("notRegistered"))) {
492
                    String user_id = jobj.getString("userId");
493
                    userDataEditor.putString("id", user_id);
494
                    userDataEditor.commit();
495
                    if(!(userData.getString("id", "").equals(""))){
496
                        UtilityFunctions utf = new UtilityFunctions();
497
                        new pushApkData().execute(utf.getDeviceInformation(getApplicationContext()));
22831 rajender 498
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
499
                        i.putExtra("displayView","0");
500
                        startActivity(i);
22131 rajender 501
                    }
502
                    else{
503
                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
504
                        i.putExtra("displayView","0");
505
                        startActivity(i);
506
                    }
507
                }
508
                else{
509
                    Intent i = new Intent(LoginActivity.this,MainActivity.class);
510
                    i.putExtra("displayView","0");
511
                    startActivity(i);
512
                }
513
 
514
            }
515
            catch (JSONException e) {
516
                e.printStackTrace();
517
            }
518
        }
519
    }
520
    boolean doubleBackToExitPressedOnce = false;
521
    @Override
522
    public void onBackPressed() {
523
        new AlertDialog.Builder(this)
524
                .setIcon(R.drawable.symbol)
525
                .setTitle("Exit!")
526
                .setMessage("Are you sure you want to close?")
527
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
528
                {
529
                    @Override
530
                    public void onClick(DialogInterface dialog, int which) {
531
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
532
                        startMain.addCategory(Intent.CATEGORY_HOME);
533
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
534
                        startActivity(startMain);
535
                    }
536
                })
537
                .setNegativeButton("No", null)
538
                .show();
539
    }
540
 
541
    private void registerInBackground() {
542
        new AsyncTask<Void, Void, String>() {
543
            @Override
544
            protected String doInBackground(Void... params) {
545
 
546
                if (fcm == null) {
547
                    regId =FirebaseInstanceId.getInstance().getToken();
548
                    Log.d("RegisterActivity", "registerInBackground - regId: "
549
                            + regId);
550
                    msg = "Device registered";
551
                }
552
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
553
                return msg;
554
            }
555
 
556
            @Override
557
            protected void onPostExecute(String msg) {
558
            }
559
        }.execute(null, null, null);
560
    }
561
 
562
    public String registerGCM() {
563
        regId = getRegistrationId(context);
564
        registerInBackground();
565
        return regId;
566
    }
567
 
568
    private String getRegistrationId(Context context) {
569
 
570
        String registrationId = userData.getString("gcm_regid", "");
571
        if (registrationId.isEmpty()) {
572
            Log.i(TAG, "Registration not found.");
573
            return "";
574
        }
575
        return registrationId;
576
    }
577
 
578
    class gcmPushData extends AsyncTask<String, Integer, String> {
579
 
580
        @Override
581
        protected void onPreExecute() {
582
            super.onPreExecute();
583
            MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
584
            MixpanelAPI.People people = mixpanel.getPeople();
585
            JSONObject props = new JSONObject();
586
            try {
587
                mixpanel.identify(userData.getString("id",null));
588
                people.identify(userData.getString("id",null));
589
                props.put("Screen", "Logged In");
590
                people.set("$last_login",new Date());
591
                people.set("user_id" , userData.getString("id",null));
592
                mixpanel.track("Successfully Logged In", props);
593
            } catch (JSONException e) {
594
                e.printStackTrace();
595
            }
596
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
597
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
598
            t.set("&uid",userData.getString("id",null));
599
            t.send(new HitBuilders.EventBuilder()
600
                    .setCategory("Login ")
601
                    .setAction("Login Successful")
602
                    .setLabel("Successful for User" +userData.getString("id",null))
603
                    .build());
604
        }
605
 
606
        @Override
607
        protected String doInBackground(String... arg0) {
608
            String id=null;
609
            try {
610
                HttpClient httpclient = new DefaultHttpClient();
22831 rajender 611
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url","http://api.profittill.com/gcm_users/add"));
22131 rajender 612
                //HttpPost httppost = new HttpPost(ProfitTillConstants.gcm_url);
613
                nameValuePairsGcm = new ArrayList<>();
614
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
615
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid",regId));
616
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
617
                nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id", null)));
618
                nameValuePairsGcm.add(new BasicNameValuePair("notification_type","fcm"));
619
                nameValuePairsGcm.add(new BasicNameValuePair("device_message",arg0[0]));
620
                nameValuePairsGcm.add(new BasicNameValuePair("androidid",UtilityFunctions.androidId(LoginActivity.this)));
621
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
622
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
623
                HttpResponse response = httpclient.execute(httppost);
624
                HttpEntity entity = response.getEntity();
625
                int status = response.getStatusLine().getStatusCode();
626
 
627
                if(status == 200){
628
                    Log.d("ResponseCode GCM",status+"");
629
                    userDataEditor.putString("fcm_token_sent", "true");
630
                    userDataEditor.commit();
631
                } else {
632
                    Log.d("ResponseCode GCM",status+"");
633
                }
634
 
635
                nameValuePairsGcm.clear();
636
                Log.e("pass 1", "connection success ");
637
            } catch (Exception e) {
638
                Log.e("Fail 1", e.toString());
639
 
640
            }
641
            return id;
642
        }
643
 
644
        @Override
645
        protected void onPostExecute(String result) {
646
            super.onPostExecute(result);
647
            if(pDlg!=null){
648
                pDlg.dismiss();
649
            }
650
            userDataEditor.putString("gcm_regid", regId);
651
            userDataEditor.commit();
652
 
653
            String check = userData.getString("message","");
654
            /* if(userData.getString("docsSubmitted","").equalsIgnoreCase("true")){
655
               // Intent i = new Intent(LoginActivity.this, PendingActivity.class);
656
               // startActivity(i);
657
            }
658
            else  if(userData.getString("referralCodeRequired","").equalsIgnoreCase("true")){
659
                Log.d("In if","in if" +inviteD.getString("referrerCode","").equalsIgnoreCase("") + inviteD  .getString("referrerCode","") );
660
                //Intent i = new Intent(LoginActivity.this, BasicInformation.class);
661
                 //startActivity(i);
662
            }
663
            else if(check.equalsIgnoreCase("true")){
664
                    Log.d("In if","in else");
665
                    //Intent i = new Intent(LoginActivity.this, MobileNumber.class);
666
                   // i.putExtra("displayView", "7");
667
                   // startActivity(i);
668
            }
669
            else{*/
22831 rajender 670
 
22131 rajender 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();
22831 rajender 755
                HttpPost httppost = new HttpPost(apiData.getString("devices_info","http://api.profittill.com/devices/add"));
22131 rajender 756
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
757
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
758
                HttpResponse response = httpclient.execute(httppost);
759
                HttpEntity entity = response.getEntity();
760
                int status = response.getStatusLine().getStatusCode();
761
                if(status == 200){
762
                    return "success";
763
                } else {
764
                    return "failure";
765
                }
766
            }
767
            catch (Exception e) {
768
                e.printStackTrace();
769
                return null;
770
            }
771
        }
772
        @Override
773
        protected void onPostExecute(String result) {
774
            super.onPostExecute(result);
775
            if(userData.getString("fcm_token_sent","false").equalsIgnoreCase("false")){
776
                new gcmPushData().execute(msg);
777
            }
778
 
779
        }
780
    }
781
}
782