Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
23410 tejbeer 1
package com.saholic.profittill;
2
 
3
import android.Manifest;
4
import android.annotation.SuppressLint;
5
import android.app.AlertDialog;
6
import android.app.FragmentManager;
7
import android.app.ProgressDialog;
8
import android.content.Context;
9
import android.content.DialogInterface;
10
import android.content.Intent;
11
import android.content.SharedPreferences;
12
import android.content.pm.PackageInfo;
13
import android.content.pm.PackageManager;
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.annotation.NonNull;
20
import android.support.v4.app.ActivityCompat;
21
import android.support.v4.content.ContextCompat;
22
import android.support.v7.app.ActionBarActivity;
23
import android.support.v7.app.AppCompatActivity;
24
import android.telephony.TelephonyManager;
25
import android.util.Log;
26
import android.view.Menu;
27
import android.view.MenuItem;
28
import android.view.View;
29
import android.view.ViewGroup;
30
import android.widget.ProgressBar;
31
import android.widget.Toast;
32
 
33
import com.google.android.gms.analytics.HitBuilders;
34
import com.google.android.gms.analytics.Tracker;
35
import com.google.android.gms.common.ConnectionResult;
36
import com.google.android.gms.common.api.GoogleApiClient;
37
import com.google.android.gms.plus.Plus;
38
import com.google.firebase.iid.FirebaseInstanceId;
39
import com.saholic.profittill.Constants.ProfitTillConstants;
40
import com.saholic.profittill.Utils.UtilityFunctions;
41
import com.saholic.profittill.main.DealsHomeFragment;
42
import com.saholic.profittill.main.GoogleAnalyticsTracker;
43
import com.saholic.profittill.main.HowItWorks;
44
import com.saholic.profittill.main.LoginActivity;
45
import com.saholic.profittill.main.MainActivity;
46
import com.saholic.profittill.main.ScreenActivity;
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.HttpPost;
55
import org.apache.http.impl.client.DefaultHttpClient;
56
import org.apache.http.message.BasicNameValuePair;
57
import org.apache.http.util.EntityUtils;
58
import org.json.JSONArray;
59
import org.json.JSONObject;
60
 
61
import java.util.ArrayList;
62
 
63
 
64
public class SplashScreen extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
65
    SharedPreferences apiData, userData, apkData;
66
    SharedPreferences.Editor apiEditor, userEditor, apkDataEditor,userDataEditor;
67
    UtilityFunctions utilityFunctions;
68
    AlertDialog dialog1;
69
    public GoogleApiClient mGoogleApiClient;
70
    AlertDialog.Builder b;
71
    ProgressBar pd;
72
    Context c;
73
    String type1;
74
    FirebaseInstanceId fcm;
75
    String regId;
76
    ArrayList<NameValuePair> apkDataListValue;
77
    ArrayList<NameValuePair> nameValuePairsGcm;
78
    public static final int READ_PHONE_STATE_PERMISSION = 100;
79
    private boolean PermissionIngranted=false;
80
    @Override
81
    protected void onCreate(Bundle savedInstanceState) {
82
        TestinAgent.init(this);
83
        super.onCreate(savedInstanceState);
84
        setContentView(R.layout.activity_splash_screen);
85
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
86
            getSupportActionBar().hide();
87
        }
88
        GIFView gifImageView = (GIFView) findViewById(R.id.gif);
89
        gifImageView.setGifImageResource(R.drawable.progressbar);
90
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
91
        apkData = getApplicationContext().getSharedPreferences("APK_Data", MODE_PRIVATE);
92
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
93
        apkDataEditor = apkData.edit();
94
        userDataEditor = userData.edit();
95
        apiEditor = apiData.edit();
96
 
97
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
98
            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, READ_PHONE_STATE_PERMISSION);
99
        }
100
        else{
101
            PermissionIngranted=true;
102
        }
103
 
104
        type1 = userData.getString("type", null);
105
        if (type1 != null && type1.equalsIgnoreCase("google")) {
106
            mGoogleApiClient = new GoogleApiClient.Builder(SplashScreen.this)
107
                    .addConnectionCallbacks(this)
108
                    .addOnConnectionFailedListener(this).addApi(Plus.API)
109
                    .addScope(Plus.SCOPE_PLUS_LOGIN).build();
110
            mGoogleApiClient.connect();
111
        }
