Subversion Repositories SmartDukaan

Rev

Rev 14991 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.saholic.profittill;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.saholic.profittill.Constants.ProfitTillConstants;
import com.saholic.profittill.main.GoogleAnalyticsTracker;
import com.saholic.profittill.main.LoginActivity;
import com.saholic.profittill.main.MainActivity;
import com.saholic.profittill.main.MobileNumber;
import com.saholic.profittill.main.ReferrerActivity;
import com.testin.agent.TestinAgent;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;


public class SplashScreen extends ActionBarActivity {
    SharedPreferences apiData, userData,apkData;
    SharedPreferences.Editor apiEditor,userEditor,apkDataEditor;

    AlertDialog dialog1;
    AlertDialog.Builder b;
    ProgressBar pd;

    ArrayList<NameValuePair> apkDataListValue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TestinAgent.init(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        getSupportActionBar().hide();
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
        apkData = getApplicationContext().getSharedPreferences("APK_Data", MODE_PRIVATE);
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
        apkDataEditor = apkData.edit();
        userEditor = userData.edit();
        apiEditor = apiData.edit();
        String url="";
        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
        t.setScreenName("Splash Screen");
        t.send(new HitBuilders.ScreenViewBuilder().build());
        try {
            String apkVersionCode = apkData.getString("versionCode","");
            String apkVersionName = apkData.getString("versionName","");
            if(userData.getString("id","").isEmpty()) {

            }else {
                if (apkVersionCode.isEmpty()) {
                    PackageManager manager = this.getPackageManager();
                    PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
                    TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                    apkDataListValue = new ArrayList<>();
                    apkDataListValue.add(new BasicNameValuePair("user_id",userData.getString("id","")));
                    apkDataListValue.add(new BasicNameValuePair("versioncode",info.versionCode+""));
                    apkDataListValue.add(new BasicNameValuePair("versionname",info.versionName+""));
                    apkDataListValue.add(new BasicNameValuePair("osversion",android.os.Build.VERSION.SDK_INT+""));
                    apkDataListValue.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
                    apkDataListValue.add(new BasicNameValuePair("manufacturer",Build.MANUFACTURER));
                    apkDataListValue.add(new BasicNameValuePair("model",Build.MODEL));
                    apkDataListValue.add(new BasicNameValuePair("brand",Build.BRAND));
                    apkDataEditor.putString("versionCode", info.versionCode + "");
                    apkDataEditor.putString("versionName", info.versionName);
                    apkDataEditor.putString("osVersion",android.os.Build.VERSION.SDK_INT+"");
                    apkDataEditor.putString("imeiNumber",telephonyManager.getDeviceId());

                    if(isInternetOn()) {
                        new pushApkData().execute();
                    }
                } else if (!(apkData.getString("checkId","blank").equalsIgnoreCase(userData.getString("id","blank")))) {
                    PackageManager manager = this.getPackageManager();
                    PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
                    TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                    apkDataListValue = new ArrayList<>();
                    apkDataListValue.add(new BasicNameValuePair("user_id",userData.getString("id","")));
                    apkDataListValue.add(new BasicNameValuePair("versioncode",info.versionCode+""));
                    apkDataListValue.add(new BasicNameValuePair("versionname",info.versionName+""));
                    apkDataListValue.add(new BasicNameValuePair("osversion",android.os.Build.VERSION.SDK_INT+""));
                    apkDataListValue.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
                    apkDataListValue.add(new BasicNameValuePair("manufacturer",Build.MANUFACTURER));
                    apkDataListValue.add(new BasicNameValuePair("model",Build.MODEL));
                    apkDataListValue.add(new BasicNameValuePair("brand",Build.BRAND));
                    apkDataEditor.putString("versionCode",info.versionCode+"");
                    apkDataEditor.putString("versionName",info.versionName);
                    apkDataEditor.putString("osVersion",android.os.Build.VERSION.SDK_INT+"");
                    apkDataEditor.putString("imeiNumber",telephonyManager.getDeviceId());
                    if(isInternetOn()) {
                        new pushApkData().execute();
                    }
                } else if (Integer.parseInt(apkVersionCode) == getPackageManager().getPackageInfo(getPackageName(), 0).versionCode) {

                }  else {
                    PackageManager manager = this.getPackageManager();
                    PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
                    TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                    apkDataListValue = new ArrayList<>();
                    apkDataListValue.add(new BasicNameValuePair("user_id",userData.getString("id","")));
                    apkDataListValue.add(new BasicNameValuePair("versioncode",info.versionCode+""));
                    apkDataListValue.add(new BasicNameValuePair("versionname",info.versionName+""));
                    apkDataListValue.add(new BasicNameValuePair("osversion",android.os.Build.VERSION.SDK_INT+""));
                    apkDataListValue.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
                    apkDataListValue.add(new BasicNameValuePair("manufacturer",Build.MANUFACTURER));
                    apkDataListValue.add(new BasicNameValuePair("model",Build.MODEL));
                    apkDataListValue.add(new BasicNameValuePair("brand",Build.BRAND));
                    apkDataEditor.putString("versionCode",info.versionCode+"");
                    apkDataEditor.putString("versionName",info.versionName);
                    apkDataEditor.putString("osVersion",android.os.Build.VERSION.SDK_INT+"");
                    apkDataEditor.putString("imeiNumber",telephonyManager.getDeviceId());
                    if(isInternetOn()) {
                        new pushApkData().execute();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        if(isInternetOn()){
                new fetchAPISettings().execute();
        }
        else{
            b= new AlertDialog.Builder(this);
            b.setMessage("No internet connection. Please try again.");
            b.setCancelable(false);
            b.setPositiveButton("Retry", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if(isInternetOn()){
                        new fetchAPISettings().execute();
                        dialog1.dismiss();
                    }
                    else{
                        dialog1 = b.create();
                        dialog1.show();
                    }
                }

            });
            b.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            });
            dialog1 = b.create();
            dialog1.show();
        }


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_splash_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    class fetchAPISettings extends AsyncTask<String, Integer, JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /*final Dialog dialog = new Dialog(getApplicationContext(), android.R.style.Theme_Translucent);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            //here we set layout of progress dialog
            dialog.setContentView(R.layout.activity_splash_internet_not_working);*/
            //bar.setVisibility(View.VISIBLE);
            //showProgressDialog();
        }

