AndroidのService- TelephonyManager
TelephonyManagerは携帯の状態を管理するためのシステムサービスである。
大量のgetXXX()を提供してあるので、携帯関連の情報を色々取得できる。
詳細は http://developer.android.com/intl/ja/reference/android/telephony/TelephonyManager.html
オブジェクト取得
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
サンプルコード
① AndroidManifest.xmlに権限追加
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
② メインActitivyレイアウト実装(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/show" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
③ ListのItemレイアウト実装(line.xml)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="120dp" android:textSize="12dp" /> <TextView android:id="@+id/value" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="8dp" android:textSize="12dp" /> </LinearLayout>
④ メインActivity実装(MainActivity.java)
package com.example.liguofeng.mytelephonymanager; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.TelephonyManager; import android.widget.ListView; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private final String KEY = "name"; private final String VALUE = "value"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // TelephonyManager取得 final TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // List表示用map ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>() { { add(new HashMap<String, String>() { { put(KEY, "デバイスID"); put(VALUE, manager.getDeviceId()); } }); add(new HashMap<String, String>() { { put(KEY, "ネット運用者名"); put(VALUE, manager.getNetworkOperatorName()); } }); add(new HashMap<String, String>() { { put(KEY, "デバイス所在地"); put(VALUE, manager.getCellLocation() != null ? manager.getCellLocation().toString() : null); } }); add(new HashMap<String, String>() { { put(KEY, "SIMシリアル番号"); put(VALUE, manager.getSimSerialNumber()); } }); } }; // Adapter SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.line, new String[]{"name", "value"}, new int[]{R.id.name, R.id.value} ); ((ListView) findViewById(R.id.show)).setAdapter(adapter); } }