Google Adsense를 블로그에 연결하고 나타나는 광고를 선택적으로 차단하는 방법 중 광고 네트워크 항목이 있습니다위치는 애드센스에 로그인 하고 좌측 메뉴에서

차단관리> 콘텐츠 > 모든사이트 를 선택합니다.


구글 애드센스 광고 네트워크


우측에 메뉴가 예전에는 탭이었는데 모양이 최근에 변경 되었네요. [광고 네트워크 관리]를 선택 합니다.


구글 애드센스 광고 네트워크


[광고 네트워크] 설정 화면입니다간단하게 사용법을 알아 보겠습니다.

 

1. 페이지를 이용 차단


[광고 네트워크] 메뉴의 하단에 한번에 보여주는 리스트 개수와 페이지를 이동하는 버튼이 있습니다이걸 이용하여 눈으로 하나씩 검사하여 차단 하려는 광고를 차단 합니다.


구글 애드센스 광고 네트워크


차단 방법은 우측에 있는 [허용됨] 버튼을 클릭 하면 예전에는 동일한 위치에서 차단됨으로만 표시가 되었는데 지금은 [차단됨] 표시도 하고 차단된 광고는 별도로 위에 모아서 표시를 해주고 있습니다.


구글 애드센스 광고 네트워크


차단한 광고를 허용 하려면 당연히 차단된 네트워크에서 [차단됨] 버튼을 클릭 하면 됩니다이렇게 하나씩 차단하는데 다음 페이지를 보기 위해 ‘>’를 누르면 텍스트인데도 이상하게 리스트가 나오는 속도가 좀 느립니다.   이미지를 보면서 차단하는 미검토 광고가 느린건 이해가 되는데 텍스트를 보여주는 화면도 느립니다아무래도 구글에서 광고 선별 차단 설정 하는 것을 않좋아 하는것 같습니다.

 

2. 검색을 이용한 차단

 

페이징을 이용하여 한 페이지씩 보면서 하는 건 생각보다 시간이 많이 소요되고 어디까지 봤는지 나중에는 잘 기억이 나지 않습니다그래서 좀더 편한 방법이 검색을 통한 차단을 하는것 입니다키워드를 입력하고 검색 버튼을 누르면 팝업과 함께 검색이 되는데 여기서 바로 차단을 시킵니다.


구글 애드센스 광고 네트워크


2.1 키워드 선택


그럼 어떤 키워드를 사용하면 될까요제일 처음에 하는건 각 국가별 도메인 약어를 이용 합니다동일한 회사에서 각 나라별 광고를 보유하고 있습니다.  


구글 애드센스 광고 네트워크


이렇게 괄호 안에 여러 버전이 존재 합니다. 여기에 보이는 것 이외에 (JP), (RU), (TW), (UK)등등 w자신의 블로그에 나타나는 국가의 도메인을 사용하면 됩니다이렇게 키워드를 사용하여 외국 광고를 차단을 하고 2차로는 페이징을 이용하여 하나씩 보면서 차단을 해야 합니다왜냐하면 검색에 안걸리는 광고네트워크도 있습니다.

 

2.2 미검토 광고 이용 차단


광고네트워크에서 외국 도메인을 차단하는데 외국 도메인이 아닌 경우는 어떻게 차단 해야 할까요이건 광고 심사 센터에 있는 미검토 광고를 이용해서 차단 합니다.

미검토 광고에 들어가 보면 영어도 아닌 모르는 언어 광고가 나오는 경우가 있습니다.


구글 애드센스 광고 네트워크


광고를 클릭하면 상세 정보를 볼 수 있습니다.


구글 애드센스 광고 네트워크


우측의 광고차단 버튼은 현재의 광고만 차단한다는 것이고 바로 위에 있는 계정 차단은 그 계정을 통해서 들어오는 모든 광고는 모두 차단 한다는 의미 입니다계정차단을 누르면 [차단된 Google Ads 계정] 팝업이 나타나고 그곳에 포함이 됩니다.


구글 애드센스 광고 네트워크


