Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】Geocoderを使って現在の国名を取得・変更する方法

Androidで現在の国名を変更する方法

このチュートリアルでは、Androidアプリで位置情報をもとに現在の国名を取得し、setCountryName()メソッドを使って国名を変更して画面に表示する方法を解説します。位置情報の取得にはLocationManager、住所情報への変換にはGeocoderクラスを使用します。

ステップ1:新しいプロジェクトを作成する

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。

ステップ2:レイアウトファイル(activity_main.xml)にコードを追加する

次に、res/layout/activity_main.xmlに以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

上記のコードでは、国名の情報を表示するためのTextViewを配置しています。

ステップ3:MainActivity.javaにコードを追加する

続いて、src/MainActivity.javaに以下のコードを追加します。

package com.example.myapplication;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Location location;
    double describeContents;
    List<Address> addresses;
    Geocoder geocoder;

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
        }
        location = locationManager
        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        geocoder= new Geocoder(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 101:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    try {
                        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
                        Address address = addresses.get(0);
                        address.setCountryName("London");
                        textView.setText("" + address.getCountryName());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    //not granted
                }
                break;
                default:
                    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        try {
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
            Address address = addresses.get(0);
            address.setCountryName("London");
            textView.setText("" + address.getCountryName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

このコードのポイントは以下の通りです。

  • 権限チェック: 位置情報(ACCESS_FINE_LOCATION/ACCESS_COARSE_LOCATION)のパーミッションが許可されていない場合、リクエストコード101で権限を要求します。
  • 位置情報の取得: getLastKnownLocation()メソッドを使って、ネットワークプロバイダーから最後に把握した位置情報を取得します。
  • 逆ジオコーディング: Geocoder.getFromLocation()で緯度・経度から住所情報(Address)を取得します。
  • 国名の変更: 取得したAddressオブジェクトに対してsetCountryName("London")を呼び出すことで、国名を任意の値(ここでは"London")に変更し、TextViewに表示します。

ステップ4:AndroidManifest.xmlにパーミッションを追加する

最後に、AndroidManifest.xmlに以下のコードを追加して、必要な権限を宣言します。

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

   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.READ_PHONE_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>

アプリを実行してみよう

それでは、アプリケーションを実行してみましょう。実 Android端末がコンピュータに接続されているものとします。Android Studioからアプリを実行するには、プロジェクトのアクティビティファイルのいずれかを開き、ツールバーの「Run」アイコンをクリックします。オプションとして自分のモバイルデバイスを選択すると、デバイスに以下のようなデフォルト画面が表示されます。

【Android】Geocoderを使って現在の国名を取得・変更する方法

  1. 【Android】実行時にアプリのテーマを動的に変更する方法をわかりやすく解説

    Androidアプリ開発では、ユーザーの好みや設定に応じてアプリの見た目を変えたいケースがあります。本記事では、実行時(ランタイム)に現在のテーマを変更する方法を、実際のコード例とともにステップごとに解説します。 テーマを実行時に切り替えるには、setTheme()メソッドを使用します。最も重要なポイントは、このメソッドをsetContentView()より前に呼び出すことです。呼び出す順序が逆になると、テーマが正しく適用されませんので注意してください。 ステップ1:新規プロジェクトを作成する Android Studioを起動し、「File」→「New Project」を選択して新しいプロジ

  2. Androidスマホの端末名を変更する方法|Bluetooth・Playストアの名前も解説

    同じようなAndroidスマートフォンが数多く存在する中で、自分のデバイスを見分けやすくしたいと思ったことはありませんか?Androidでは端末の名前を自由に変更でき、好きな名前を付けることが可能です。 この設定には、システムのコア設定を書き換えたり、カスタムROMをインストールしたりする必要は一切ありません。名前を変更する機能は、最初から端末に組み込まれています。この記事では、スマートフォン本体の名前、Bluetooth名、さらにGoogle Playストア上のデバイス名を変更する方法を詳しくご紹介します。 Android端末の名前を変更する 名前の変更手順は機種によって多少異なりますが、ほ