Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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