스크롤을 해보면 지금까지 차단한 계정들을 볼 수 있고 차단 해제 버튼을 누르면 다시 그곳에서보내는 광고가 블로그에 나타 납니다저는 위와 같이 일본, 중국어는 일단 차단을 했습니다

그리고 도착 URL이 있는데 바로 이 도메인을 키워드로 사용해서 광고네트워크의 검색 기능을 사용 하고 차단을 하면 됩니다.

 

3. 결론

 

- 2, 3개월 동안 일본어, 중국어, 러시아어, 아랍어 등은 차단을 했습니다검색을 통해서 하고 페이징을 이용해서 다시한번 이잡듯이 차단하고 미검토 광고를 이용하여 차단하고 그래도 계속해서 외국어 광고가 나옵니다.

- 한국어 광고와 믿을 수 있는 도메인을 남기고 네트워크 광고의 95% 정도를 차단 해 봅니다그래도 외국어 광고가 나옵니다.

- [네트워크 광고]를 모두 차단 합니다그래도 외국어 광고가 나옵니다.

[네트워크 광고]를 모두 차단해도 외국어 광고가 나오는 이유는 상단에 나와 있습니다.


구글 애드센스 광고 네트워크


Google 인증 신규 광고 네트워크를 자동으로 허용

신규 광고는 허용으로 되어 있어 계속 신규 광고가 나오기 떄문에 그렇습니다.

- 광고 네트워크와 신규 광고 네트워크를 모두 차단 합니다그래도 한동안 광고가 나옵니다.(적용 기간이 있는것 같습니다.) 그러다가 광고가 완전히 차단 됩니다광고 사이즈와 관계 없이 블로그에서 완전히 광고가 차단이 됩니다.

- 광고 네트워크를 이용해서 외국어 광고를 차단 하는건 안될것 같습니다.

- 지금은 그냥 모두 풀어 놓고 미검토 광고의 [계정 차단]을 해놓은 것만 유지하고 있습니다그랬더니 일본어, 중국어 광고는 많이 줄었습니다.

- 위의 내용은 3개월 정도 개인적인 테스트 였습니다다른 사람은 다른 결론이 나올 수도 있겠지만 신규광고까지 알아서 차단 하는 건 [광고 네트워크]를 이용해서는 어려운 것 같습니다.


- copy coding -


Serverandroid app간에 데이터를 주고 받는 작업이 필요하여 간단하게 샘플 작업을 해보았습니다인터넷에 많은 예제가 널려 있는데 하나 더 던져 봅니다.  IPPC에 설정된 것으로 사용을 하기 위해 PC에 설정된(자동으로 잡히도록 되어 있으므로 다음에는 변할 수 있지만) 값을 찾아 봅니다.  ipconfig/all 명령으로 찾으면 됩니다.


andriod eclipse socket


 

1. Eclipse Server

 

서버에서는 IP는 사용하지 않고 port 번호만으로 접속 대기 상황을 만들면 됩니다그리고 client에서 연결 요청과 데이터가 들어오면 다시 보내주는 작업을 진행 합니다.

 

//client 접속 대기

Socket client = serverSocket.accept();

//client data 수신

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

String str = in.readLine();

//client 다시 전송

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

out.println("Server Received : '" + str + "'");

 

2. Android Client

 

Client 에서는 화면작업이 좀 있습니다그리고 문자를 입력 받아 서버에 보내주고 다시 받아오는 작업을 진행 합니다.

 

//소켓 생성
InetAddress serverAddr = InetAddress.getByName(ip);
 
socket =  new Socket(serverAddr,port);
//입력 메시지
String sndMsg = et.getText().toString();
//데이터 전송
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(sndMsg);
//데이터 수신
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String read = input.readLine();

 

그리고 인터넷을 사용하므로 Manifest.xml에 권한 설정을 해주면 됩니다.

 

<uses-permission android:name="android.permission.INTERNET" />

 

  

3. 결과 화면

 

안드로이드 클라이언트 화면입니다문자 입력과 전송버튼 그리고 서버로 부터 받은 데이터를 화면에 출력하는 기능이 있습니다.


andriod eclipse socket