        @Override
        protected JSONObject doInBackground(String... arg0) {
            try {

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(ProfitTillConstants.MOBILE_API+"?t="+apkData.getString("timestamp","0"));
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
                System.out.println(jObjGmail.toString());
                return jObjGmail;

            } catch (Exception e) {
                return null;

            }

        }
        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            if(result==null){
                finish();
            }
            try {
                JSONArray objects = result.getJSONArray("settings");
                if(objects.length()==0){
                    System.out.println("Null settings array");
                }else {
                    for (int i = 0; i < objects.length(); i++) {
                        JSONObject jsonObject = objects.getJSONObject(i);
                        JSONObject j = jsonObject.getJSONObject("Mobileappsetting");
                        System.out.println("Setting " + j.getString("setting"));
                        System.out.println("Value " + j.getString("value"));
                        apiEditor.remove(j.getString("setting"));
                        apiEditor.commit();
                        apiEditor.putString(j.getString("setting"), j.getString("value"));
                        apiEditor.commit();
                    }
                }
                String timestamp=result.getString("t");
                System.out.println("Time stamp " + timestamp);
                apkDataEditor.putString("timestamp",timestamp);
                apkDataEditor.commit();
                final String idCheck = userData.getString("id",null);
                //String check = userData.getString("which screen needs to be displayed");
                if(userData.getString("referralCodeRequired","false").equalsIgnoreCase("true")){
                    startActivity(new Intent(SplashScreen.this,ReferrerActivity.class));
                }else if(userData.getString("message","false").equalsIgnoreCase("true")){
                    startActivity(new Intent(SplashScreen.this,MobileNumber.class));
                }else if(idCheck!=null){
                    startActivity(new Intent(SplashScreen.this,MainActivity.class));
                }else {
                    startActivity(new Intent(SplashScreen.this, LoginActivity.class));

                }
            }catch (Exception e){
                finish();
            }
        }
    }

    class pushApkData extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // showProgressDialog();
        }

        @Override
        protected String doInBackground(String... arg0) {
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://api.profittill.com/devices/add");
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                httppost.setEntity(new UrlEncodedFormEntity(apkDataListValue));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                int status = response.getStatusLine().getStatusCode();

                if(status == 200){
                    apkDataEditor.putString("checkId",userData.getString("id",""));
                    apkDataEditor.commit();
                    return "success";
                } else {
                    return "failure";
                }

            } catch (Exception e) {
                return null;

            }

        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
         }
    }


    public final boolean isInternetOn() {

        ConnectivityManager connection =
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);

        if (  connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {

            /*Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();*/
            return true;

        } else if (

                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {

 /*           Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();*/
            return false;
        }
        return false;
    }

    private void showProgressDialog()
    {
       // bar = (ProgressBar) this.findViewById(R.id.progressBar);
       /* pDlg =  new ProgressDialog(new ContextThemeWrapper(SplashScreen.this, android.R.style.Theme_Holo_Light_Dialog));
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDlg.setIndeterminate(true);
        pDlg.setCancelable(false);
        pDlg.setProgressDrawable(getResources().getDrawable(R.drawable.greenprogressdialog));
        pDlg.show();*/

       // pDlg.setContentView(R.layout.activity_splash_internet_not_working);
        pDlg =  new ProgressDialog(getApplicationContext());
        pDlg.setIndeterminate(true);
        pDlg.setCancelable(false);
        pDlg.show();
    }

    ProgressDialog pDlg;
    //ProgressBar bar;
}