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

Androidで現在の国コードを変更する方法をサンプルコード付きで解説

はじめに

本記事では、Androidアプリで現在の国コード(Country Code)を取得し、変更して表示する方法をサンプルコードとともに解説します。位置情報と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.setCountryCode("KR");
                    textView.setText("" + address.getCountryCode());
                } 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.setCountryCode("KR");
            textView.setText("" + address.getCountryCode());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

このコードでは、まずLocationManagerを使ってネットワーク経由で取得した最後の既知の位置情報を取得し、Geocoderクラスで緯度経度から住所情報を取得しています。その後、setCountryCode()メソッドを呼び出して国コードを「KR」(韓国)に変更し、結果をTextViewに表示します。位置情報の利用にはユーザーの許可が必要なため、ACCESS_FINE_LOCATIONとACCESS_COARSE_LOCATIONの権限リクエスト処理もあわせて実装しています。

手順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)、電話状態の読み取り(READ_PHONE_STATE)の各権限を宣言しています。特にINTERNET権限はGeocoderが正しく動作するために必須なので、忘れずに設定しましょう。

アプリを実行してみよう

それでは、アプリケーションを実行してみましょう。ここでは、実際のAndroidスマートフォンをパソコンに接続していることを前提としています。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーにある実行(Run)アイコンをクリックします。表示された選択肢から自分のモバイルデバイスを選択すると、端末上に以下のようなデフォルト画面が表示されます。

Androidで現在の国コードを変更する方法をサンプルコード付きで解説

  1. Androidで現在のGPS位置情報をプログラムから取得する方法【サンプルコード付き】

    この記事では、Androidアプリでプログラムから現在のGPS位置情報を取得する方法を、サンプルコードとともにステップごとに解説します。 仕組みの概要 位置情報の取得には、Google Play Servicesが提供するFusedLocationProviderClientを使用します。このAPIはGPS・Wi-Fi・携帯基地局など複数の情報源を統合し、高精度かつバッテリー消費を抑えた位置情報を提供してくれます。 また、位置情報はユーザーのプライバシーに関わるデータであるため、ACCESS_FINE_LOCATIONパーミッションを実行時にリクエストする処理も必須となります。 ステップ1:新

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

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