이런... Connet 버튼은 테스트하려고 만들었는데 사용하지 않습니다삭제 안했네요.

 

서버쪽은 클라이언트에서 보내온 데이터를 콘솔에 출력만 합니다.


andriod eclipse socket


소스가 간단해서 설명도 간단 하네요.

 

4. 전체 소스

 

4.1 Eclipse Server

 

package egovframework.admin.chart.web;

 

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.ObjectOutputStream;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

 

public class TCPServer implements Runnable {

 

             public static final int ServerPort = 9999;

//    public static final String ServerIP = "192.168.0.6";

 

             @Override

             public void run() {

                           try {

            System.out.println("Connecting...");

            ServerSocket serverSocket = new ServerSocket(ServerPort);

 

            while (true) {

                     //client 접속 대기

                Socket client = serverSocket.accept();

                System.out.println("Receiving...");

                try {

                   //client data 수신

                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

                    String str = in.readLine();

                    System.out.println("Received: '" + str + "'");

                    //client에 다시 전송

                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

                    out.println("Server Received : '" + str + "'");

                   

                } catch (Exception e) {

                    System.out.println("Error");

                    e.printStackTrace();

                } finally {

                    client.close();

                    System.out.println("Done.");

                }

            }

        } catch (Exception e) {

            System.out.println("S: Error");

            e.printStackTrace();

        }

             }

            

             public static void main(String[] args) {

        Thread ServerThread = new Thread(new TCPServer());

        ServerThread.start();

     }

}

 

4.2 안드로이드 Client

 

activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
   
tools:context=".MainActivity">

    <
TextView
       
android:id="@+id/TextView01"
       
android:layout_width="fill_parent"
       
android:layout_height="wrap_content" />

    <
EditText
       
android:id="@+id/EditText01"
       
android:layout_width="289dp"
       
android:layout_height="wrap_content"
       
android:layout_marginStart="92dp"
       
app:layout_constraintStart_toStartOf="@+id/Button01"
       
tools:layout_editor_absoluteY="0dp" />

    <
Button
       
android:id="@+id/Button01"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Send" />

    <
Button
       
android:id="@+id/button02"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginEnd="16dp"
       
android:layout_marginTop="456dp"
       
android:text="Connect"
       
app:layout_constraintEnd_toEndOf="parent"
       
app:layout_constraintTop_toTopOf="parent" />

    <
TextView
       
android:id="@+id/chatTV"
       
android:layout_width="fill_parent"
       
android:layout_height="381dp"
       
android:layout_marginTop="64dp"
       
app:layout_constraintTop_toTopOf="@+id/TextView01"
       
tools:layout_editor_absoluteX="0dp" />
</
android.support.constraint.ConstraintLayout>

 

 

AndroidManifest.xml

 

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

    <
uses-permission android:name="android.permission.INTERNET" />

    <
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>

 

 

MainActivity.java


package com.example.tcpclient;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class MainActivity extends AppCompatActivity {

   
private Handler mHandler;
    Socket
socket;
   
private String ip = "192.168.0.6"; // IP 주소
   
private int port = 9999; // PORT번호
   
EditText et;
    TextView
msgTV;

   
@Override
   
protected void onStop() {
       
super.onStop();
       
try {
           
socket.close();
        }
catch (IOException e) {
            e.printStackTrace();
        }
    }

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

       
mHandler = new Handler();

       
et = (EditText) findViewById(R.id.EditText01);
        Button btn = (Button) findViewById(R.id.
Button01);
        Button btnCon = (Button)findViewById(R.id.
button02);
       
final TextView tv = (TextView) findViewById(R.id.TextView01);
       
msgTV = (TextView)findViewById(R.id.chatTV);

        btn.setOnClickListener(
new View.OnClickListener() {
           
public void onClick(View v) {
               
if (et.getText().toString() != null || !et.getText().toString().equals("")) {
                    ConnectThread th =
new ConnectThread();
                    th.start();
                }
            }
        });
    }

   
