Subversion Repositories SmartDukaan

Rev

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