본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/Android 기능

Android Studio(기능) LBS 2(Location Test)

by 차누감 2019. 10. 10.
반응형

Android Studio(기능) LBS과 같은 예제이지만, 코드가 다른게 만들어보자.

구글에서 만든 Fused API를 갖고 위치정보를 가져오는 앱을 만들자.

 

라이브러리 추가

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
    
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GET MY LOCATION"
        android:onClick="clickBtn"/>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="lat, lng"/>
 
 
</LinearLayout>
 
 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
 
import android.location.Location;
 
 
public class MainActivity extends AppCompatActivity {
 
    TextView tv;
 
    //Google Fused API의 클래스 참조 변수
    GoogleApiClient googleApiClient; //위치정보관리 객체[LocationManager 역할]
    FusedLocationProviderClient providerClient; //위치정보 제공자 객체[알아서 적절한 제공자 선택]
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tv=findViewById(R.id.tv);
 
        //api 23이상이면 동적퍼미션 필요
 
    }
 
    public void clickBtn(View view) {
        //위치정보객체를 만들어주는 건축가 객체 생성
        GoogleApiClient.Builder builder= new GoogleApiClient.Builder(this);
        //건축가에게 FusedAPI 사용 인증키 지정
        //건축가에게 위치정보 탐색연결 성공 리스너
        builder.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
            @Override
            public void onConnected(@Nullable Bundle bundle) {
                Toast.makeText(MainActivity.this, "위치정보 탐색을 시작합니다.", Toast.LENGTH_SHORT).show();
 
                //연결이 성공되면 위치정보 얻어오기..
 
                //위치정보 요청 객체 생성 및 설정
                LocationRequest locationRequest= LocationRequest.create();
                locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //높은 정확도 : gps
                locationRequest.setInterval(5000); //5초에 한번씩 위치정보 갱신
 
                providerClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
 
            }
 
            @Override
            public void onConnectionSuspended(int i) {
                Toast.makeText(MainActivity.this, "위치정보 탐색연결을 잠시 대기합니다.", Toast.LENGTH_SHORT).show();
            }
        });
 
        //연결실패 콜백리스너 추가
        builder.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                Toast.makeText(MainActivity.this, "위치정보 탐색 연결 실패", Toast.LENGTH_SHORT).show();
            }
        });
 
        //건축가에게 위치정보 관리 객체 생성 요청
        googleApiClient= builder.build();
 
        //위치정보 관리 객체에게 위치정보연결 시도
        googleApiClient.connect();
 
        //위치정보의 실시간 위치정보 취득을 위해 위치정보 제공자 소환
        providerClient=LocationServices.getFusedLocationProviderClient(this);
    }
 
    //위치정보 결과 콜백 리스너 객체
    LocationCallback locationCallback= new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
 
            Location location= locationResult.getLastLocation();
            double latitude=location.getLatitude();
            double longitude=location.getLongitude();
 
            tv.setText(latitude+" , "+longitude);
        }
    };
 
    //화면에서 보이지 않으면 더이상 위치정보를
    //업데이트 하지 않도록.
    @Override
    protected void onPause() {
        super.onPause();
 
        if(providerClient!= null){
            providerClient.removeLocationUpdates(locationCallback);
        }
    }
}
 
 
 

반응형

댓글