class ConnectThread extends Thread{
       
public void run(){
           
try{
               
//소켓 생성
               
InetAddress serverAddr = InetAddress.getByName(ip);
                
socket new Socket(serverAddr,port);
               
//입력 메시지
               
String sndMsg = et.getText().toString();
                Log.d(
"=============", sndMsg);
               
//데이터 전송
               
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                out.println(sndMsg);
               
//데이터 수신
               
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String read = input.readLine();
               
//화면 출력
               
mHandler.post(new msgUpdate(read));
                Log.d(
"=============", read);
               
socket.close();
            }
catch(Exception e){
                e.printStackTrace();
            }
        }
    }
   
// 받은 메시지 출력
   
class msgUpdate implements Runnable {
       
private String msg;
       
public msgUpdate(String str) {
           
this.msg = str;
        }
       
public void run() {
           
msgTV.setText(msgTV.getText().toString() + msg + "\n");
        }
    };
}

 

- copy coding -


예전에 초창기 GPS 관련 자료를 얻기 위해 세미나를 찾아 다니고 자료를 수집할 때

우리나라에는 위성이 없으니 얻어 써야 하고 GPS 정보 자체가 군용으로 사용되고 있어서

일부러 오차를 약 20m 정도 나도록 신호를 주고 있다고 했었습니다.

그래서 그 20m를 보정하는 것 자체가 큰 기술이라고 했는데 이제는 핸드폰에서 아무때나

꺼내서 사용할 수 있게 되었으니 참 신기한 일입니다.

물론 그동안 수많은 지도 업체와 네비 업체가 문을 닫았지요.



1. 좌표값 생성


위치정보를 구하는 방법은 2가지가 있습니다.


1.1 GPS Provider


3각 측량의 방법으로 좌표를 위성을 이용하여 취득합니다.

그러므로 위성의 전파를 잡지 못하는 실내에서는 사용이 어렵고 실외에서는 건물 또는

계곡이 깊으면 전파를 잡기 어려워 위치를 잡지 못할 수 있습니다.


1.2 Network Provider


이동통신 기지국 또는 WiFi  access point들을 이용하여 측정을 있습니다.


1.3 Passive Provider


위치를 구하는 방법이 2가지라고 했는데 Passive 방식은 좌표를 직접 구하는 것이 아니고

다른 어플리케이션이나 서비스가 좌표 값을 구하면 단순히 값을 받아 오기만 하는

전달자 역할을 하기 때문에 값을 얻을 수는 있지만 구한다고는 없습니다.



2. LocationManager 개요



2.1 Permission


모바일 기기의 장치를 사용하려면 사용 허가가 필요합니다.

provider 별 사용 허가에 대한 변수들 입니다.

대부분 ACCESS_FINE_LOCATION 이거 하나면 권한을 받을 수 있습니다.


 Provider

 permission

 GPS

 android.permission.ACCESS_FINE_LOCATION

 Network

 android.permission.ACCESS_COARSE_LOCATION 또는

 android.permission.ACCESS_FINE_LOCATION

 Passive

 android.permission.ACCESS_FINE_LOCATION



2.2 Provider


Type 

 Parameter

 설명

 String

 GPS_PROVIDER

 GPS를 이용 위치 제공

 String

 NETWORK_PROVIDER

 기지국, WiFi를 이용 위치 제공

 String

 TYPE_STEP_COUNTER

 기존 좌표값 이용 위치 제공



2.3 Method


Type

 Method / 설명

 List

 getAllProviders()

  - 모든 Provider 정보를 리턴 한다.

 LocationProvider

 getProvider(String name)

  - 명칭(name)에 대한 Provider 정보를 리턴 한다.

 List

 getProviders(boolean enabledOnly)

  - true를 입력하면 현재 사용 가능한 Provider의 목록을 리턴 합니다.

  - false를 입력하면 비활성화 포함 모든 Provider의 목록을 리턴 합니다.

 boolean

 isProviderEnabled(String provider)

  - 입력한 Provider의 명칭에 대한 사용 가능 여부를 리턴 합니다.

 void

 removeUpdates(LocationListener listener)

  - 더 이상 위치 정보가 필요 없을 때 위치 정보 수집을 종료 시킵니다.

 void

 requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

  - Provider를 등록하고 기입한 거리와 시간의 변동이 있을 때 마다 update 된 위치 정보를 리턴 합니다.



