Subversion Repositories SmartDukaan

Rev

Rev 21480 | Rev 22381 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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