[Android] 도로명 주소 검색 기능

노유성·2023년 7월 18일
0
post-thumbnail

들어가며

API를 이용해서 도로명 주소를 가져오는 기능을 만들어보자.

Firebase 호스팅

먼저 API를 이용해서 도로명 주소를 가져오려면 개인 서버가 필요하다 그러므로 Firebase 서버를 호스팅하자.

프로젝트 생성 절차를 전부 밟은 다음에

npm install -g firebase-tools

cmd에 입력해서 firebase를 node로 이용하기 위한 툴을 설치한다.

로그인

firebase login

cmd에 입력해서 로그인을 해준다.

이렇게 묻는데 그냥 다 Yes하면 된다. 그런 다음 firebase에서 서버를 만들었던 계정으로 로그인을 한다.

init

firebase init


cmd에서 init을 하고나면 어떤걸 할 거냐고 묻는데 첫번째 Hosting을 선택하고 진행한다.

그런 다음 우린 프로젝트를 이미 만들었으니 Use an exsting project를 선택한다.
그 중에 우리가 만든 프로젝트를 선택 그리고 쭉 설정들을 yes하고 지나가고 깃허브에 deploy하겠냐는 것만 no를 하고 지나간다.

그 다음 public 폴더를 들어가서 index.html 파일을 변경해야한다.

html 파일 가져오기

출처 유투브 강의

일단 이 노트는 위 강의를 참조해서 만들었다. 위 강의에 가서 index.html파일을 가져온 다음, public 폴더에 덮어씌운다.

firebase deploy

그런 다음 이를 서버에 전송해주면은 android studio에서 사용하기 위한 API 서버가 열린다.

SearchActivity

public class SearchAddress extends AppCompatActivity {

	WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_address);

		init();
	}

	private void init() {
		webView = findViewById(R.id.webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new BridgeInterface(), "Android");
		webView.setWebViewClient(new WebViewClient() {
			/**
			 * Notify the host application that a page has finished loading. This method
			 * is called only for main frame. Receiving an {@code onPageFinished()} callback does not
			 * guarantee that the next frame drawn by WebView will reflect the state of the DOM at this
			 * point. In order to be notified that the current DOM state is ready to be rendered, request a
			 * visual state callback with {@link WebView#postVisualStateCallback} and wait for the supplied
			 * callback to be triggered.
			 *
			 * @param view The WebView that is initiating the callback.
			 * @param url  The url of the page.
			 */
			@Override
			public void onPageFinished(WebView view, String url) {
				// 안드로이드에서 javascript 함수 호출
				webView.loadUrl("javascript:sample2_execDaumPostcode();");
			}
		});

		// 최초 웹뷰 로드
		webView.loadUrl("https://searchaddress-c35b3.web.app");
	}

	private class BridgeInterface {
		@JavascriptInterface
		public void processDATA(String data) {
			// 카카오 주소 검색 API 결과 값을 전달받음. (from javascript)
			Intent intent = new Intent();
			intent.putExtra("data",data);
			setResult(RESULT_OK, intent);
			finish();
		}
	}
}

주소 검색을 위한 activity이다. xml 파일은 부모 레이아웃을 WebView 객체가 꽉 차게 설정을 해두었다.

위 코드를 간단하게 설명하면, html파일의 script를 이용하기 위한 설정을 init()함수에서 하고있다. 그리고 webView가 종료되었을 때 수행할 동작을 콜백함수로 지정하고 있다. BridgeInterface는 javascript에서 넘어온 코드를 받을 수 있는 통로 역할을 하고 있고 넘어온 데이터를 받아서 처리하는 메소드가 정의되어있으며 해당 함수에 annotation이 붙혀져있다.

MainActivity

private final ActivityResultLauncher<Intent> getSearchResult = registerForActivityResult(
		new ActivityResultContracts.StartActivityForResult(),
		result -> {
			// SearchAddress 로부터의 결과 값이 이곳으로 전달 된다.
			if(result.getResultCode() == RESULT_OK) {
				if (result.getData() != null) {
					String data = result.getData().getStringExtra("data");
					mText.setText(data);
				}
			}
		}
);

private View.OnClickListener Listener = new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		// API 검색창 띄우기
		Intent intent = new Intent(OpenAccount3.this, SearchAddress.class);
		getSearchResult.launch(intent);

결과값을 받아서 처리하는 런쳐와 이를 통해 activity를 실행하는 버튼으로 구성되어있다. 런처는 결과값을 받아서 결과값이 유효하면 setText 메소드를 통해 받아온 값을 view에 보여준다.

profile
풀스택개발자가되고싶습니다:)

2개의 댓글

comment-user-thumbnail
2023년 7월 18일

덕분에 좋은 정보 얻어갑니다, 감사합니다.

1개의 답글