반응형

Explains how to take a photo and get the thumbnail of it in an easy way.

기기의 카메라 앱을 실행 시키고 사진을 찍어 썸네일을 가져 온다.


<AndroidManifest.xml>

1
    <uses-feature android:name="android.hardware.camera" android:required="true"/>



<MainActivity.java>

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
public class MainActivity extends AppCompatActivity {
 
    static final int REQUEST_IMAGE_CAPTURE = 1001;
 
    ImageView imageView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        imageView = findViewById(R.id.imageView);
        Button button = findViewById(R.id.button);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                }
            }
        });
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap bitmap = (Bitmap)extras.get("data");
            imageView.setImageBitmap(bitmap);
        }
    }
}




Run the app and click CAMERA button.


Take a picture.


Get the thumbnail.


반응형
Posted by J-sean
:
반응형

You can retrieve the contact data.

연락처 정보를 모두 받아 올 수 있다.


<AndroidManifest.xml>

1
2
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>


<MainActivity.java>

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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
public class MainActivity extends AppCompatActivity {
 
    private final int MY_PERMISSION_REQUEST_CONTACTS = 1001;
    private final int MY_ACTIVITY_REQUEST_CODE = 2001;
 
    TextView textView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        String[] permissionRequests = {
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS
        };
 
        checkPermissions(permissionRequests);
 
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseContacts();
            }
        });
    }
 
    public void checkPermissions(String[] permissionRequests) {
        final ArrayList<String> permissionRequestList = new ArrayList<String>();
 
        for (final String request : permissionRequests) {
            if (ContextCompat.checkSelfPermission(this, request) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, request)) {   // Redundant in this case
                    permissionRequestList.add(request);
                } else {
                    permissionRequestList.add(request);
                }
            }
        }
 
        if (!permissionRequestList.isEmpty()) {
            final String[] results = new String[permissionRequestList.size()];
            permissionRequestList.toArray(results);
 
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("info");
 
            String msg = "This app won't work properly unless you grant below permissions.";
            for (String str : results)
                msg += ("\n- "+ str);
 
            builder.setMessage(msg);
            builder.setIcon(android.R.drawable.ic_dialog_info);
 
            builder.setNeutralButton("OK"new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(MainActivity.this, results, MY_PERMISSION_REQUEST_CONTACTS);
                }
            });
 
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSION_REQUEST_CONTACTS: {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(this, permissions[i] + " permission granted.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, permissions[i] + " permission denied.", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
 
    public void chooseContacts() {
        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(contactPickerIntent, MY_ACTIVITY_REQUEST_CODE);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == MY_ACTIVITY_REQUEST_CODE) {
                try {
                    Uri contactsUri = data.getData();
                    String id = contactsUri.getLastPathSegment();
 
                    getContacts(id);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public void getContacts(String id) {
        Cursor cursor;
        String name;
        String phone;
 
        try {
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                    new String[] {id},
                    null);
 
            if (cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                textView.setText("Name: " + name + '\n' + "Phone: " + phone + '\n');
 
                String columns[] = cursor.getColumnNames();
                for (String column : columns) {
                    int index = cursor.getColumnIndex(column);
                    String columnOutput = ("#" + index + " -> [" + column + "] = " + cursor.getString(index));
                    textView.append('\n' + columnOutput);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}




Run the app.


Choose contact.


Display contact data.


반응형
Posted by J-sean
:
반응형

You can retrieve multiple sensor data at the same time. Say you need ACCELEROMETER and AMBIENT_TEMPERATURE data.

동시에 여러가지 센서 데이터를 받아 올 수 있다. 예를 들어 ACCELEROMETER 와 AMBIENT_TEMPERATURE 센서의 데이터를 받아 오자.


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
public class MainActivity extends AppCompatActivity {
 
    TextView textView;
    TextView textView2;
 
    SensorManager manager;
    List<Sensor> sensors;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager = (SensorManager)getSystemService(SENSOR_SERVICE);
                sensors = manager.getSensorList(Sensor.TYPE_ALL);
 
                int index = 0;
                for (Sensor sensor : sensors) {
                    textView.append("#" + index++ + ": " + sensor.getName() + '\n');
                }
            }
        });
 
        final SensorEventListener sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                    String str = "Sensor Timestamp: " + event.timestamp + "\n\n";
                    str = str + "Sensor Accuracy: " + event.accuracy + '\n';
 
                    for (int index = 0; index < event.values.length; index++) {
                        str += ("Sensor Value #" + index + ": " + event.values[index] + '\n');
                    }
 
                    textView.setText(str);
                }
 
                if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
                    String str = "Sensor Timestamp: " + event.timestamp + "\n\n";
                    str = str + "Sensor Accuracy: " + event.accuracy + '\n';
 
                    for (int index = 0; index < event.values.length; index++) {
                        str += ("Sensor Value #" + index + ": " + event.values[index] + '\n');
                    }
 
                    textView2.setText(str);
                }
            }
 
            /*
            SENSOR_STATUS_ACCURACY_HIGH
            This sensor is reporting data with maximum accuracy
            Constant Value: 3 (0x00000003)
            SENSOR_STATUS_ACCURACY_LOW
            This sensor is reporting data with low accuracy, calibration with the environment is needed
            Constant Value: 1 (0x00000001)
            SENSOR_STATUS_ACCURACY_MEDIUM
            This sensor is reporting data with an average level of accuracy, calibration with the environment may improve the readings
            Constant Value: 2 (0x00000002)
            SENSOR_STATUS_NO_CONTACT
            The values returned by this sensor cannot be trusted because the sensor had no contact with what it was measuring
            (for example, the heart rate monitor is not in contact with the user).
            Constant Value: -1 (0xffffffff)
            SENSOR_STATUS_UNRELIABLE
            The values returned by this sensor cannot be trusted, calibration is needed or the environment doesn't allow readings
            Constant Value: 0 (0x00000000)
            */
 
            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
            }
        };
 
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manager.registerListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
                // If sensors.get(0) == manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)...
                //manager.registerListener(sensorEventListener, sensors.get(0), SensorManager.SENSOR_DELAY_UI);
                manager.registerListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE), SensorManager.SENSOR_DELAY_UI);
            }
        });
 
        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manager.unregisterListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
                // If sensors.get(0) == manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)...
                //manager.unregisterListener(sensorEventListener, sensors.get(0));
                manager.unregisterListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE));
            }
        });
    }
}



