오늘이라도
[Android] 26. 구글 지도 연동, 현재 위치 표시, 장소 검색, 특정 위치에 마커 추가 / 와이파이, 데이터 연결 확인 본문
취업성공패키지 SW 개발자 교육/Android
[Android] 26. 구글 지도 연동, 현재 위치 표시, 장소 검색, 특정 위치에 마커 추가 / 와이파이, 데이터 연결 확인
upcake_ 2020. 6. 12. 13:07반응형
https://github.com/upcake/Class_Examples
교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다.
gif 파일은 클릭해서 보는 것이 정확합니다.
- 구글 지도 연동, 현재 위치 표시, 장소 검색, 특정 위치에 마커 추가 -
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.my38_locationmap"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.android.gms:play-services:12.0.1'
implementation 'com.android.support:multidex:1.0.3'
}
▲build.gradle(:app)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.my38_locationmap">
<!--필요한 권한 생성-->
<permission android:name="com.example.my38_locationmap.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<!--권한 부여 설정-->
<uses-permission android:name="com.example.my38_locationmap.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name="androidx.multidex.MultiDexApplication">
<!--라이브러리 사용 설정-->
<uses-library android:name="com.google.android.maps"/>
<uses-library android:name="org.apache.http.legacy"
android:required="false"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="개인 API 키"/>
<!--value는 API키-->
<meta-data
android:name="com.google.android.gms.vision"
android:value="@integer/google_play_services_version"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
▲AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginStart="6dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="317dp"
android:layout_marginRight="317dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="6dp"
android:text="위치 확인"
android:textSize="14sp"/>
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:layout_marginEnd="95dp"
android:ems="10"
android:hint="한글 주소 입력"
android:inputType="textPersonName"
android:layout_alignParentRight="true"
android:layout_marginRight="95dp" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="7dp"
android:layout_marginEnd="2dp"
android:text="확인"
android:layout_alignParentRight="true"
android:layout_marginRight="2dp" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/button1">
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</FrameLayout>
</RelativeLayout>
▲activity_main.xml
package com.example.my38_locationmap;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//로그캣 사용 설정
private static final String TAG = "MainActivity";
//객체 선언
SupportMapFragment mapFragment;
GoogleMap map;
Button btnLocation, btnKor2Loc;
EditText editText;
MarkerOptions myMarker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//권한 설정
checkDangerousPermissions();
//객체 초기화
editText = findViewById(R.id.editText);
btnLocation = findViewById(R.id.button1);
btnKor2Loc = findViewById(R.id.button2);
//지도 프래그먼트 설정
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady: ");
map = googleMap;
map.setMyLocationEnabled(true);
}
});
MapsInitializer.initialize(this);
//위치 확인 버튼 기능 추가
btnLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestMyLocation();
}
});
btnKor2Loc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(editText.getText().toString().length() > 0) {
Location location = getLocationFromAddress(getApplicationContext(), editText.getText().toString());
showCurrentLocation(location);
}
}
});
}
private Location getLocationFromAddress(Context context, String address) {
Geocoder geocoder = new Geocoder(context);
List<Address> addresses;
Location resLocation = new Location("");
try {
addresses = geocoder.getFromLocationName(address, 5);
if((addresses == null) || (addresses.size() == 0)) {
return null;
}
Address addressLoc = addresses.get(0);
resLocation.setLatitude(addressLoc.getLatitude());
resLocation.setLongitude(addressLoc.getLongitude());
} catch (Exception e) {
e.printStackTrace();
}
return resLocation;
}
private void requestMyLocation() {
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
long minTime = 1000; //갱신 시간
float minDistance = 0; //갱신에 필요한 최소 거리
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
showCurrentLocation(location);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
});
} catch (SecurityException e) {
e.printStackTrace();
}
}
private void showCurrentLocation(Location location) {
LatLng curPoint = new LatLng(location.getLatitude(), location.getLongitude());
String msg = "Latitutde : " + curPoint.latitude
+ "\nLongitude : " + curPoint.longitude;
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
//화면 확대, 숫자가 클수록 확대
map.animateCamera(CameraUpdateFactory.newLatLngZoom(curPoint, 15));
//마커 찍기
Location targetLocation = new Location("");
targetLocation.setLatitude(37.4937);
targetLocation.setLongitude(127.0643);
showMyMarker(targetLocation);
}
//------------------권한 설정 시작------------------------
private void checkDangerousPermissions() {
String[] permissions = {
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_WIFI_STATE
};
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for (int i = 0; i < permissions.length; i++) {
permissionCheck = ContextCompat.checkSelfPermission(this, permissions[i]);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
break;
}
}
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "권한 있음", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "권한 없음", Toast.LENGTH_LONG).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
Toast.makeText(this, "권한 설명 필요함.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, permissions, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1) {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, permissions[i] + " 권한이 승인됨.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, permissions[i] + " 권한이 승인되지 않음.", Toast.LENGTH_LONG).show();
}
}
}
}
//------------------권한 설정 끝------------------------
private void showMyMarker(Location location) {
if(myMarker == null) {
myMarker = new MarkerOptions();
myMarker.position(new LatLng(location.getLatitude(), location.getLongitude()));
myMarker.title("◎ 내위치\n");
myMarker.snippet("여기가 어디지?");
myMarker.icon(BitmapDescriptorFactory.fromResource(R.drawable.mylocation));
map.addMarker(myMarker);
}
}
}
▲MainActivity.java
- 와이파이, 데이터 연결 확인 -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.my39_isnetwork">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
▲AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="연결 상태 확인"
android:textSize="24sp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TextView"
android:textSize="24sp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
▲activity_main.xml
package com.example.my39_isnetwork;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button1;
WifiReceiver wifiReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkConnectivity();
}
});
wifiReceiver = new WifiReceiver();
}
private void checkConnectivity() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
if(info.getType() == ConnectivityManager.TYPE_WIFI) {
println("WIFI로 설정됨");
} else if(info.getType() == ConnectivityManager.TYPE_MOBILE) {
println("일반 망으로 설정됨");
}
println("연결 여부 : " + info.isConnected());
} else {
println("데이터 통신 불가");
}
}
private void println(String str) {
textView.append(str + "\n");
}
class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
if(state == WifiManager.WIFI_STATE_ENABLED) {
println("Wifi enabled");
} else if (state == WifiManager.WIFI_STATE_DISABLED) {
println("Wifi disabled");
}
} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
String ssid = manager.getConnectionInfo().getSSID();
if (info.getState() == NetworkInfo.State.CONNECTED) {
println("Connected : " + ssid);
} else if(info.getState() == NetworkInfo.State.DISCONNECTED) {
println("Disconnected : " + ssid);
}
}
}
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiReceiver);
}
}
▲MainActivity.java
반응형
'취업성공패키지 SW 개발자 교육 > Android' 카테고리의 다른 글
[Do it! 안드로이드] I. Hello! 안드로이드 / 01. 안드로이드란? / 01-1. 안드로이드 이해하기 / 01-2. 안드로이드의 흐름 살펴보기 (0) | 2020.06.15 |
---|---|
[Android] 27. 진동 울리기, 소리 울리기, 짧은 음악 파일 재생 / 알림 띄우기 (0) | 2020.06.15 |
[Android] 25. 동영상 재생 / 유튜브 재생 : API 라이브러리 다운, API키 생성 (0) | 2020.06.11 |
[Android] 24. 녹음 후 재생 / 사진 촬영 후 화면에 출력 (0) | 2020.06.10 |
[Android] 23. Navigation Drawer / 오디오 재생, 정지, 일시정지, 재시작 (0) | 2020.06.09 |