【Android】ネットワークプロバイダーから現在の国名を取得する方法
概要
この記事では、Androidアプリでネットワークプロバイダー(NETWORK_PROVIDER)から取得した位置情報をもとに、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);
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);
textView.setText("" + address.getCountryName());
} catch (IOException e) {
e.printStackTrace();
}
}
}このコードの処理の流れは以下のとおりです。
- onCreate():LocationManager を取得し、位置情報のパーミッションが未許可の場合はリクエストを行います。その後、ネットワークプロバイダーから最後に取得した位置情報(getLastKnownLocation)を保持し、Geocoder のインスタンスを生成します。
- onRequestPermissionsResult():パーミッションが許可されたタイミングで、緯度・経度をもとに Geocoder で住所情報を取得し、その中から国名(getCountryName())を取り出して TextView に表示します。
- onResume():画面が再表示された際にも同様に国名の取得と表示を行います。
手順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>
ここで宣言している主な権限は以下のとおりです。
- ACCESS_COARSE_LOCATION:ネットワークプロバイダーによるおおよその位置情報の取得に必要な権限です。
- INTERNET:Geocoder がサーバーと通信して座標を住所に変換するために必要な権限です。
- READ_PHONE_STATE:端末の状態を読み取るための権限です。
補足:実装時の注意点
- getLastKnownLocation() は、端末がまだ一度も位置情報を取得していない場合に null を返すことがあります。実運用では null チェックや、requestLocationUpdates() による最新位置の取得を組み合わせるのが安全です。
- Geocoder はバックグラウンドでの通信を伴うため、実際のアプリではメインスレッド以外で呼び出すことが推奨されます。
アプリの実行と確認
それでは、アプリを実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続しているものとして説明します。Android Studio でプロジェクト内のアクティビティファイルを開き、ツールバーの実行アイコンをクリックしてください。接続したモバイル端末を選択してアプリを起動すると、端末の画面に以下のように現在の国名が表示されます。

-
【Android】現在のスレッド名を取得して表示する方法をわかりやすく解説
スレッドとは? まず、スレッドについて簡単におさらいしておきましょう。スレッドとは軽量なサブプロセスのことで、UI(ユーザーインターフェース)の動作を妨げることなくバックグラウンド処理を実行するために使われます。Androidアプリ開発では、時間のかかる処理を別スレッドに分離することで、画面のフリーズやANR(Application Not Responding)エラーを防ぐことができます。 本記事では、Androidアプリで現在実行中のスレッドの名前を取得して表示する方法を、サンプルコード付きで解説します。 手順1:新規プロジェクトを作成する Android Studioを起動し、メニューか
-
【Android開発】現在の日付と時刻を取得して画面に表示する方法を解説
このチュートリアルでは、Androidアプリで現在の日付と時刻を取得し、画面に表示する方法を段階的に解説します。ボタンをタップすると、フォーマットされた日時がTextViewに表示されるシンプルなサンプルアプリを作成します。手順1:新しいプロジェクトを作成するAndroid Studioを開き、メニューから「File」→「New Project」を選択して、必要な情報を入力し、新しいプロジェクトを作成します。テンプレートは「Empty Activity」を選んでおくとスムーズです。手順2:レイアウトファイル(activity_main.xml)を編集するres/layout/activity_