Sensor List


Sensor data


반응형
Posted by J-sean
:
반응형

서버에서 데이터를 받아 오는 경우 모든 문자가 알파벳이나 숫자라면 상관 없지만 한글이 섞여 있다면 글자가 깨지는 문제가 발생하고 어떤 인코딩이 사용되었는지 확인하기 어려운 경우가 있다. 아래와 같이 단순한 방법으로 간단히 확인 할 수 있다.


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
try {
    Log.d("Encoding Check""utf-8 -> euc-kr: " + new String(str.getBytes("utf-8"), "euc-kr"));
    Log.d("Encoding Check""utf-8 -> ksc5601: " + new String(str.getBytes("utf-8"), "ksc5601"));
    Log.d("Encoding Check""utf-8 -> x-windows-949: " + new String(str.getBytes("utf-8"), "x-windows-949"));
    Log.d("Encoding Check""utf-8 -> iso-8859-1: " + new String(str.getBytes("utf-8"), "iso-8859-1"));
 
    Log.d("Encoding Check""iso-8859-1 -> euc-kr: " + new String(str.getBytes("iso-8859-1"), "euc-kr"));
    Log.d("Encoding Check""iso-8859-1 -> ksc5601: " + new String(str.getBytes("iso-8859-1"), "ksc5601"));
    Log.d("Encoding Check""iso-8859-1 -> x-windows-949: " + new String(str.getBytes("iso-8859-1"), "x-windows-949"));
    Log.d("Encoding Check""iso-8859-1 -> utf-8: " + new String(str.getBytes("iso-8859-1"), "utf-8"));
 
    Log.d("Encoding Check""euc-kr -> utf-8: " + new String(str.getBytes("euc-kr"), "utf-8"));
    Log.d("Encoding Check""euc-kr -> ksc5601: " + new String(str.getBytes("euc-kr"), "ksc5601"));
    Log.d("Encoding Check""euc-kr -> x-windows-949: " + new String(str.getBytes("euc-kr"), "x-windows-949"));
    Log.d("Encoding Check""euc-kr -> iso-8859-1: " + new String(str.getBytes("euc-kr"), "iso-8859-1"));
 
    Log.d("Encoding Check""ksc5601 -> euc-kr: " + new String(str.getBytes("ksc5601"), "euc-kr"));
    Log.d("Encoding Check""ksc5601 -> utf-8: " + new String(str.getBytes("ksc5601"), "utf-8"));
    Log.d("Encoding Check""ksc5601 -> x-windows-949: " + new String(str.getBytes("ksc5601"), "x-windows-949"));
    Log.d("Encoding Check""ksc5601 -> iso-8859-1: " + new String(str.getBytes("ksc5601"), "iso-8859-1"));
 
    Log.d("Encoding Check""x-windows-949 -> euc-kr: " + new String(str.getBytes("x-windows-949"), "euc-kr"));
    Log.d("Encoding Check""x-windows-949 -> utf-8: " + new String(str.getBytes("x-windows-949"), "utf-8"));
    Log.d("Encoding Check""x-windows-949 -> ksc5601: " + new String(str.getBytes("x-windows-949"), "ksc5601"));
    Log.d("Encoding Check""x-windows-949 -> iso-8859-1: " + new String(str.getBytes("x-windows-949"), "iso-8859-1"));
catch(Exception e) {
    e.printStackTrace();
}



Logcat을 확인해 보면 'iso-8859-1 -> utf-8'이 정상적으로 한글을 표시했다.


그런데 위 코드 중 'utf-8 -> iso-8859-1'은 Logcat에 출력 되지 않는다. System.out.println()으로 해도 출력되지 않지만, 이 문자열을 기기에서 출력해 보면 깨진 한글로 표시는 된다. 이유는 알 수 없다.

1
    Log.d("Encoding Check""utf-8 -> iso-8859-1: " + new String(str.getBytes("utf-8"), "iso-8859-1"));



반응형
Posted by J-sean
:
반응형

웹서버에 데이터를 요청하고 app에서 응답 받아 처리할 수 있다.


서버에서 전달 되는 데이터 형식(Json)

1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "LastUpdate":"2019.10.12",
    "SalesRecord":
    [
        {"date":"2016.03.08","item":"apple","price":2400,"quantity":84,"total":201600},
        {"date":"2016.07.29","item":"grape","price":3100,"quantity":37,"total":114700},
        {"date":"2017.10.25","item":"peach","price":4600,"quantity":55,"total":253000},
        {"date":"2018.12.08","item":"banana","price":1500,"quantity":83,"total":124500},
        {"date":"2019.05.09","item":"melon","price":7200,"quantity":75,"total":540000},
        {"date":"2019.10.17","item":"coconut","price":6800,"quantity":59,"total":401200},
        {"date":"2019.11.07","item":"strawberry","price":4900,"quantity":30,"total":147000}
    ]
}