112
        String url = "";
113
        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
114
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
115
        t.setScreenName("Splash Screen");
116
        t.send(new HitBuilders.ScreenViewBuilder().build());
117
        try {
118
            String apkVersionCode = apkData.getString("versionCode","");
119
            String apkVersionName = apkData.getString("versionName","");
120
            if(userData.getString("id","").isEmpty()) {
121
 
122
            }else {
123
                if (apkVersionCode.isEmpty()) {
124
                    utilityFunctions=new UtilityFunctions();
125
                    apkDataListValue = utilityFunctions.getDeviceInformation(this);
126
 
127
                    if(isInternetOn()) {
128
                        new pushApkData().execute();
129
                    }
130
                } else if (!(apkData.getString("checkId","blank").equalsIgnoreCase(userData.getString("id","blank")))) {
131
                    utilityFunctions=new UtilityFunctions();
132
                    apkDataListValue = utilityFunctions.getDeviceInformation(this);
133
                    if(isInternetOn()) {
134
                        new pushApkData().execute();
135
                    }
136
                } else if (Integer.parseInt(apkVersionCode) == getPackageManager().getPackageInfo(getPackageName(), 0).versionCode) {
137
 
138
                }  else {
139
                    utilityFunctions=new UtilityFunctions();
140
                    apkDataListValue = utilityFunctions.getDeviceInformation(this);
141
                    if(isInternetOn()) {
142
                        new pushApkData().execute();
143
                    }
144
                }
145
            }
146
        }catch (Exception e){
147
            e.printStackTrace();
148
        }
149
        if(isInternetOn()){
150
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
151
                requestphoneUpdates();
152
            }
153
            else{
154
                    new fetchAPISettings().execute();
155
                }
156
        }
157
        else{
158
            b= new AlertDialog.Builder(this);
159
            b.setIcon(R.drawable.interet);
160
            b.setTitle("No Internet Connection");
161
            b.setMessage("No internet connection. Please try again.");
162
            b.setCancelable(false);
163
            b.setPositiveButton("Retry", new DialogInterface.OnClickListener()
164
            {
165
                @Override
166
                public void onClick(DialogInterface dialog, int which) {
167
                    if(isInternetOn()){
168
                        new fetchAPISettings().execute();
169
                        dialog1.dismiss();
170
                    }
171
                    else{
172
                        dialog1 = b.create();
173
                        dialog1.show();
174
                    }
175
                }
176
 
177
            });
178
            b.setNegativeButton("No", new DialogInterface.OnClickListener() {
179
                @Override
180
                public void onClick(DialogInterface dialog, int which) {
181
                    finish();
182
 
183
                }
184
            });
185
            dialog1 = b.create();
186
            dialog1.show();
187
        }
188
    }
189
 
190
 
191
    private int getFirstTimeRun() throws PackageManager.NameNotFoundException {
192
        SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
193
        int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
194
        int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
195
 
196
        if (appLastBuildVersion == appCurrentBuildVersion ) {
197
            final String idCheck = userData.getString("id", null);
198
 
199
            if(idCheck != null){
200
                Intent startActivityIntent=new Intent(SplashScreen.this, MainActivity.class);
201
                Intent intent = getIntent();
202
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
203
                    Uri uri = intent.getData();
204
                    startActivityIntent.setAction("31");
205
                    startActivityIntent.setData(Uri.parse(uri.toString()));
206
                }
207
                startActivity(startActivityIntent);
208
            }
209
            else{
210
                Intent startActivityIntent=new Intent(SplashScreen.this,LoginActivity   .class);
211
                Intent intent = getIntent();
212
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
213
                    Uri uri = intent.getData();
214
                    startActivityIntent.setAction("31");
215
                    startActivityIntent.setData(Uri.parse(uri.toString()));
216
                }
217
                startActivity(startActivityIntent);
218
            }
219
            return 1;
220
        }
221
 
