TelephonyManager類主要提供了一系列用于通路與手機通訊相關的狀态和資訊的get方法。其中包括手機SIM的狀态和資訊、電信網絡的狀态及手機使用者的資訊。在應用程式中可以使用這些get方法擷取相關資料。
TelephonyManager類的對象可以通過Context.getSystemService(Context.TELEPHONY_SERVICE)方法來獲得,需要注意的是有些通訊資訊的擷取對應用程式的權限有一定的限制,在開發的時候需要為其添加相應的權限。
一、設計界面
1、布局檔案
打開res/layout/activity_main.xml檔案。
輸入以下代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/getphoneinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="獲得手機網絡資訊" />
</LinearLayout>
二、程式檔案
打開“src/com.genwoxue.contentprovider_b/MainActivity.java”檔案。
然後輸入以下代碼:
package com.genwoxue.telephony;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.telephony.TelephonyManager;
import android.content.Context;
public class MainActivity extends Activity {
private Button btnGet=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGet=(Button)super.findViewById(R.id.getphoneinfo);
btnGet.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
StringBuilder info=new StringBuilder();
//擷取TelephonyManager服務
TelephonyManager telphony=(TelephonyManager)MainActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
//擷取移動服務商名稱
info.append(telphony.getNetworkOperatorName()+"☆☆☆");
//擷取裝置号碼
info.append(telphony.getDeviceId()+"☆☆☆");
Toast.makeText(getApplicationContext(), info, Toast.LENGTH_LONG).show();
}
});
}
}
三、配置檔案
打開“AndroidManifest.xml”檔案。
然後輸入以下代碼:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.genwoxue.telephony"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.genwoxue.telephony.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
注意:需要在AndroidManifest.xml檔案中添權重限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
四、運作結果
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicGcq5CMzMWZ1MTNhdDMwUmNilTOjJWN0QGZxEzMlVDZ4UTOy0CMyADM4ATMx8CXyEzMxAjMvwVM1IDOxIzLcd2bsJ2Lc12bj5ycn9Gbi52YuAzcldWYtl2Lc9CX6MHc0RHaiojIsJye.jpg)