<AndroidManifest.xml>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:usesCleartextTraffic="true">
        <!--
        android:usesCleartextTraffic
        Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP.
        The default value for apps that target API level 27 or lower is "true". Apps that target
        API level 28 or higher default to "false". When the attribute is set to "false", platform
        components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse
        the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged
        to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of
        confidentiality, authenticity, and protections against tampering; a network attacker can
        eavesdrop on transmitted data and also modify it without being detected.
        -->



<MainActivity.java>

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
public class MainActivity extends AppCompatActivity {
 
    EditText editText;
    TextView textView;
 
    static RequestQueue requestQueue;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                makeRequest();
            }
        });
 
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }
 
    public void makeRequest() {
        String url = editText.getText().toString();
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //Server(Ubuntu) data encoding
                            response = new String(response.getBytes("iso-8859-1"), "utf-8");
                            //textView.append("Raw data: " + response);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
 
                        Gson gson = new Gson();
                        RequestResult requestResult = gson.fromJson(response, RequestResult.class);
                        textView.setText("Items count: " + requestResult.SalesRecord.size() + '\n');
                        textView.append("Last Update: " + requestResult.LastUpdate + '\n');
                        ArrayList<Data> items = requestResult.SalesRecord;
                        for (int i = 0; i < items.size(); i++) {
                            textView.append(String.format("■ Date: %s, Item: %s, Price: %s, Quantity: %s, Total: %s\n",
                                    items.get(i).date, items.get(i).item, items.get(i).price, items.get(i).quantity, items.get(i).total));
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        textView.append("Error: " + error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<StringString> getParams() throws AuthFailureError {
                Map<StringString> params = new HashMap<StringString>();
 
                return params;
            }
        };
 
        request.setShouldCache(false);
        requestQueue.add(request);
        textView.setText("Request sent.");
    }
}