3. Location 프로그램



그럼 좌표 값을 얻기가 얼마나 쉬운지 한번 알아보도록 하겠습니다.



3.1 신규 프로젝트 생성


프로젝트 명을 적당하게 명명해서 생성 하고 기타 설정 사항도 본인의 기호에 맞게 설정 하여 신규 프로젝트를 하나 생성 합니다.

저는 항상 DeviceAndroid 4.0을 선택 하고



Activity Empty로 설정 합니다.




3.2 Permission


장치 사용에 대한 권한 허가는 두개 다 적어 줍니다.


AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


3.3 Layout 작성

 

지금까지 Layout은 그냥 TextView를 죽 나열하는 방식으로 작업 했는데

이번에는 기입 하는게 많고 우측 정렬도 필요해서 GridLayout을 사용했습니다.


<GridLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:columnCount="2"
    app:layout_constraintTop_toBottomOf="@+id/tvTitle"
    >

참고로 여기서는 그냥 android:columnCount=”2” 이것만 보시면 됩니다.

컬럼이 2개 이니까 아래에 나열된 TextView들은 자동으로 2개씩 나누어져서 하나의 Row를 만듭니다.

HTMLTable tag보다 참 편하죠.

 

3.4 MainActivity.java


- 권한 설정


이미 Manifest에 권한을 추가 했지만 Android 6.0 부터는 source 안에도 권한에 대한 체크를 해야 한다는군요.

저는 location를 사용하는 모든 곳에 추가를 했습니다.

안그러면 실행은 되는데 빨간 줄이 자꾸 나와서 눈에 거슬리더군요


if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    //권한이 없을 경우 최초 권한 요청 또는 사용자에 의한 재요청 확인
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION) &&
            ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
        // 권한 재요청
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
        return;
    } else {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
        return;
    }
}

- 초기 좌표값


프로그램이 시작되면 우선 초기 좌표 값을 기록하도록 했습니다.


Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
    double lng = lastKnownLocation.getLongitude();
    double lat = lastKnownLocation.getLatitude();
    Log.d(TAG, "longtitude=" + lng + ", latitude=" + lat);
    tvGpsLatitude.setText(":: " + Double.toString(lat ));
    tvGpsLongitude.setText((":: " + Double.toString(lng)));
}

그리고 초기 값을 나타낼 때만 중간에 콜론을 두개 찍었는데( :: ) 이러면 초기값이 그대로 인지

아니면 변경된 값을 얻어오는지 확인을 할 수 있습니다.

 

- Provider 작동 확인


기기에 어떤 Provider들이 있는지 값을 가져오고


listProviders = locationManager.getAllProviders();

Provider별 작동 여부를 확인 하여 Update가 되도록 합니다.

requestLocationUpdates()의 두번 째 값은 갱신 시간이고 세번 째 값은 갱신 이동 거리입니다.

저는 둘다 0으로 해서 계속 값을 갱신 하도록 했습니다.

이렇게요.


if(listProviders.get(i).equals(LocationManager.GPS_PROVIDER)) {
    isEnable[0] = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    tvGpsEnable.setText(": " +  String.valueOf(isEnable[0]));

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}

- LocationChange


onLocationChanged(Location location)에서 이동을 하면 좌표 값이 변경되고 변경된 좌표를 얻어옵니다.


if(location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    tvGpsLatitude.setText(": " + Double.toString(latitude ));
    tvGpsLongitude.setText((": " + Double.toString(longitude)));
    Log.d(TAG + " GPS : ", Double.toString(latitude )+ '/' + Double.toString(longitude));
}

- 수집 중단


어플리케이션을 사용하지 않을 때는 더 이상 좌표 수집을 하지 않도록 중단해야 합니다.

안그러면 계속 백그라운드에서 작업을 하여 리소스를 잡아먹겠죠.


locationManager.removeUpdates(this);



4. 결과



4.1 결과 화면