222
        else {
223
            appPreferences.edit().putInt("app_first_time",
224
                    appCurrentBuildVersion).apply();
225
            if (appLastBuildVersion == 0) {
226
                Intent startActivityIntent=new Intent(SplashScreen.this,  ScreenActivity.class);
227
                startActivity(startActivityIntent);
228
 
229
                }
230
            else {
231
                try{
232
                    if (mGoogleApiClient.isConnected()) {
233
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
234
                        mGoogleApiClient.disconnect();
235
                        mGoogleApiClient.connect();
236
                        userDataEditor.clear().commit();
237
                        startActivity(new Intent(SplashScreen.this,LoginActivity.class));
238
                    }
239
                    else{
240
                        if(!mGoogleApiClient.isConnected()){
241
                            userDataEditor.clear().commit();
242
                            startActivity(new Intent(SplashScreen.this, LoginActivity.class));
243
                        }
244
 
245
                    }
246
                }catch (Exception e){
247
                    userDataEditor.clear().commit();
248
                    startActivity(new Intent(SplashScreen.this, LoginActivity.class));
249
                }
250
            }
251
        }
252
        return 2;
253
    }
254
 
255
    @Override
256
    public Intent getIntent() {
257
        return super.getIntent();
258
    }
259
 
260
    @Override
261
    public void setContentView(View view, ViewGroup.LayoutParams params) {
262
        super.setContentView(view, params);
263
    }
264
 
265
    public SplashScreen() {
266
        super();
267
    }
268
 
269
    public void requestphoneUpdates(){
270
 
271
      if (ContextCompat.checkSelfPermission(SplashScreen.this,
272
              Manifest.permission.READ_PHONE_STATE)
273
              != PackageManager.PERMISSION_GRANTED) {
274
          if (ActivityCompat.shouldShowRequestPermissionRationale(SplashScreen.this,
275
                  Manifest.permission.READ_PHONE_STATE)) {
276
 
277
          } else {
278
              ActivityCompat.requestPermissions(SplashScreen.this,
279
                      new String[]{Manifest.permission.READ_PHONE_STATE},
280
                      READ_PHONE_STATE_PERMISSION);
281
          }
282
          return;
283
      }
284
  }
285
    @Override
286
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
287
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
288
        switch (requestCode){
289
 
290
            case READ_PHONE_STATE_PERMISSION:
291
                try {
292
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
293
                        PermissionIngranted = true;
294
 
295
                        if(isInternetOn()) {
296
                              new fetchAPISettings().execute();
297
 
298
        } else {
299
                b = new AlertDialog.Builder(this);
300
                b.setIcon(R.drawable.interet);
301
                b.setTitle("No Internet Connection");
302
                b.setMessage("No internet connection. Please try again.");
303
                b.setCancelable(false);
304
                b.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
305
                    @Override
306
                    public void onClick(DialogInterface dialog, int which) {
307
                        if (isInternetOn()) {
308
                            new fetchAPISettings().execute();
309
                            dialog1.dismiss();
310
                        } else {
311
                            dialog1 = b.create();
312
                            dialog1.show();
313
                        }
314
                    }
315
 
316
                });
317
        b.setNegativeButton("No", new DialogInterface.OnClickListener() {
318
            @Override
319
            public void onClick(DialogInterface dialog, int which) {
320
                finish();
321
 
322
            }
323
        });
324
        dialog1 = b.create();
325
        dialog1.show();
326
    }}
327
        else {
328
         // Toast.makeText(getApplicationContext(),"Permission is required to enter in application",Toast.LENGTH_LONG).show();
329
            PermissionIngranted = false;
330
        }
331
    }
332
    catch (Exception e){
333
        e.printStackTrace();
334
    }
335
 
336
         break;
337
        }
338
 
339
    }
340
 
341
    @Override
342
    public boolean onCreateOptionsMenu(Menu menu) {
343
        getMenuInflater().inflate(R.menu.menu_splash_screen, menu);
344
        return true;
345
    }
346
 
347
    @Override
348
    public boolean onOptionsItemSelected(MenuItem item) {
349
        int id = item.getItemId();
350
        if (id == R.id.action_settings) {
351
            return true;
352
        }
353
 
354
        return super.onOptionsItemSelected(item);
355
    }
356
 
357
    @Override
358
    public void onConnected(Bundle bundle) {
359
     requestphoneUpdates();
360
    }
361
 
362
    @Override
363
    public void onConnectionSuspended(int i) {
364
 
365
    }
366
 
367
 
368
    @Override
369
    public void onConnectionFailed(ConnectionResult connectionResult) {
370
 
371
    }
372
 
