//보내는부분
private void Fnc(File uploadFile){
try {
			String url = "Http://host/getURL";
			String charset = "UTF-8";
			File binaryFile = uploadFile;
			String boundary = Long.toHexString(System.currentTimeMillis());
			String CRLF = "\r\n";

			URLConnection connection = new URL(url).openConnection();
			connection.setDoOutput(true);
			connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

			OutputStream output = null;
			try {
				output = connection.getOutputStream();
				PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
				// Send binary file.
				writer.append("--" + boundary).append(CRLF);
				writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
				writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
				writer.append("Content-Transfer-Encoding: binary").append(CRLF);
				writer.append(CRLF).flush();
				Files.copy(binaryFile.toPath(), output);
				output.flush(); // Important before continuing with writer!
				writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

				// End of multipart/form-data.
				writer.append("--" + boundary + "--").append(CRLF).flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
			int responseCode = ((HttpURLConnection) connection).getResponseCode();
			System.out.println(responseCode); // Should be 200

		} catch (Exception e) {
			e.printStackTrace();
		}
}

//받는부분
@RequestMapping(value = "/getURL", method = RequestMethod.POST)
	private void getURL(HttpServletRequest request, HttpServletResponse response) throws Exception {

		
		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);

		File directory = CommonUtil.getImageDirectory(multipartRequest);

		Iterator<String> iterator = multipartRequest.getFileNames();
		int successCount = 0;
		while (iterator.hasNext()) {
			MultipartFile multipartFile = multipartRequest.getFile(iterator.next());
			multipartFile.getSize();

			String fileName = multipartFile.getOriginalFilename();

			File uploadFile = new File(directory, fileName);
			multipartFile.transferTo(uploadFile);
		}
	

	}
    
    
//디렉터리 생성 유틸

		//로컬
		 ServletContext servlet = request.getSession().getServletContext();
		 String root = servlet.getRealPath("/") + UPLOAD_FOLDER + File.separator;

		//서버
		//String root = "/data" + File.separator + UPLOAD_FOLDER + File.separator;

		System.out.println("root = " + root);

		String dayPath = new SimpleDateFormat("yyMMdd").format(new Date());

		dayPath = root + File.separator + dayPath;

		File dayDirectory = new File(dayPath);
		if (!dayDirectory.isDirectory()) {
			dayDirectory.mkdirs();
		}

		int subCount = dayDirectory.listFiles().length;

		if (subCount == 0) {
			String subPath = dayDirectory + File.separator + subCount;
			File subDirectory = new File(subPath);
			subDirectory.mkdirs();
			return subDirectory;
		} else {
			String subPath = dayDirectory + File.separator + (subCount - 1);
			File subDirectory = new File(subPath);
			if (subDirectory.isDirectory()) {
				if (subDirectory.listFiles().length > 0) {
					subPath = dayDirectory + File.separator + subCount;
					subDirectory = new File(subPath);
					subDirectory.mkdirs();
				}
			} else {
				subDirectory.mkdirs();
			}
			return subDirectory;
		}

 

'프로그래밍 > Java,eclipse' 카테고리의 다른 글

httpConnection 으로 데이터 받기 (저장용)  (0) 2021.07.15
이해하기 폴리곤 알고리즘  (0) 2019.05.23
eclipse SVN 설치중 오류  (0) 2019.05.02
배경 테마 바꾸기  (0) 2018.10.25
연산자의 종류  (0) 2018.10.25
window.dispatchEvent(new Event('resize'));

윈도우를 강제로 리사이즈 할 수 있습니다 .

차트 크기변경이나 

맵 api 타일 미변경에 의한 리사이즈등 사용하면 좋습니다.

popupwindow.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="300dp"
    android:gravity="center"
    android:background="#E1000000"
    android:padding="10px">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="주의"
        android:textStyle="bold"
        android:textSize="30sp"
        android:textColor="#ABF106"/>
    <TextView
        android:layout_margin="30px"
        android:id="@+id/popup_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textStyle="bold"
        android:textSize="38sp"
        android:textColor="#FCFCFC"/>

    <Button
        android:id="@+id/closePopupBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="확인"
        />
</LinearLayout>

메인 엑티비티의 레이아웃 id도 필요합니다. 

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mainLayout"
    tools:context=".activity.MainActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

mainLayout 이라고 심플하게 만들어 줬습니다.

 

mainActivity.java 