<RequestResult.java>

1
2
3
4
public class RequestResult {
    String LastUpdate;
    ArrayList<Data> SalesRecord = new ArrayList<Data>();
}


서버 데이터의 key와 같은 이름의 변수를 만들어야 한다.


<Data.java>

1
2
3
4
5
6
7
public class Data {
    String date;
    String item;
    String price;
    String quantity;
    String total;
}


서버 데이터의 key와 같은 이름의 변수를 만들어야 한다


실행 화면. 서버 주소를 입력하고 DATA REQUEST 버튼을 클릭한다.


서버부터 전달된 데이터가 지정한 대로 표시된다.


반응형
Posted by J-sean
:
반응형

Timer와 TimerTask를 이용해 정해진 시간에 반복적인 작업을 할 수 있다.


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
public class MainActivity extends AppCompatActivity {
 
    TextView textView;
    Timer timer;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = findViewById(R.id.textView);
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd EEE HH:mm:ss");
 
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // Only the original thread that created a view hierarchy can touch its views.
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String currentTime = simpleDateFormat.format(new Date());
                        textView.setText(currentTime);
                    }
                });
            }
        };
 
        timer = new Timer();
        timer.schedule(timerTask, 01000);
    }
 
    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }
}




반응형
Posted by J-sean
:
반응형

Location과 Geocoder를 이용해 내 현재 위치와 다른 위치 사이의 거리를 구할 수 있다.

 

<AndroidManifest.xml>

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

 

<MainActivity.java>

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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
public class MainActivity extends AppCompatActivity {
 
    final int MY_PERMISSION_REQUEST_GPS = 1001;
 
    Button button;
    Button button2;
    Button button3;
 
    EditText editText;
 
    TextView textView;
    TextView textView2;
    TextView textView3;
 
    Location myLocation;
    Location tarLocation;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tarLocation = new Location("Target location");
        myLocation = new Location("My location");
 
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
 
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("info");
                builder.setMessage("This app won't work properly unless you grant GPS permission.");
                builder.setIcon(android.R.drawable.ic_dialog_info);
 
                builder.setNeutralButton("OK"new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(MainActivity.thisnew String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_GPS);
                    }
                });
 
                AlertDialog dialog = builder.create();
                dialog.show();
            } else {
                ActivityCompat.requestPermissions(thisnew String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_GPS);
            }
        }
 
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocationService();
            }
        });
 
        final Geocoder geocoder = new Geocoder(this);
        editText = findViewById(R.id.editText);
        textView2 = findViewById(R.id.textView2);
        button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String search = editText.getText().toString();
                List<Address> addressList;
                try {
                    addressList = geocoder.getFromLocationName(search, 10);
                    String[] split = addressList.get(0).toString().split(",");
                    String address = split[0].substring(split[0].indexOf("\""+ 1split[0].length() - 2);
                    String latitude = split[10].substring(split[10].indexOf("="+ 1);  // 위도(수평선)
                    String longitude = split[12].substring(split[12].indexOf("="+ 1); // 경도(수직선)
 
                    String data = "Address: " + address + "\n" + "Latitude: " + latitude + "\n" + "Longitude: " + longitude;
                    textView2.setText(data);
                    tarLocation.setLatitude(Double.parseDouble(latitude));
                    tarLocation.setLongitude(Double.parseDouble(longitude));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
 
        textView3 = findViewById(R.id.textView3);
        button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float[] distance = new float[1];
                Location.distanceBetween(myLocation.getLatitude(), myLocation.getLongitude(), tarLocation.getLatitude(), tarLocation.getLongitude(), distance);
                textView3.setText("Distance: " + distance[0/ 1000.0f + "km");
                //textView3.setText("Distance: " + String.valueOf(myLocation.distanceTo(tarLocation) / 1000.0f) + "km");
            }
        });
    }
 
    public void startLocationService() {
        LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        try {
            Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                
                myLocation.setLatitude(latitude);
                myLocation.setLongitude(longitude);
                
                String message = "My last location\nLatitude: " + latitude + "\nLongitude: " + longitude;
                Log.d("App""Last location request");
                textView.setText(message);
            } else
            {
                Toast.makeText(this"location is null", Toast.LENGTH_SHORT).show();
            }
 
            GPSListener gpsListener = new GPSListener();
            long minTime = 3000;
            float minDistance = 0;
 
            manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, gpsListener);
            Log.d("App""Current location request");
        }catch (SecurityException e) {
            e.printStackTrace();
        }
    }
 
    class GPSListener implements LocationListener {
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            String message = "My current location\nLatitude: " + latitude + "\nLongitude: " + longitude;
            textView.setText(message);
 
            myLocation.setLatitude(latitude);
            myLocation.setLongitude(longitude);
        }
 
        @Override
        public void onProviderEnabled(String provider) {
        }
 
        @Override
        public void onProviderDisabled(String provider) {
        }
 
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSION_REQUEST_GPS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0== PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this,"Permission granted.",Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this,"Permission denied.",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
 

 

 