373
    class fetchAPISettings extends AsyncTask<String, Integer, JSONObject> {
374
 
375
        @Override
376
        protected void onPreExecute() {
377
            super.onPreExecute();
378
        }
379
 
380
        @Override
381
        protected JSONObject doInBackground(String... arg0) {
382
            try {
383
 
384
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
385
                HttpClient httpclient = new DefaultHttpClient();
386
                String url = ProfitTillConstants.MOBILE_API+"?t="+apkData.getString("timestamp","0")+"&imeinumber="+telephonyManager.getDeviceId();
387
                HttpPost httppost=new HttpPost(url);
388
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
389
                HttpResponse response = httpclient.execute(httppost);
390
                HttpEntity entity = response.getEntity();
391
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
392
                return jObjGmail;
393
 
394
            }
395
            catch(Exception e) {
396
                e.printStackTrace();
397
                return null;
398
 
399
            }
400
 
401
        }
402
        @Override
403
        protected void onPostExecute(JSONObject result) {
404
            super.onPostExecute(result);
405
            if(result==null){
406
                finish();
407
            }
408
            try {
409
               JSONArray objects = result.getJSONArray("settings");
410
                if(objects.length()==0){
411
                    System.out.println("Null settings array");
412
                }else {
413
                    for (int i = 0; i < objects.length(); i++) {
414
                        JSONObject jsonObject = objects.getJSONObject(i);
415
                        JSONObject j = jsonObject.getJSONObject("Mobileappsetting");
416
                        apiEditor.remove(j.getString("setting"));
417
                        apiEditor.commit();
418
                        apiEditor.putString(j.getString("setting"), j.getString("value"));
419
                        apiEditor.commit();
420
                    }
421
                }
422
                String timestamp=result.getString("t");
423
                String failureCount=result.getString("failureCount");
424
                apkDataEditor.putString("timestamp",timestamp);
425
                apkDataEditor.commit();
426
                getFirstTimeRun();
427
 
428
            }catch (Exception e){
429
                finish();
430
            }
431
        }
432
    }
433
 
434
    class pushApkData extends AsyncTask<String, Integer, String> {
435
 
436
        @Override
437
        protected void onPreExecute() {
438
            super.onPreExecute();
439
        }
440
 
441
        @Override
442
        protected String doInBackground(String... arg0) {
443
            try {
444
                HttpClient httpclient = new DefaultHttpClient();
445
                HttpPost httppost = new HttpPost(apiData.getString("devices_info","http://api.profittill.com/devices/add"));
446
                //HttpPost httppost = new HttpPost(ProfitTillConstants.Push_Url);
447
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
448
                httppost.setEntity(new UrlEncodedFormEntity(apkDataListValue));
449
                HttpResponse response = httpclient.execute(httppost);
450
                HttpEntity entity = response.getEntity();
451
                int status = response.getStatusLine().getStatusCode();
452
 
453
                if(status == 200){
454
                    apkDataEditor.putString("checkId",userData.getString("id",""));
455
                    apkDataEditor.commit();
456
                    return "success";
457
                } else {
458
                    return "failure";
459
                }
460
 
461
            } catch (Exception e) {
462
                return null;
463
 
464
            }
465
 
466
        }
467
        @Override
468
        protected void onPostExecute(String result) {
469
            super.onPostExecute(result);
470
        }
471
    }
472
 
473
 
474
    public final boolean isInternetOn() {
475
 
476
        ConnectivityManager connection =
477
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);
478
 
479
        if (    connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
480
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
481
            return true;
482
 
483
        } else if (
484
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
485
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
486
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
487
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
488
            return false;
489
        }
490
        return false;
491
    }
492
 
493
    ProgressDialog pDlg;
494
 
495
    public void registerGCM() {
496
 
497
        registerInBackground();
498
 
499
    }
500
 
501
    private void registerInBackground() {
502
        new AsyncTask<Void, Void, String>() {
503
            @Override
504
            protected String doInBackground(Void... params) {
505
                String msg = "";
506
                if (fcm == null) {
507
                    regId = FirebaseInstanceId.getInstance().getToken();
508
                    msg = "Device registered";
509
                }
510
                return msg;
511
            }
512
 
513
            @Override
514
            protected void onPostExecute(String msg) {
515
                if(userData.getString("fcm_token_sent","false").equalsIgnoreCase("false")) {
516
                    new gcmPushData().execute(msg);
517
                }
518
            }
519
        }.execute(null, null, null);
520
    }
