반응형

예전에 간단히 이벤트 팝업만들었을때 생각나서 올려보려고한다. 

 

서버에 html파일 있는지 확인 -> 있으면 가저와서 로딩후 리사이징

	//이벤트 팝업 변수들
	private static final String CHECK_USER_DATE = "FIRST_MEET";
	private static final String TAG = "MainActivity";
	private static final String CHECK_EVNET_POPUP = "CHECK_EVNET_POPUP";
	private static final String CHECK_EVNET_POPUP_NO = "CHECK_EVNET_POPUP_NO";
	private static final String CHECK_EVNET_POPUP_YES = "CHECK_EVNET_POPUP_YES";
	private String event_popup_result;

-지금와서 보니 preference 키값들은 별도 클래스에 모아서 관리하는게 좋은것같다.

 

// EVENT POP
	public void checkShowOrNotshow(){
		String chk_today =null;
		String pref_user_date= null;

		SharedPreferences pref = getApplicationContext().getSharedPreferences("event_popup", MODE_PRIVATE);
		chk_today = pref.getString(CHECK_EVNET_POPUP,CHECK_EVNET_POPUP_NO);
		pref_user_date = pref.getString(CHECK_USER_DATE,"FIRST_MEET");

		if(!pref_user_date.equals("FIRST_MEET")){
			int my_result =compareUserdateWithToday(pref_user_date);
			//오늘 접속함
			if(my_result == 0){
				Log.i(TAG,"## 이벤트 팝업 : 오늘 접속함");

				//하루 안보기 클릭
				if(chk_today.equals(CHECK_EVNET_POPUP_YES)){
					Log.i(TAG,"## 이벤트 팝업 : 하루 안보기 클릭");
				}
				//하루 안보기 클릭 안했음
				else if(chk_today.equals(CHECK_EVNET_POPUP_NO)){
					Log.i(TAG,"## 이벤트 팝업 : 하루 안보기 클릭 안했음");
					showEventPopup();
				}
			}
			//어제 접속함
			else if(my_result < 0){
				Log.i(TAG,"## 이벤트 팝업 : 어제 접속함");
				getApplication().getSharedPreferences("event_popup",MODE_PRIVATE).edit().putString(CHECK_EVNET_POPUP,CHECK_EVNET_POPUP_NO).apply();
				pref.edit().putString(CHECK_USER_DATE,getToday()).apply();
				showEventPopup();
			}
			//미래에서 왔을일은 없으니 에러
			else{
				Log.i(TAG,"## 이벤트 팝업 : 미래에서 왔을일은 없으니 에러");
				getApplication().getSharedPreferences("event_popup",MODE_PRIVATE).edit().putString(CHECK_EVNET_POPUP,CHECK_EVNET_POPUP_NO).apply();
			}
		} else {
			Log.i(TAG,"## 이벤트 팝업 : 앱을 처음 깔음");
			pref.edit().putString(CHECK_USER_DATE,getToday()).apply();
			showEventPopup();
		}

	}

	private void showEventPopup(){
		Intent intent = new Intent(MainActivity.this,EventPopupActivity.class);
		intent.putExtra("URL",URL.EVENT_POPUP.url(false));
		startActivity(intent);
		overridePendingTransition(R.anim.activity_fade_in,0);
	}

	// 미래 : int_calDateDays > 0 양수
	// 현재 : int_calDateDays == 0 같을때
	// 과거 : int_calDateDays < 0 음수
	private int compareUserdateWithToday(String user_date) {
		Integer int_calDateDays =null;
		try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal = Calendar.getInstance();

			Date FirstDate = format.parse(user_date);
			Date SecondDate = format.parse(getToday());// 오늘 날짜를 yyyy-MM-dd포맷 String 값

			long calDate = FirstDate.getTime() - SecondDate.getTime();
			Long calDateDays = calDate / ( 24*60*60*1000);
			int_calDateDays = (calDateDays != null) ? calDateDays.intValue() : -1;//long to int
		}
		catch(ParseException e) { e.printStackTrace(); }
		return int_calDateDays;
	}


	private static String getToday() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		final Calendar cal = Calendar.getInstance();
		return format.format(cal.getTime());
	}

	// start NewHttpGetRequest.class
	private class NewHttpGetRequest extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params){
			HttpsURLConnection urlConnection= null;
			java.net.URL url = null;
			String response = "";
			try {
				event_popup_result=null;
				url  = new java.net.URL(params[0]);
				urlConnection=(HttpsURLConnection)url.openConnection();
				urlConnection.setRequestMethod("GET");
				urlConnection.setDoOutput(true);
				urlConnection.setDoInput(true);
				urlConnection.connect();
				InputStream inStream = null;
				inStream = urlConnection.getInputStream();
				BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
				String temp = "";
				while((temp = bReader.readLine()) != null){
					//Parse data
					response += temp;
				}
				bReader.close();
				inStream.close();
				urlConnection.disconnect();
				event_popup_result = response;
				Log.i("??","## response :" +response);
			} catch (FileNotFoundException no_file_exception){
				event_popup_result ="FileNotFoundException";
			} catch (Exception e) {
				e.printStackTrace();
				Log.i("??","## Exception :" +e.toString());
				event_popup_result = "otherException";
			}
			return event_popup_result;
		}

		@Override
		protected void onPostExecute(String s) {
			super.onPostExecute(s);
			//파일 없을 경우 처리
			if(event_popup_result.contains("FileNotFoundException")){
				Toast.makeText(MainActivity.this,event_popup_result, Toast.LENGTH_SHORT).show();
			}
			//다른 익셉션일 경우 처리
			else if(event_popup_result.contains("otherException")){
				Toast.makeText(MainActivity.this,event_popup_result, Toast.LENGTH_SHORT).show();
			}
			// 통신이 성공했을때
			else{
				checkShowOrNotshow();
			}

			Log.i("??","## onPostExecute" +s);
		}
	}// end NewHttpGetRequest.class