public void checkWebRoadEvent(String data0, String data1, String data2) {

        ConstraintLayout linearLayout1 = (ConstraintLayout) findViewById(R.id.mainLayout);
        LayoutInflater layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        final View customView = layoutInflater.inflate(R.layout.popupwindow, null);
        Button closeBtn = (Button) customView.findViewById(R.id.closePopupBtn);
        TextView textview = (TextView) customView.findViewById(R.id.popup_text);
        textview.setText(Messages[0] + "지도를 확인하세요.");
        popupWindow = new PopupWindow(customView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
        customView.startAnimation(animation);
        popupWindow.showAtLocation(linearLayout1, Gravity.TOP, 0, 0);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());


        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                // 원래 하려던 동작 (UI변경 작업 등)
                final Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.close);
                customView.startAnimation(animation);

                Handler mhandler = new Handler();
                mhandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                            popupWindow = null;
                        }
                    }
                }, 500);
            }
        };

        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        Message msg = handler.obtainMessage();
                        handler.sendMessage(msg);
                        Log.d("lati", "check ");
                    }
                };

                Timer timer = new Timer();
                timer.schedule(task, 5000);
            }
        });


        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = handler.obtainMessage();
                handler.sendMessage(msg);
                Log.d("lati", "check ");

            }
        });
        thread.start();
        startSound();
        
        Log.d("dialogStart", "get Show Road Event");
    }

timer , runable , thread  사용은 다른곳 참고 부탁드릴게요~ 저도 완벽한 개념을 알고 쓴게 아니라서 ㅎㅎ 저장용입니다.
popupwindow 에서 타이머 사용시 뷰를 변경할 수 없다는 오류가 뜨는데 핸들러를 통하여 한번 돌아서 사용하시면 될것 같습니다. 

 

사운드

알람은 raw 패키지 폴더 생성하고 거기에 넣으셔야합니다.

기본 알람도 사용할 수 있습니다. 따로 안적을게요~

    public void startSound() {
        MediaPlayer player = MediaPlayer.create(this, R.raw.alarm1);
        player.start();
    }

애니메이션

anum 패키지 폴더 생성후

오픈시에는 위에서 밑으로 내려오게끔 
클로즈는 오른쪽으로 없어지게 만들었습니다.

 

open.xml

<?xml version="1.0" encoding="utf-8"?>

<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromYDelta="-100%"
    android:toYDelta="0">
</translate>

 

close.xml

<?xml version="1.0" encoding="utf-8"?>

<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromXDelta="0"
    android:toXDelta="100%">
</translate>

 

 

우선 티맵을 생성하고 마커를 찍어보자.

tmapapis.sktelecom.com/

 

Guide | T MAP API

 

tmapapis.sktelecom.com

티맵 개발자 사이트 참고

 

티맵 마커의 elements 를 보면

이미지의 아이디와 네임이 따로 명시가 안된 상황,

 

여기서 이미지를 회전 시킬려면

해당 이미지의 style에 transform: rotate(회전각도);

이런식으로 사용해야하는데 마커이미지 자체를 추출하는 방법을 찾아봤다.

 

$('img').each(function(idx) {
	if($(this).prop('src').includes('http://tmapapis.sktelecom.com/upload/tmap/marker/pin_r_b_c.png')){
  	  $('img').eq(idx).css("transform","rotate(45deg)")
	}
});

전체 이미지에서 이미지 src 를 찾아 해당 이미지의 index 부분을 회전시킬 수 있다.

 

회전시킨 마커의 모습이다.

 

이미지를 예로 들었지만 다른곳에도 쓸곳이 많아 보여 글을 남깁니다.

js에서 ajax를 통해서 뷰를 그려줄때가 많다 .

 

해당 과정에서 실수

context += '<div class="c-destination"
onclick=\goworkdetail(' + SEQ + ',"' + NM+ '",' + SEQ2 + ');\>';

자바 버전에 따라 위와같은 모양이 될 수 있고 안될 수 있다, (완전 안좋은 예) 

중간에 코드가 끈기게 된다.

 

context += '<div class="c-destination" onclick="gofunction(' + SEQ + ',\'' + NM+ '\');">';​

String 형의로 받아야할 경우 \' 역슬레쉬 따옴표를 이용해 보도록 하자 

 

객체생성

public class WarningData {
    public enum WarningValue {
        SAFE, // 안전
        ATTENTION, // 관심
        CAUTION, // 주의
        WARNING, // 경고
        DANGER // 위험
    }

    private String Time;
    private String vertialdistance;
    private String ttcp;
    private WarningValue warning;

    public WarningData(String time, String vertialdistance, String ttcp, WarningValue warning) {
        Time = time;
        this.vertialdistance = vertialdistance;
        this.ttcp = ttcp;
        this.warning = warning;
    }

    public String getTime() {
        return Time;
    }

    public void setTime(String time) {
        Time = time;
    }

