2016년 8월 4일 목요일

Android Studio - LBS(Location Based Service) 프로그래밍 - 1



[위치정보 가져오기]

위치정보는 Android 위치정보 표준 API를 이용하는 방법이 있고, Fused Location을 이용하는 방법이 있다.
표준 API는 다양한 Location Provider를 자유롭게 이용할 수 있는 반면에, 개발하는 동안에 고려해서 처리해야 하는 부분이 너무 많다.
그래서 보다 편리한 개발을 위해서 활용할 수 있는 Fused Location을 이용하자.

Fused Location은 Google Play 라이브러리를 Dependency에 추가해야지 사용할 수 있다.

Graddle 에 dependency 추가
프로젝트 익스플로러에서 '모듈 우클릭' -> 'open module setting' -> 'dependency 탭 선택' -> '우측의 + 버튼 클릭'

com.google.android.gms:play-services:9.2.1 추가

Graddle에 추가된 것 확인

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.4.0'    compile 'com.google.android.gms:play-services:9.2.1'}


MainActivity.java

package com.example.ch5_lbs;

import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationServices;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;


public class MainActivity extends AppCompatActivity        implements GoogleApiClient.ConnectionCallbacks,
                    GoogleApiClient.OnConnectionFailedListener{

    TextView providerTextView;
    ImageView onOffImageView;
    TextView timeTextView;
    TextView locationTextView;
    TextView accuracyTextView;

    GoogleApiClient googleApiClient;
    FusedLocationProviderApi fusedLocationProviderApi;
    Location currentlocation;

    @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        providerTextView = (TextView) findViewById(R.id.txt_location_provider);
        onOffImageView = (ImageView) findViewById(R.id.img_location_on_off);
        timeTextView = (TextView) findViewById(R.id.gps_time);
        locationTextView = (TextView) findViewById(R.id.gps_location);
        accuracyTextView = (TextView) findViewById(R.id.gps_accuracy);

        /**         * Fused API는 실제 google play service라이브러리에서 제공되는 기능으로         * google의 다양한 service를 활용하기 위한 라이브러리이다.         * 그중 locationservice쪽을 이용하겠다고 선언         */        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        fusedLocationProviderApi = LocationServices.FusedLocationApi;
    }

    private void toast(String msg){
        Toast t=Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        t.show();
    }

    private String getDateTime(long time) {
        if (time == 0)
            return "";

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return formatter.format(new java.util.Date(time));
    }

    private String convertDouble(double input) {
        DecimalFormat format = new DecimalFormat(".######");
        return format.format(input);
    }

    /**     * 위치정보 획득후 호출     * 매개변수의 정보대로 다양한 정보 추출하고 화면 출력 역할     */    private void updateInfo(Location location){
        onOffImageView.setImageResource(R.drawable.on);
        timeTextView.setText(getDateTime(location.getTime()));
        locationTextView.setText("LAT:" + convertDouble(location.getLatitude())
                                +" LNG:" + convertDouble(location.getLongitude()));
        accuracyTextView.setText(location.getAccuracy() + " meters");
    }

    @Override    protected void onResume() {
        super.onResume();
        googleApiClient.connect();  // 겨리과는 callback함수 호출로    }

    @Override    protected void onPause() {
        super.onPause();
        if(googleApiClient.isConnected()){
            googleApiClient.disconnect();
        }
    }

    @Override    public void onConnected(@Nullable Bundle bundle) {
        // 위치값 획득        Location location = fusedLocationProviderApi.getLastLocation(googleApiClient);
        if(location != null){
            currentlocation = location;
            updateInfo(location);
        }
    }

    @Override    public void onConnectionSuspended(int i) {
        toast("onConnectionSuspended");
    }

    @Override    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        toast("onConnectionFailed");
    }
}


댓글 없음:

댓글 쓰기