Android學習記錄(二十一)

TelephonyManager(電話管理器)

獲得其他app的Context,而這個Context代表訪問該app的全局信息的接口,而決定應用的唯一標識 是應用的包名,所以我們可以通過應用包名獲得對應app的Context 另外有一點要注意的是:其他應用的SP文件是否能被讀寫的前提就是SP文件是否指定了可讀或者 可寫的權限,我們上面創建的是MODE_PRIVATE的就不可以了

1.如何獲得TelephonyManager的服務對象

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

2.案例演示

2.1 調用撥號器撥打電話號碼

Uri uri=Uri.parse("tel:"+電話號碼);    
Intent intent=new Intent(Intent.ACTION_DIAL,uri);    
startActivity(intent);  

2.2 獲取Sim卡信息與網絡信息

(1)新建項目

在這裏插入圖片描述
在這裏插入圖片描述

(2)activity_main.xml

在這裏插入圖片描述

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_phone1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_phone9"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

</LinearLayout>

(3)MainActivity.java

在這裏插入圖片描述

public class MainActivity extends AppCompatActivity {
   
   

    private TextView tv_phone1;
    private TextView tv_phone2;
    private TextView tv_phone3;
    private TextView tv_phone4;
    private TextView tv_phone5;
    private TextView tv_phone6;
    private TextView tv_phone7;
    private TextView tv_phone8;
    private TextView tv_phone9;
    private TelephonyManager tManager;
    private String[] phoneType = {
   
   "未知","2G","3G","4G"};
    private String[] simState = {
   
   "狀態未知","無SIM卡","被PIN加鎖","被PUK加鎖",
            "被NetWork PIN加鎖","已準備好"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //①獲得系統提供的TelphonyManager對象的實例
        tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        bindViews();
    }

    private void bindViews() {
   
   
        tv_phone1 = (TextView) findViewById(R.id.tv_phone1);
        tv_phone2 = (TextView) findViewById(R.id.tv_phone2);
        tv_phone3 = (TextView) findViewById(R.id.tv_phone3);
        tv_phone4 = (TextView) findViewById(R.id.tv_phone4);
        tv_phone5 = (TextView) findViewById(R.id.tv_phone5);
        tv_phone6 = (TextView) findViewById(R.id.tv_phone6);
        tv_phone7 = (TextView) findViewById(R.id.tv_phone7);
        tv_phone8 = (TextView) findViewById(R.id.tv_phone8);
        tv_phone9 = (TextView) findViewById(R.id.tv_phone9);

        tv_phone1.setText("設備編號:" + tManager.getDeviceId());
        tv_phone2.setText("軟件版本:" + (tManager.getDeviceSoftwareVersion()!= null?
                tManager.getDeviceSoftwareVersion():"未知"));
        tv_phone3.setText("運營商代號:" + tManager.getNetworkOperator());
        tv_phone4.setText("運營商名稱:" + tManager.getNetworkOperatorName());
        tv_phone5.setText("網絡類型:" + phoneType[tManager.getPhoneType()]);
        tv_phone6.setText("設備當前位置:" + (tManager.getCellLocation() != null ? tManager
                .getCellLocation().toString() : "未知位置"));
        tv_phone7.setText("SIM卡的國別:" + tManager.getSimCountryIso());
        tv_phone8.setText("SIM卡序列號:" + tManager.getSimSerialNumber());
        tv_phone9.setText("SIM卡狀態:" + simState[tManager.getSimState()]);
    }
}

(4)AndroidManifest.xml

<!-- 添加訪問手機位置的權限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- 添加訪問手機狀態的權限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

2.3 獲取手機信號強度

網絡信號強度的單位是dBm(毫瓦分貝),一般用負數表示,正常手機信號變化範圍是從-110dBm (差)到-50dBm(好)之間。
手機獲取信號強度代碼示例:

dBm =-113+2*asu這是一個固定公式,asu(獨立信號單元)

主要代碼

MainActivity.java

public class MainActivity extends AppCompatActivity {
   
   

    private TextView tv_rssi;
    private MyPhoneStateListener mpsListener;
    private TelephonyManager tManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tManager = ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE));
        tv_rssi = (TextView) findViewById(R.id.tv_rssi);
        mpsListener  = new MyPhoneStateListener();
        tManager.listen(mpsListener,290);
    }

    private class MyPhoneStateListener extends PhoneStateListener {
   
   
        private int asu = 0,lastSignal = 0;
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
   
   
            asu = signalStrength.getGsmSignalStrength();
            lastSignal = -113 + 2 * asu;
            tv_rssi.setText("當前手機的信號強度:" + lastSignal + " dBm" );
            super.onSignalStrengthsChanged(signalStrength);
        }
    }
}

AndroidManifest.xml

<!-- 添加訪問手機狀態的權限 -->
 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