FIND MY CURRENT LOCATION 버튼을 클릭 한다. (내 위치는 분당 서현역)

 

주소를 입력하고 FIND ADDRESS LOCATION 버튼을 클릭 한다.

 

CALCULATE DISTANCE 버튼을 클릭 한다.

 

현재 위치(서현역)와 동탄역 사이의 (직선)거리가 표시 된다.

 

 

Google Map에서 계산한 거리와 거의 같다.

 

 

반응형
Posted by J-sean
:
반응형

Geocoder를 사용하면 주소로 위경도를, 위경도로 주소를 확인 할 수 있다.


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
public class MainActivity extends AppCompatActivity {
 
    Geocoder geocoder;
 
    EditText editText;
    Button button;
    TextView textView;
 
    EditText editText2;
    EditText editText3;
    Button button2;
    TextView textView2;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        geocoder = new Geocoder(this);
 
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Address> addressList;
                String search = editText.getText().toString();
 
                try {
                    addressList = geocoder.getFromLocationName(search, 10);
                    String[] split = addressList.get(0).toString().split(",");
                    String address = split[0].substring(split[0].indexOf("\""+ 1split[0].length() - 2);
                    String latitude = split[10].substring(split[10].indexOf("="+ 1);  // 위도(수평선)
                    String longitude = split[12].substring(split[12].indexOf("="+ 1); // 경도(수직선)
 
                    String data = "Address: " + address + "\n" + "Latitude: " + latitude + "\n" + "Longitude: " + longitude;
                    textView.setText(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
 
        editText2 = findViewById(R.id.editText2);
        editText3 = findViewById(R.id.editText3);
        textView2 = findViewById(R.id.textView2);
        button2 = findViewById(R.id.button2);
 
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Address> addressList;
                double latitude = Double.parseDouble(editText2.getText().toString());
                double longitude = Double.parseDouble(editText3.getText().toString());
 
                try {
                    addressList = geocoder.getFromLocation(latitude, longitude, 10);
                    textView2.setText("Address: " + addressList.get(0).getAddressLine(0));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}




실행 화면


간단한 주소를 입력하고 SEARCH GEOGRAPHIC COORDINATE 버튼을 클릭 하면 정확한 주소와 위경도가 표시 된다.


위경도를 입력하고 SEARCH ADDRESS 버튼을 클릭 하면 주소가 표시된다.


주소로 서현역을 검색 하거나 서현역 위경도로 검색하면 addressList[0]에 입력되는 내용은 아래와 같다. (똑같은 양식으로 입력 된다)


Address[addressLines=[0:"대한민국 경기도 성남시 분당구 서현동 성남대로 지하 601 서현"],feature=서현,admin=경기도,sub-admin=null,locality=성남시,thoroughfare=null,postalCode=463-050,countryCode=KR,countryName=대한민국,hasLatitude=true,latitude=37.384938999999996,hasLongitude=true,longitude=127.12326300000001,phone=null,url=null,extras=null]


반응형
Posted by J-sean
: