/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.kneet.v3.view;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.gcm.service.GCMRegistrater;
import com.ntels.kneet.v3.common.gcm.service.GcmSharedPreferences;
import com.ntels.kneet.v3.common.gcm.service.PushService;
import com.ntels.kneet.v3.common.gcm.support.GcmRegLocalBroadCast;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.mdns.MdnsRegService;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.dialog.Dialog_Spinner;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
public class Intro extends CustomActivity implements CustomDialog.OnMsgAlterToResult {

    /*툴바 관련*/
    private Toolbar toolbar;

    /*통신 관련*/
    private              int                                iType                 = 0;
    private static final int                                MSG_COM_G_APP_VERSION = 1;
    private static final int                                MSG_COM_ACTINIT       = 2;
    private static final int                                MSG_COM_MDNS_INIT     = 3;

    /*공통*/
    private Activity       act;
    private AppConfig      appConfig;
    private Intent         intent;
    private Util              util            = new Util();
    private CustomDialog      customDialog    = new CustomDialog();
    private Boolean           bPushSucess     = false;
    private Boolean           bMdnsSucess     = false;
    private String            sVersionName    = "";
    private String            sGcmRegID       = "";
    private int               iServerPosition = 0;
    private String            sPush_type_code = "";
    private ArrayList<String> alServerTitle   = new ArrayList<String>();
    private ArrayList<String> alServerId      = new ArrayList<String>();

    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     *
     * @param savedInstanceState
     */
    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        act = Intro.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        if ( getIntent() != null ) {
            sPush_type_code = util.null2string(getIntent().getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
            Dlog.v("jino intro sType = ", sPush_type_code);
        }

        Dlog.v("appConfig.getIntro()=" + appConfig.getIntro());
        if ( appConfig.getIntro() ) {
            bMdnsSucess = true;
            if ( appConfig.getLogin() ) {
                gotoMainStart();
            } else {
                gotoLoginStart();
            }
        } else {
            View viewToLoad = LayoutInflater.from(act).inflate(R.layout.intro, null);
            act.setContentView(viewToLoad);
            appConfig.Labinit();
            appConfig.setIntro(true);
            appConfig.setGoErr(false);
            appConfig.setMain(false);
            notiCancel();

            float scale = util.getDisplayScale(act);
            appConfig.setScale(scale);

            int iHeight = util.str2int(util.getMyDisplayHeight(act));
            int iWidth = util.str2int(util.getMyDisplayWidth(act));

            appConfig.setDisplayHeight(iHeight);
            appConfig.setDisplayWidth(iWidth);
            int iTempHeight = (int) (iHeight * 0.7);
            int iTempWidht = (int) ((iHeight * 0.7) * 0.52);
            RelativeLayout.LayoutParams paramView3 = new RelativeLayout.LayoutParams(iTempWidht, iTempHeight);
            paramView3.addRule(RelativeLayout.CENTER_IN_PARENT);
            util.getView(act, R.id.ivLogo).setLayoutParams(paramView3);
            ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_ACTINIT), 10);
        }
    }

    private void actinit() {
        // 강제 종료시 복구를 위한 코드
        getUUid();
        // 버전확인
        AppVerCheck();

        //mdns 서비스 초기화
        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_MDNS_INIT), 10);
        LocalBroadcastManager.getInstance(this).registerReceiver(mGcmRegLocalBroadCast, new IntentFilter(GcmRegLocalBroadCast.INTENT_ACTION));

        if ( appConfig.isDebuggable(act) ) {
            alServerId.clear();
            alServerId.add("0");
            alServerId.add("1");
            alServerId.add("2");
            alServerTitle.clear();
//            alServerTitle.add("Kneet2_개발\n(http://61.40.220.132:5007, 20001)");
            alServerTitle.add("Kneet3_개발\n(https://dev.allofthings.com:5018, 30001)");
            alServerTitle.add("Kneet2_운영\n(https://home-api.allofthings.com, 20001)");
            alServerTitle.add("Kneet2_Custom\n(http://192.168.0.10:5007, 20001)");

            intent = new Intent();
            intent.setClass(act, Dialog_Spinner.class);
            intent.putExtra(Constants.EXTRA_SPINNER_LIST1, alServerTitle);
            intent.putExtra(Constants.EXTRA_SPINNER_TITLE, "접속 서버 선택");
            intent.putExtra(Constants.EXTRA_SPINNER_TYPE, 0);
            intent.putExtra(Constants.EXTRA_SPINNER_POSITION, iServerPosition);
            util.callActivityForResultNoAnim(act, intent, Constants.ACT_SPINNER);
        } else {
            setServer(Constants.KEY_URL_KNEET_V2);
        }
    }

    private void notiCancel() {

        NotificationManager notifier = (NotificationManager) act.getSystemService(Context.NOTIFICATION_SERVICE);
        notifier.cancel(Constants.NOTIFICATION_ID);
    }

    private void setInit() {

        //gcm 서비스 초기화
        stopPushService();
        startPushService();
        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_APP_VERSION), 10);
    }

    /**
     * <pre>
     *     어플 버전 확인
     * </pre>
     */
    private void AppVerCheck() {
        // 어플 버전 정보 체크
        PackageManager pm = this.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
            sVersionName = pi.versionName;
            appConfig.setVer(sVersionName);
            // util.getTextView(act, R.id.tvVer).setText("Ver. " +
            // sVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * <pre>
     *      UUID구하기
     * </pre>
     */
    private void getUUid() {
        // IMEI, IMSI
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String sImei = telephonyManager.getDeviceId();
        String sImsi = telephonyManager.getSubscriberId();

        // MAC ADDRESS
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String sMacAddress = wifiInfo.getMacAddress();

        // ANDROID_ID
        String sAndroid_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        if ( util.null2string(sImei).equals("") ) {
            if ( util.null2string(sMacAddress).equals("") ) {
                customDialog.MsgAlert(act, Constants.MSG836);
            } else {
                appConfig.setUuid(sMacAddress);
            }
        } else {
            appConfig.setUuid(sImei);
        }
    }

    /**
     * <pre>
     * 푸쉬& GCM 통합 서비스 시작
     * </pre>
     *
     * @return void
     *
     * @author Sangtae
     * @since 2014. 4. 14. 오후 3:41:43
     */
    private void startPushService() {

        startService(new Intent(this, PushService.class));
    }

    /**
     * <pre>
     * 푸쉬& GCM 통합 서비스 종료
     * </pre>
     *
     * @return void
     *
     * @author Sangtae
     * @since 2014. 4. 14. 오후 3:42:49
     */
    private void stopPushService() {

        stopService(new Intent(this, PushService.class));
    }

    /**
     * <PRE>
     * 1. MethodName: startMdnsService
     * 2. ClassName :
     * 3. Comment   : startMdnsService
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void startMdnsService() {

        new MdnsServiceTask().execute();
    }

    private GcmSharedPreferences mGcmSharedPreferences;
    private GcmRegLocalBroadCast mGcmRegLocalBroadCast = new GcmRegLocalBroadCast() {
        public void onMessage(String msg) {

        }

        ;

        public void onMessage(int resultcode, String msg) {

        }

        ;

        @Override public void onMessage(int action, int resultcode, String msg) {

            super.onMessage(action, resultcode, msg);
            mGcmSharedPreferences = new GcmSharedPreferences(act);
            bPushSucess = true;
            switch (action) {
                case GCMRegistrater.onGCMRegistraterListener.ACTION_SUCESS: // 퓌시 키 발급 성공 // msg에 키
                    // 값 반환
                    //				bPushSucess = true;
                    if ( mGcmSharedPreferences.isRegistrationID() ) { // 등록키 존재 여부 확인
                        Dlog.v("GCM RegID: " + mGcmSharedPreferences.getRegistrationID()); // GCM
                        // 등록키
                        // 반환
                        sGcmRegID = mGcmSharedPreferences.getRegistrationID();
                        appConfig.setPush_Token(sGcmRegID);
                    }

                    break;
                // 퓌시 사용 불가한 경우
                case GCMRegistrater.onGCMRegistraterListener.ACTION_NOT_PLAY_SERVICE:
                case GCMRegistrater.onGCMRegistraterListener.ACTION_DEVICE_NOT_SURPROT:
                case GCMRegistrater.onGCMRegistraterListener.ACTION_REG_EXCEPTION:
                case GCMRegistrater.onGCMRegistraterListener.PLAY_SERVICES_RESOLUTION_REQUEST:
                    //																			if (GooglePlayServicesUtil.isUserRecoverableError(resultcode)) {
                    //																				GooglePlayServicesUtil.getErrorDialog(resultcode, act,
                    //																						onGCMRegistraterListener.PLAY_SERVICES_RESOLUTION_REQUEST).show();
                    //																			} else {
                    //																				Dlog.i("MainActivity.java | checkPlayService", "|This device is not supported.|");
                    //																				finish();
                    //																			}
                    break;
                case GCMRegistrater.onGCMRegistraterListener.ACTION_USE_PLAY_SERVICE: // 플레이 서비스
                    // 사용가능
                    break;
                default:
                    break;
            }
        }
    };

    @Override public void onPause() {

        super.onPause();
    }

    /**
     * <PRE>
     * 1. MethodName: onResume
     * 2. ClassName :
     * 3. Comment   : onResume
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onResume() {

        super.onResume();
    }

    @Override protected void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    public void setBackLoadLogin() {

        handler.sendEmptyMessageDelayed(0, 2000); // ms,
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override public boolean handleMessage(Message message) {

            if ( !bPushSucess ) {
                Dlog.v("handler : " + appConfig.getPush_Token());
                setBackLoadLogin();
            } else {
                gotoLoginStart();
            }
            return false;
        }
    });

    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : onBackPressed
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {

    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == RESULT_OK ) {
            switch (requestCode) {
                case Constants.ACT_LOGIN:
                    setFinish();
                    break;
                case Constants.ACT_SPINNER:
                    iServerPosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, 0);
                    setServer(iServerPosition);
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_SPINNER:
                    int iCONNECTION_TYPE = util.null2int(getIntent().getIntExtra(Constants.EXTRA_CONNECTION_TYPE, Constants.KEY_URL));
                    setServer(iCONNECTION_TYPE);
                    break;
                default:
                    setFinish();
                    break;
            }
        }
    }

    private void setServer(int iVal) {

        if ( iVal == Constants.KEY_URL_KNEET_V3_DEV ) {
            appConfig.setUrl(Constants.URL_KNEET_V3_DEV);
            appConfig.setSmartUrl(Constants.SMART_URL_KNEET_V3_DEV);
            appConfig.setService_Id(Constants.SERVICE_ID_KNEET_V3_DEV);
            appConfig.setProject_Id(Constants.PROJECT_ID_KNEET_V3_DEV);
            util.setPreferences(act, Constants.EXTRA_APPSTART_ID, Constants.APP_START_ID_KNEET_V3_DEV);
        } else if ( iVal == Constants.KEY_URL_KNEET_V2 ) {
            appConfig.setUrl(Constants.URL_KNEET_V2);
            appConfig.setSmartUrl(Constants.SMART_URL_KNEET_V2);
            appConfig.setService_Id(Constants.SERVICE_ID_KNEET_V2);
            appConfig.setProject_Id(Constants.PROJECT_ID_KNEET_V2);
            util.setPreferences(act, Constants.EXTRA_APPSTART_ID, Constants.APP_START_ID_KNEET_V2);
        } else if ( iVal == Constants.KEY_URL_KNEET_V2_DEV_CUSTOM ) {
            appConfig.setUrl(Constants.URL_KNEET_V2_DEV_CUSTOM);
            appConfig.setSmartUrl(Constants.SMART_URL_KNEET_V2_DEV_CUSTOM);
            appConfig.setService_Id(Constants.SERVICE_ID_KNEET_V2_DEV_CUSTOM);
            appConfig.setProject_Id(Constants.PROJECT_ID_KNEET_V2_DEV_CUSTOM);
            util.setPreferences(act, Constants.EXTRA_APPSTART_ID, Constants.APP_START_ID_KNEET_V2_CUSTOM);
        }
        setInit();
    }

    private void setFinish() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mGcmRegLocalBroadCast);

        Dlog.v("appConfig.getIntro()=" + appConfig.getIntro());
        act.finish();
    }

    Handler ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_APP_VERSION:
                    send_G_app_version();
                    break;
                case MSG_COM_ACTINIT:
                    actinit();
                    break;
                case MSG_COM_MDNS_INIT:
                    startMdnsService();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    private void send_G_app_version() {

        try {
            HttpSend httpSend = new HttpSend(act);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override public void resultResponse(Response result) {

                    result_G_app_version(result);
                }
            });
            httpSend.G_app_version(Constants.OS_TYPE, Constants.APP_STORE_CD, appConfig.getVer(), appConfig.getService_Id());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_G_app_version(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sRESULT_CODE = util.null2string(joResult.get(Constants.HTTP_result_code));
                if ( sRESULT_CODE.equals("00") ) {
                    setBackLoadLogin();
                } else if ( sRESULT_CODE.equals("01") ) {
                    customDialog.MsgAlert(act, Constants.MSG819);
                } else if ( sRESULT_CODE.equals("99") ) {
                    // 업데이트 진행해야 함
                    customDialog.MsgAlert(act, Constants.MSG821);
                }
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {
            case Constants.MSG801:
                if ( iBtnResult == 1 ) {
                    Dlog.v("jino test");
                }
                break;
            case Constants.MSG836:
                if ( iBtnResult == 1 ) {
                    appConfig.setGoErr(true);
                    setResult(RESULT_CANCELED, new Intent());
                    finish();
                }
                break;
            case Constants.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                } else {
                    appConfig.setGoErr(true);
                    appConfig.setIntro(false);
                    setResult(RESULT_CANCELED, new Intent());
                    act.finish();
                }
                break;
            case Constants.MSG821:
                if ( iBtnResult == 1 ) {
                    // 업데이트 소스(다운로드)
                    Intent marketLaunch = new Intent(Intent.ACTION_VIEW);
                    //				marketLaunch.setData(Uri.parse("market://search?q=" + Constants.PACKAGE_NAME));
                    marketLaunch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    marketLaunch.setData(Uri.parse("market://details?id=" + act.getPackageName()));
                    startActivity(marketLaunch);
                    setExit();
                } else {
                    setExit();
                }
                break;
            case Constants.MSG819:
                if ( iBtnResult == 1 ) {
                    // 업데이트 소스(다운로드)
                    Intent marketLaunch = new Intent(Intent.ACTION_VIEW);
                    //				marketLaunch.setData(Uri.parse("market://search?q=" + Constants.PACKAGE_NAME));
                    marketLaunch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    marketLaunch.setData(Uri.parse("market://details?id=" + act.getPackageName()));
                    startActivity(marketLaunch);
                    setExit();
                } else {
                    setBackLoadLogin();
                }
                break;
            default:
                break;
        }
    }

    private void setExit() {

        appConfig.setIntro(false);
        Dlog.v(appConfig.getIntro());
        finish();
        return;
    }

    void gotoLoginStart() {

        Intent intent = new Intent(act, Login.class);
        Dlog.v("jino intro1 sType = ", sPush_type_code);
        if ( !sPush_type_code.equals("") ) {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, sPush_type_code);
        } else {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, "");
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        util.callActivityForResultNoAnim(act, intent, Constants.ACT_LOGIN);
        //        util.callActivityNoAnim(act, intent);
    }

    void gotoMainStart() {

        Intent intent = new Intent(act, Main.class);
        Dlog.v("jino intro2 sType = ", sPush_type_code);
        if ( !sPush_type_code.equals("") ) {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, sPush_type_code);
        } else {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, "");
        }

        if ( sPush_type_code.equals("HOME_MEM_INV") ) {
            //    홈 초대 받음
        } else if ( sPush_type_code.equals("HOME_MEM_REF") ) {
            //    초대했는데 거절 당할 시
        } else if ( sPush_type_code.equals("HOME_MEM_BAN") ) {
            //    홈 강퇴 받음
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ( sPush_type_code.equals("HOME_MEM_SEL") ) {
            //    홈 자진 탈퇴 받음
        } else if ( sPush_type_code.equals("HOME_DEL") ) {
            //    홈 삭제
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ( sPush_type_code.equals("DVC_CER_REV") ) {
            //    단말 인증 해지 됨
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ( sPush_type_code.equals("MODE_CHG") ) {
            //    홈 모드 변경 시
        } else if ( sPush_type_code.equals("MODE_CHG_ERR") ) {
            //    홈 모드 변경 시 일부 장치 제어 실패
        } else if ( sPush_type_code.equals("RULE_EXC") ) {
            //    규칙의 액션 결과
        } else if ( sPush_type_code.equals("RULE_ERR") ) {
            //    규칙 실패 누적으로 규칙 비 활성시킴
        } else if ( sPush_type_code.equals("HOMEHUB_DEL") ) {
            //    홈 허브가 삭제됨
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ( sPush_type_code.equals("DVC_OWN_CHG") ) {
            //    장치 소유주 변경 알림
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ( sPush_type_code.equals("MEM_ALL_OUT") ) {
            //    멤버 All out 시
        } else if ( sPush_type_code.equals("MEM_ANY_IN") ) {
            //    멤버 Any in 시
        } else if ( sPush_type_code.equals("HOME_LOC_CHG") ) {
            //    홈 위치 변경 알림
        } else if ( sPush_type_code.equals("MEM_DVC_DEL") ) {
            //    단말 등록 해지 알림
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ( sPush_type_code.equals("HOME_RELOAD") ) {
            //    홈 멤버 정보 재조회 알림
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ( sPush_type_code.equals("LOGOUT") ) {
            //    강제 로그아웃 시킴
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }

        util.callActivityNoAnim(act, intent);
        setFinishLoading();
    }

    public void setFinishLoading() {

        int iInterval = 1000;
        finishhandler.sendEmptyMessageDelayed(0, iInterval); // ms,
    }

    private Handler finishhandler = new Handler(new Handler.Callback() {
        @Override public boolean handleMessage(Message message) {

            if ( !bMdnsSucess ) {
                Dlog.v("handler : " + appConfig.getPush_Token());
                setFinishLoading();
            } else if ( !appConfig.getMain() ) {
                setFinishLoading();
            } else {
                setFinish();
            }
            return false;
        }
    });

    private class MdnsServiceTask extends AsyncTask<Void, Void, Void> {

        @Override protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override protected Void doInBackground(Void... params) {

            try {
                if ( isServiceRunning(MdnsRegService.class.getName()) ) {
                    stopService(new Intent(act, MdnsRegService.class));
                } else {
                    startService(new Intent(act, MdnsRegService.class));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override protected void onPostExecute(Void result) {

            super.onPostExecute(result);
            bMdnsSucess = true;
        }
    }

    public boolean isServiceRunning(String serviceClassName) {

        final ActivityManager activityManager = (ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for ( ActivityManager.RunningServiceInfo runningServiceInfo : services ) {
            if ( runningServiceInfo.service.getClassName().equals(serviceClassName) ) {
                return true;
            }
        }
        return false;
    }
}