GPS는 잘 잡히는데 Network은 안잡히는 걸로 나오네요.


gps network provider android


구해진 좌표 값은 google map과 연동하면 바로 위치를 확인 할 수 있습니다.

실제로 google map과 연동 테스트를 하려면 구글에 회원 가입을 하고

맵을 사용하겠다고 해서 API 키값을 받아야 합니다.

귀찮으니 그냥 간단하게 구글 맵에서 위치를 확인 할 수 있는데요.

구글 지도를 웹으로 열면 주소창의 URL에 좌표가 같이 나타 납니다.

그럼 거기에 핸드폰으로 구한 좌표를 콤마로 구분해서 변경해 주면 위치를 확인할 수 있습니다.

 

https://www.google.com/maps/@37.5555062,126.7976293,14z




4.2 Source Code


LocProvider.7z



4.3 APK File


LocProvider.apk




5. Full Source Code


원래 취지대로 그냥 복사해서 붙여넣기를 해서 사용할 때를 위해 전체 소스를 남김니다



5.1 AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.desk.locprovider">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <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>


5.2 activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Location Test"
        android:layout_marginTop="20dp"
        android:textSize="30dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:columnCount="2"
        app:layout_constraintTop_toBottomOf="@+id/tvTitle"
        >

        <TextView
            android:id="@+id/tvGpsEnableLabel"
            android:layout_gravity="right"
            android:text="GPS Enable "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvGpsEnable"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvNetworkEnableLabel"
            android:layout_gravity="right"
            android:text="Network Enable "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvNetworkEnable"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvPassiveEnableLabel"
            android:layout_gravity="right"
            android:text="Passive Enable "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvPassiveEnable"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvGpsLocationLabel"
            android:layout_gravity="right"
            android:text="GPS Location "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvGpsLocation"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvGpsLatitudeLabel"
            android:layout_gravity="right"
            android:text="GPS Latitude "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvGpsLatitude"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvGpsLongitudeLabel"
            android:layout_gravity="right"
            android:text="GPS Longitude "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvGpsLongitude"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvNetworkLocationLabel"
            android:layout_gravity="right"
            android:text="Network Location "
            android:textSize="20dp"
        />
        <TextView
            android:id="@+id/tvNetworkLocation"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvNetworkLatitudeLabel"
            android:layout_gravity="right"
            android:text="Network Latitude "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvNetworkLatitude"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvNetworkLongitudeLabel"
            android:layout_gravity="right"
            android:text="Network Longitude "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvNetworkLongitude"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvPassiveLocationLabel"
            android:layout_gravity="right"
            android:text="Passive Location "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvPassiveLocation"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvPassiveLatitudeLabel"
            android:layout_gravity="right"
            android:text="Passive Latitude "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvPassiveLatitude"
            android:text=""
            android:textSize="20dp"
            />

        <TextView
            android:id="@+id/tvPassivekLongitudeLabel"
            android:layout_gravity="right"
            android:text="Passive Longitude "
            android:textSize="20dp"
            />
        <TextView
            android:id="@+id/tvPassivekLongitude"
            android:text=""
            android:textSize="20dp"
            />
    </GridLayout>
</android.support.constraint.ConstraintLayout>


5.3 MainAcitvity.java


