Subversion Repositories SmartDukaan

Rev

Rev 17057 | Rev 19653 | 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.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
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.google.android.gms.gcm.GoogleCloudMessaging;
import com.saholic.profittill.Constants.ProfitTillConstants;
import com.saholic.profittill.Utils.UtilityFunctions;
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.io.IOException;
import java.util.ArrayList;


public class SplashScreen extends ActionBarActivity {
    SharedPreferences apiData, userData,apkData;
    SharedPreferences.Editor apiEditor,userEditor,apkDataEditor;
    UtilityFunctions utilityFunctions;
    AlertDialog dialog1;
    AlertDialog.Builder b;
    ProgressBar pd;
    GoogleCloudMessaging gcm;
    String regId;
    ArrayList<NameValuePair> apkDataListValue;
    ArrayList<NameValuePair> nameValuePairsGcm;
    @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());*/
                    utilityFunctions=new UtilityFunctions();
                    apkDataListValue = utilityFunctions.getDeviceInformation(this);

                    if(isInternetOn()) {
                        new pushApkData().execute();
                    }
                } else if (!(apkData.getString("checkId","blank").equalsIgnoreCase(userData.getString("id","blank")))) {
                    utilityFunctions=new UtilityFunctions();
                    apkDataListValue = utilityFunctions.getDeviceInformation(this);
                    if(isInternetOn()) {
                        new pushApkData().execute();
                    }
                } else if (Integer.parseInt(apkVersionCode) == getPackageManager().getPackageInfo(getPackageName(), 0).versionCode) {

                }  else {
                    utilityFunctions=new UtilityFunctions();
                    apkDataListValue = utilityFunctions.getDeviceInformation(this);
                    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();
        }

        @Override
        protected JSONObject doInBackground(String... arg0) {
            try {
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                HttpClient httpclient = new DefaultHttpClient();
                String url = ProfitTillConstants.MOBILE_API+"?t="+apkData.getString("timestamp","0")+"&imeinumber="+telephonyManager.getDeviceId();
                //HttpPost httppost = new HttpPost(ProfitTillConstants.MOBILE_API+"?t="+apkData.getString("timestamp","0"));
                HttpPost httppost=new HttpPost(url);
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
                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");
                        apiEditor.remove(j.getString("setting"));
                        apiEditor.commit();
                        apiEditor.putString(j.getString("setting"), j.getString("value"));
                        apiEditor.commit();
                    }
                }
                String timestamp=result.getString("t");
                String failureCount=result.getString("failureCount");
                apkDataEditor.putString("timestamp",timestamp);
                apkDataEditor.commit();
                final String idCheck = userData.getString("id",null);
                //String check = userData.getString("which screen needs to be displayed");
                if(Integer.parseInt(failureCount)<=0) {
                    if (userData.getString("referralCodeRequired", "false").equalsIgnoreCase("true")) {
                        Intent startActivityIntent=new Intent(SplashScreen.this, ReferrerActivity.class);
                        Intent intent = getIntent();
                        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                            Uri uri = intent.getData();
                            startActivityIntent.setAction("31");
                            startActivityIntent.setData(Uri.parse(uri.toString()));
                        }
                        startActivity(startActivityIntent);
                        //startActivity(new Intent(SplashScreen.this, ReferrerActivity.class));
                    } else if (userData.getString("message", "false").equalsIgnoreCase("true")) {
                        Intent startActivityIntent=new Intent(SplashScreen.this, MobileNumber.class);
                        Intent intent = getIntent();
                        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                            Uri uri = intent.getData();
                            startActivityIntent.setAction("31");
                            startActivityIntent.setData(Uri.parse(uri.toString()));
                        }
                        startActivity(startActivityIntent);
                        //startActivity(new Intent(SplashScreen.this, MobileNumber.class));
                    } else if (idCheck != null) {
                        Intent startActivityIntent=new Intent(SplashScreen.this, MainActivity.class);
                        Intent intent = getIntent();
                        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                            Uri uri = intent.getData();
                            startActivityIntent.setAction("31");
                            startActivityIntent.setData(Uri.parse(uri.toString()));
                        }
                        startActivity(startActivityIntent);
                    } else {
                        Intent startActivityIntent=new Intent(SplashScreen.this, LoginActivity.class);
                        Intent intent = getIntent();
                        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                            Uri uri = intent.getData();
                            startActivityIntent.setAction("31");
                            startActivityIntent.setData(Uri.parse(uri.toString()));
                        }
                        startActivity(startActivityIntent);
                        //startActivity(new Intent(SplashScreen.this, LoginActivity.class));

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

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

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

        @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.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.CONNECTING ||
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                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()
    {
        pDlg =  new ProgressDialog(getApplicationContext());
        pDlg.setIndeterminate(true);
        pDlg.setCancelable(false);
        pDlg.show();
    }

    ProgressDialog pDlg;