    public String getVertialdistance() {
        return vertialdistance;
    }

    public void setVertialdistance(String vertialdistance) {
        this.vertialdistance = vertialdistance;
    }

    public String getTtcp() {
        return ttcp;
    }

    public void setTtcp(String ttcp) {
        this.ttcp = ttcp;
    }

    public WarningValue getWarning() {
        return warning;
    }

    public void setWarning(WarningValue warning) {
        this.warning = warning;
    }
}

 

Utill class 생성

public class Util {
    public static WarningData.WarningValue getWarningValue(int risk) {
        WarningData.WarningValue value = WarningData.WarningValue.SAFE;
        switch (risk) {
            case 0:
                value = WarningData.WarningValue.SAFE;
                break;
            case 1:
                value = WarningData.WarningValue.ATTENTION;
                break;
            case 2:
                value = WarningData.WarningValue.CAUTION;
                break;
            case 3:
                value = WarningData.WarningValue.WARNING;
                break;
            case 4:
                value = WarningData.WarningValue.DANGER;
                break;
        }
        return value;
    }
}

 

통신을 통해 받아온 risk는 0,1,2,3,4 입니다.

   int risk = worningObject.getRiskMin();
                WarningData.WarningValue warningValue = Util.getWarningValue(risk);
                 warningData= new WarningData(formatDate,String.valueOf(worningObject.getDistanceMin()),String.valueOf(worningObject.getTtcpMin()),warningValue);

받아온 데이터는 객체를 통해 전달됩니다.

 

 

어뎁터사용 예시

        int color = context.getResources().getColor(R.color._2086c0);
        if (item.getWarning() == WarningData.WarningValue.SAFE) {
            holder.warningText.setText("안전");
            color = context.getResources().getColor(R.color._2086c0);
        } else if (item.getWarning() == WarningData.WarningValue.ATTENTION) {
            holder.warningText.setText("관심");
            color = context.getResources().getColor(R.color._179033);
        } else if (item.getWarning() == WarningData.WarningValue.CAUTION) {
            holder.warningText.setText("주의");
            color = context.getResources().getColor(R.color._e9c71d);
        } else if (item.getWarning() == WarningData.WarningValue.WARNING) {
            holder.warningText.setText("경고");
            color = context.getResources().getColor(R.color._c05b20);
        } else if (item.getWarning() == WarningData.WarningValue.DANGER) {
            holder.warningText.setText("위험");
            color = context.getResources().getColor(android.R.color.holo_red_dark);
        }

        holder.warningText.setTextColor(color);

 

 

엑티비티에서의 사용 예시

                if (infos != null) {
                    if (infos.getWarning() == SAFE) {
                        levelImage.setImageResource(R.drawable.warning_0);
                    } else if (infos.getWarning() == ATTENTION) {
                        levelImage.setImageResource(R.drawable.warning_1);
                    } else if (infos.getWarning() == CAUTION) {
                        levelImage.setImageResource(R.drawable.warning_2);
                    } else if (infos.getWarning() == WARNING) {
                        levelImage.setImageResource(R.drawable.warning_3);
                    } else if (infos.getWarning() == DANGER) {
                        levelImage.setImageResource(R.drawable.warning_4);
                    }
                }

 

 

다음과 같이 selector 를 담아줄 xml 생성 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/gps_good" android:state_selected="true" />
    <item android:drawable="@drawable/gps_bad" android:state_selected="false" />
</selector>

 

뷰의 이미지 설정

  <ImageView
                android:id="@+id/workGpsStateImage"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:background="@drawable/background_line"
                android:scaleType="center"
                android:src="@drawable/seletor_gps_state" />

Activity 에서 

 gpsImage = findViewById(R.id.workGpsStateImage);
 
   gpsImage.setSelected(true);
   gpsImage.setSelected(false);

 

트루펄스로 이미지 변경이 가능합니다.

double locationX = location.getLongitude();

 

받아온 좌표는 double형입니다.

String formatStringLocationX = String.format(Locale.KOREA,"%.6f", locationX);
locationX = Double.parseDouble(formatStringLocationX);

만약 좌표가 123.456 이라면 

Locale 에 따라 float 타입이 .이 콤마로 표시될 수 있다고 합니다. 이점 참고하고 작업하시길..

 

참고 블로그
fumin.tistory.com/299

 

[안드로이드] String Format 사용시 주의사항

안녕하세요 푸민입니다. 이번에 개발하다가 생긴 이슈인 String 객체의 format() 메소드에 대해서 포스팅합니다. String.format() 의 경우 많이 사용하지는 않지만 가끔 Url 같이 긴 String 을 작성할때 사��

fumin.tistory.com

 

+ Recent posts