package com.example.desk.locprovider;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity implements LocationListener {

    private LocationManager locationManager;
    private List<String> listProviders;
    private TextView tvGpsEnable, tvNetworkEnable, tvPassiveEnable, tvGpsLatitude, tvGpsLongitude;
    private TextView tvNetworkLatitude, tvNetworkLongitude, tvPassiveLatitude, tvPassivekLongitude;
    private String TAG = "LocationProvider";

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

        tvGpsEnable = (TextView)findViewById(R.id.tvGpsEnable);
        tvNetworkEnable = (TextView)findViewById(R.id.tvNetworkEnable);
        tvPassiveEnable = (TextView)findViewById(R.id.tvPassiveEnable);
        tvGpsLatitude = (TextView)findViewById(R.id.tvGpsLatitude);
        tvGpsLongitude = (TextView)findViewById(R.id.tvGpsLongitude);
        tvNetworkLatitude = (TextView)findViewById(R.id.tvNetworkLatitude);
        tvNetworkLongitude = (TextView)findViewById(R.id.tvNetworkLongitude);
        tvPassiveLatitude = (TextView)findViewById(R.id.tvPassiveLatitude);
        tvPassivekLongitude = (TextView)findViewById(R.id.tvPassivekLongitude);

        //권한 체크
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocation != null) {
            double lng = lastKnownLocation.getLongitude();
            double lat = lastKnownLocation.getLatitude();
            Log.d(TAG, "longtitude=" + lng + ", latitude=" + lat);
            tvGpsLatitude.setText(":: " + Double.toString(lat ));
            tvGpsLongitude.setText((":: " + Double.toString(lng)));
        }
        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (lastKnownLocation != null) {
            double lng = lastKnownLocation.getLongitude();
            double lat = lastKnownLocation.getLatitude();
            Log.d(TAG, "longtitude=" + lng + ", latitude=" + lat);
            tvNetworkLatitude.setText(":: " + Double.toString(lat ));
            tvNetworkLongitude.setText((":: " + Double.toString(lng)));
        }

        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        if (lastKnownLocation != null) {
            double lng = lastKnownLocation.getLongitude();
            double lat = lastKnownLocation.getLatitude();
            Log.d(TAG, "longtitude=" + lng + ", latitude=" + lat);
            tvPassiveLatitude.setText(":: " + Double.toString(lat ));
            tvPassivekLongitude.setText((":: " + Double.toString(lng)));
        }

        listProviders = locationManager.getAllProviders();
        boolean [] isEnable = new boolean[3];
        for(int i=0; i<listProviders.size();i++) {
            if(listProviders.get(i).equals(LocationManager.GPS_PROVIDER)) {
                isEnable[0] = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                tvGpsEnable.setText(": " +  String.valueOf(isEnable[0]));

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            } else if(listProviders.get(i).equals(LocationManager.NETWORK_PROVIDER)) {
                isEnable[1] = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                tvNetworkEnable.setText(": " +  String.valueOf(isEnable[1]));

                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
            } else if(listProviders.get(i).equals(LocationManager.PASSIVE_PROVIDER)) {
                isEnable[2] = locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
                tvPassiveEnable.setText(": " +  String.valueOf(isEnable[2]));

                locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this);
            }

        }

        Log.d(TAG, listProviders.get(0) + '/' + String.valueOf(isEnable[0]));
        Log.d(TAG, listProviders.get(1) + '/' + String.valueOf(isEnable[1]));
        Log.d(TAG, listProviders.get(2) + '/' + String.valueOf(isEnable[2]));
    }

    @Override
    public void onProviderEnabled(String provider) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this);
    }


    @Override
    public void onLocationChanged(Location location) {

        double latitude = 0.0;
        double longitude = 0.0;

        if(location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            tvGpsLatitude.setText(": " + Double.toString(latitude ));
            tvGpsLongitude.setText((": " + Double.toString(longitude)));
            Log.d(TAG + " GPS : ", Double.toString(latitude )+ '/' + Double.toString(longitude));
        }

        if(location.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            tvNetworkLatitude.setText(": " + Double.toString(latitude ));
            tvNetworkLongitude.setText((": " + Double.toString(longitude)));
            Log.d(TAG + " NETWORK : ", Double.toString(latitude )+ '/' + Double.toString(longitude));
        }

        if(location.getProvider().equals(LocationManager.PASSIVE_PROVIDER)) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            tvPassiveLatitude.setText(": " + Double.toString(latitude ));
            tvPassivekLongitude.setText((": " + Double.toString(longitude)));
            Log.d(TAG + " PASSIVE : ", Double.toString(latitude )+ '/' + Double.toString(longitude));
        }

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //권한이 없을 경우 최초 권한 요청 또는 사용자에 의한 재요청 확인
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION) &&
                    ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
                // 권한 재요청
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
                return;
            } else {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
                return;
            }
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this);
    }
}

- copy coding -


1

+ Recent posts