521
 
522
 
523
    class gcmPushData extends AsyncTask<String, Integer, String> {
524
 
525
        @Override
526
        protected void onPreExecute() {
527
            super.onPreExecute();
528
        }
529
 
530
        @SuppressLint("MissingPermission")
531
        @Override
532
        protected String doInBackground(String... arg0) {
533
            String id = null;
534
            try {
535
                HttpClient httpclient = new DefaultHttpClient();
536
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url", "http://api.profittill.com/gcm_users/add"));
537
                //HttpPost httppost = new HttpPost(ProfitTillConstants.gcm_url);
538
                nameValuePairsGcm = new ArrayList<>();
539
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
540
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid", regId));
541
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber", telephonyManager.getDeviceId()));
542
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id", null)));
543
                nameValuePairsGcm.add(new BasicNameValuePair("device_message", arg0[0]));
544
                nameValuePairsGcm.add(new BasicNameValuePair("notification_type","fcm"));
545
                nameValuePairsGcm.add(new BasicNameValuePair("androidid", UtilityFunctions.androidId(SplashScreen.this)));
546
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
547
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
548
                HttpResponse response = httpclient.execute(httppost);
549
                HttpEntity entity = response.getEntity();
550
                int status = response.getStatusLine().getStatusCode();
551
 
552
                if(status == 200){
553
                    Log.d("ResponseCode GCM ",status+"");
554
                    userDataEditor.putString("fcm_token_sent", "true");
555
                    userDataEditor.commit();
556
                } else {
557
                    Log.d("ResponseCode GCM ",status+"");
558
                }
559
 
560
                nameValuePairsGcm.clear();
561
                Log.e("pass 1", "connection success ");
562
            } catch (Exception e) {
563
                Log.e("Fail 1", e.toString());
564
 
565
            }
566
            return id;
567
        }
568
 
569
 
570
        @Override
571
        protected void onPostExecute(String result) {
572
            super.onPostExecute(result);
573
            final String idCheck = userData.getString("id",null);
574
          /*  if(userData.getString("docsSubmitted","false").equalsIgnoreCase("true")){
575
                Intent i = new Intent(SplashScreen.this, PendingActivity.class);
576
                startActivity(i);
577
            }
578
         else if (userData.getString("referralCodeRequired", "false").equalsIgnoreCase("true")) {
579
                Intent startActivityIntent=new Intent(SplashScreen.this, BasicInformation.class);
580
                Intent intent = getIntent();
581
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
582
                    Uri uri = intent.getData();
583
                    startActivityIntent.setAction("31");
584
                    startActivityIntent.setData(Uri.parse(uri.toString()));
585
                }
586
                startActivity(startActivityIntent);
587
                //startActivity(new Intent(SplashScreen.this, ReferrerActivity.class));
588
            }
589
            else if (userData.getString("message", "false").equalsIgnoreCase("true")) {
590
                Intent startActivityIntent=new Intent(SplashScreen.this, MobileNumber.class);
591
                Intent intent = getIntent();
592
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
593
                    Uri uri = intent.getData();
594
                    startActivityIntent.setAction("31");
595
                    startActivityIntent.setData(Uri.parse(uri.toString()));
596
                }
597
                startActivity(startActivityIntent);
598
                //startActivity(new Intent(SplashScreen.this, MobileNumber.class));
599
            } else*/
600
             if (idCheck != null) {
601
                Intent startActivityIntent=new Intent(SplashScreen.this, MainActivity.class);
602
                Intent intent = getIntent();
603
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
604
                    Uri uri = intent.getData();
605
                    startActivityIntent.setAction("31");
606
                    startActivityIntent.setData(Uri.parse(uri.toString()));
607
                }
608
                startActivity(startActivityIntent);
609
            }
610
            else {
611
                Intent startActivityIntent=new Intent(SplashScreen.this, LoginActivity.class);
612
                Intent intent = getIntent();
613
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
614
                    Uri uri = intent.getData();
615
                    startActivityIntent.setAction("31");
616
                    startActivityIntent.setData(Uri.parse(uri.toString()));
617
                }
618
                startActivity(startActivityIntent);
619
 
620
            }
621
        }
622
    }
623
}