- 통신에 성공하고나면 ,checkShowOrNotShow()를 불러 오늘하루안보기를 클릭했는지 체크한다.

 

public class EventPopupActivity extends AppCompatActivity {
    private static final String TAG = "EventPopupActivity";
    private static final String CHECK_EVNET_POPUP = "CHECK_EVNET_POPUP";
    private static final String CHECK_EVNET_POPUP_YES = "CHECK_EVNET_POPUP_YES";

    private LinearLayout line_container;
    private Button pop_close_button;
    private Button not_show_today_btn;
    private WebView pop_webview;

    View.OnClickListener pop_close_button_lisn = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
            overridePendingTransition(0, R.anim.activity_fade_out);//종료 애니메이션
        }
    };
    View.OnClickListener not_show_today_btn_lisn = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getApplication().getSharedPreferences("event_popup",MODE_PRIVATE).edit().putString(CHECK_EVNET_POPUP,CHECK_EVNET_POPUP_YES).apply();
            finish();
            overridePendingTransition(0, R.anim.activity_fade_out);//종료 애니메이션
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        Locale locale = DeviceUtil.getDeviceLocale(this);
        Configuration config = getResources().getConfiguration();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            config.setLocale(locale);
            createConfigurationContext(config);
        } else {
            config.locale = locale;
        }
        getResources().updateConfiguration(config, getResources().getDisplayMetrics());

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_popup_1);
        settingViews();//view 세팅
        webviewSettings();//webview 기본 세팅

        String getURL = null;
        getURL = getIntent().getStringExtra("URL");
        ELog.i(TAG, getURL);

        pop_webview.loadUrl(EventUtil.makeCountryURL(this,getURL));
    }

    //findByView
    private void settingViews() {
        line_container = findViewById(R.id.line_container);
        pop_close_button = findViewById(R.id.pop_close_button);
        not_show_today_btn = findViewById(R.id.not_show_today_btn);

        pop_close_button.setOnClickListener(pop_close_button_lisn);
        not_show_today_btn.setOnClickListener(not_show_today_btn_lisn);
        pop_webview = findViewById(R.id.pop_webview);
    }

    //webview setting
    private void webviewSettings() {
        pop_webview.clearCache(true);
        pop_webview.setWebViewClient(new SimpleWebviewClient());
        pop_webview.addJavascriptInterface(new WebAppInterface(),"AndroidFunction");
        WebSettings set = pop_webview.getSettings();
        set.setJavaScriptEnabled(true);
        set.setJavaScriptCanOpenWindowsAutomatically(true);
        set.setDomStorageEnabled(true);
        set.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    @Override
    public void finish() {
        super.finish();

    }

    class SimpleWebviewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            ELog.i(TAG, "## onPageStarted : " + url);
            if (url.contains("/popup/event_detail")) {
                view.stopLoading();
                Intent intent = new Intent(EventPopupActivity.this, EventPopupDetailActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_right_enter, R.anim.activity_right_out);
                finish();
            }
            super.onPageStarted(view, url, favicon);
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            ELog.i(TAG, "## onPageFinished : " + url);
            view.loadUrl("javascript:AndroidFunction.resize(document.body.scrollHeight)");
        }
    }
    //name : AndroidFunction
    public class WebAppInterface {
        @JavascriptInterface
        public void resize(final float height) {
            //webview 안쪽 컨텐츠 사이즈에 따른 리사이징
            float webViewHeight = (height * getResources().getDisplayMetrics().density);
            ViewGroup.LayoutParams params = line_container.getLayoutParams();//컨테이너
            ViewGroup.LayoutParams btn_params = not_show_today_btn.getLayoutParams();//버튼
            params.height =  btn_params.height+((int)Math.round(webViewHeight));//컨테이너+버튼
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    line_container.setLayoutParams(params);//리사이징 : UIException이 나기 때문에 쓰레드로 구현
                }
            });

        }
    }
}

- 통신했을땐 파일이 있었으니까 바로 웹뷰로 html을 불러준다.

- 이후 resize 를 호출해 사이즈딱맞게 재정렬한다.

 

지금보니까 소스가 개판...ㅋㅋㅋ .. 가끔씩 예전소스보면서 리뷰하는것도 좋은것같네요

반응형

+ Recent posts