/*

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        Log.d("On Restore Instance","On Restore Instance");
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestart() {
        Log.d("On Restart","On Restart");
        super.onRestart();

        try {
            String apkVersionCode = apkData.getString("versionCode","");
            String apkVersionName = apkData.getString("versionName","");
            if(userData.getString("id","").isEmpty()) {

            }else {
                if (apkVersionCode.isEmpty()) {
                    apkDataListValue = getDeviceInformation();

                    if(isInternetOn()) {
                        new pushApkData().execute();
                    }
                } else if (!(apkData.getString("checkId","blank").equalsIgnoreCase(userData.getString("id","blank")))) {
                    apkDataListValue = getDeviceInformation();
                    if(isInternetOn()) {
                        new pushApkData().execute();
                    }
                } else if (Integer.parseInt(apkVersionCode) == getPackageManager().getPackageInfo(getPackageName(), 0).versionCode) {

                }  else {
                    apkDataListValue = getDeviceInformation();
                    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();
        }

    }


    public ArrayList<NameValuePair> getDeviceInformation(){
        ArrayList<NameValuePair> deviceDataList=null;
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            deviceDataList = new ArrayList<>();
            deviceDataList.add(new BasicNameValuePair("user_id", userData.getString("id", "")));
            deviceDataList.add(new BasicNameValuePair("versioncode", info.versionCode + ""));
            deviceDataList.add(new BasicNameValuePair("versionname", info.versionName + ""));
            deviceDataList.add(new BasicNameValuePair("osversion", android.os.Build.VERSION.SDK_INT + ""));
            deviceDataList.add(new BasicNameValuePair("imeinumber", telephonyManager.getDeviceId()));
            deviceDataList.add(new BasicNameValuePair("manufacturer", Build.MANUFACTURER));
            deviceDataList.add(new BasicNameValuePair("model", Build.MODEL));
            deviceDataList.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());
        }catch (Exception e){
            e.printStackTrace();
        }
        return deviceDataList;
    }
*/

    /*@Override
    protected void onPause() {
        Log.d("On Pause","On Pause");
        super.onPause();
    }*/
    public void registerGCM() {

        gcm = GoogleCloudMessaging.getInstance(SplashScreen.this);
        registerInBackground();

    }

    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(SplashScreen.this);
                    }
                    regId = gcm.register(ProfitTillConstants.GOOGLE_SENDER_ID);
                    msg = "Device registered";

                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                new gcmPushData().execute(msg);
            }
        }.execute(null, null, null);
    }


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

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

        @Override
        protected String doInBackground(String... arg0) {
            String id = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url", "http://staging.profittill.com/gcm_users/add"));
                nameValuePairsGcm = new ArrayList<>();
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid", regId));
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber", telephonyManager.getDeviceId()));
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id", null)));
                nameValuePairsGcm.add(new BasicNameValuePair("device_message", arg0[0]));
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    Log.d("ResponseCode GCM ", status + "");
                } else {
                    Log.d("ResponseCode GCM ", status + "");
                }

                nameValuePairsGcm.clear();
                Log.e("pass 1", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 1", e.toString());

            }
            return id;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            final String idCheck = userData.getString("id",null);
            if (userData.getString("referralCodeRequired", "false").equalsIgnoreCase("true")) {
                Intent startActivityIntent=new Intent(SplashScreen.this, ReferrerActivity.class);
                Intent intent = getIntent();
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                    Uri uri = intent.getData();
                    startActivityIntent.setAction("31");
                    startActivityIntent.setData(Uri.parse(uri.toString()));
                }
                startActivity(startActivityIntent);
                //startActivity(new Intent(SplashScreen.this, ReferrerActivity.class));
            } else if (userData.getString("message", "false").equalsIgnoreCase("true")) {
                Intent startActivityIntent=new Intent(SplashScreen.this, MobileNumber.class);
                Intent intent = getIntent();
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                    Uri uri = intent.getData();
                    startActivityIntent.setAction("31");
                    startActivityIntent.setData(Uri.parse(uri.toString()));
                }
                startActivity(startActivityIntent);
                //startActivity(new Intent(SplashScreen.this, MobileNumber.class));
            } else if (idCheck != null) {
                Intent startActivityIntent=new Intent(SplashScreen.this, MainActivity.class);
                Intent intent = getIntent();
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                    Uri uri = intent.getData();
                    startActivityIntent.setAction("31");
                    startActivityIntent.setData(Uri.parse(uri.toString()));
                }
                startActivity(startActivityIntent);
            } else {
                Intent startActivityIntent=new Intent(SplashScreen.this, LoginActivity.class);
                Intent intent = getIntent();
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                    Uri uri = intent.getData();
                    startActivityIntent.setAction("31");
                    startActivityIntent.setData(Uri.parse(uri.toString()));
                }
                startActivity(startActivityIntent);
                //startActivity(new Intent(SplashScreen.this, LoginActivity.class));
            }
        }
    }
}