2.4 監聽手機的所有來電

思路:

重寫TelephonyManager的一個通話狀態監聽器PhoneStateListener 然後調用TelephonyManager.listen()的方法進行監聽,當來電的時候, 程序就會將來電號碼記錄到文件中!

實現代碼:
MainActivity.java:

public class MainActivity extends Activity  
{
   
     
    TelephonyManager tManager;  
  
    @Override  
    public void onCreate(Bundle savedInstanceState)  
    {
   
     
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        // 取得TelephonyManager對象  
        tManager = (TelephonyManager)   
            getSystemService(Context.TELEPHONY_SERVICE);  
        // 創建一個通話狀態監聽器  
        PhoneStateListener listener = new PhoneStateListener()  
        {
   
     
            @Override  
            public void onCallStateChanged(int state, String number)  
            {
   
     
                switch (state)  
                {
   
     
                // 無任何狀態  
                    case TelephonyManager.CALL_STATE_IDLE:  
                        break;  
                    case TelephonyManager.CALL_STATE_OFFHOOK:  
                        break;  
                    // 來電鈴響時  
                    case TelephonyManager.CALL_STATE_RINGING:  
                        OutputStream os = null;  
                        try  
                        {
   
     
                            os = openFileOutput("phoneList", MODE_APPEND);  
                        }  
                        catch (FileNotFoundException e)  
                        {
   
     
                            e.printStackTrace();  
                        }  
                        PrintStream ps = new PrintStream(os);  
                        // 將來電號碼記錄到文件中  
                        ps.println(new Date() + " 來電:" + number);  
                        ps.close();  
                        break;  
                    default:  
                        break;  
                }  
                super.onCallStateChanged(state, number);  
            }  
        };  
        // 監聽電話通話狀態的改變  
        tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);  
    }  
}  

AndroidManifest.xml

<!-- 授予該應用讀取通話狀態的權限 -->  
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

運行效果

注意!要讓這個程序位於前臺哦!用另一個電話撥打該電話,接着就可以在DDMS的file Explorer的應用 對應包名的files目錄下看到phoneList的文件了,我們可以將他導出到電腦中打開,文件的大概內容如下:

THR Oct 30 12:05:48 GMT 2014 來電: 137xxxxxxx

2.5 黑名單來電自動掛斷

下面只顯示一部分比較主要的代碼

MainActivity.java

public class MainActivity extends Activity {
   
     
  
    private TelephonyManager tManager;  
    private PhoneStateListener pListener;  
    private String number;  
    private EditText locknum;  
    private Button btnlock;  
      
    public class PhonecallListener extends PhoneStateListener  
    {
   
     
        @Override  
        public void onCallStateChanged(int state, String incomingNumber) {
   
     
            switch(state)  
            {
   
     
            case TelephonyManager.CALL_STATE_IDLE:break;  
            case TelephonyManager.CALL_STATE_OFFHOOK:break;  
            //當有電話撥入時  
            case TelephonyManager.CALL_STATE_RINGING:  
                if(isBlock(incomingNumber))  
                {
   
     
                    try  
                    {
   
     
                        Method method = Class.forName("android.os.ServiceManager")  
                                .getMethod("getService", String.class);  
                        // 獲取遠程TELEPHONY_SERVICE的IBinder對象的代理  
                        IBinder binder = (IBinder) method.invoke(null,  
                            new Object[] {
   
    TELEPHONY_SERVICE });  
                        // 將IBinder對象的代理轉換爲ITelephony對象  
                        ITelephony telephony = ITelephony.Stub.asInterface(binder);  
                        // 掛斷電話  
                        telephony.endCall();  
                    }catch(Exception e){
   
   e.printStackTrace();}  
                }  
                break;  
            }  
            super.onCallStateChanged(state, incomingNumber);  
        }  
    }  
      
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {
   
     
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        locknum = (EditText) findViewById(R.id.locknum);  
        btnlock = (Button) findViewById(R.id.btnlock);  
          
        //獲取系統的TelephonyManager管理器  
        tManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);  
        pListener = new PhoneStateListener();  
        tManager.listen(pListener, PhoneStateListener.LISTEN_CALL_STATE);  
          
        btnlock.setOnClickListener(new OnClickListener() {
   
     
              
            @Override  
            public void onClick(View v) {
   
     
                number = locknum.getText().toString();                
            }  
        });  
          
    }  
      
    public boolean isBlock(String phone)  
    {
   
     
        if(phone.equals(number))return true;  
        return false;  
    }  
}

AndroidManifest.xml

<!-- 授予該應用控制通話的權限 -->  
<uses-permission android:name="android.permission.CALL_PHONE" />    
<!-- 授予該應用讀取通話狀態的權限 -->  
<uses-permission android:name="android.permission.READ_PHONE_STATE" />  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章