Android获取手机状态和监听手机来电状态

时间:2022-02-24 19:05:32

获取手机状态:

import android.content.Context;
import android.telephony.TelephonyManager;

//获得相应的系统服务
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
/**
* 返回电话状态
*
* CALL_STATE_IDLE 无任何状态时
* CALL_STATE_OFFHOOK 接起电话时
* CALL_STATE_RINGING 电话进来时
*/
tm.getCallState();
if(tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
Log.d("test", "call state idle...");
} else if(tm.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
Log.d("test", "call state offhook...");
} else if(tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
Log.d("test", "call state ringing...");
}


监听手机来电状态:

        //获得相应的系统服务

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

    //使用TelephonyManager对象的listen(PhoneStateListener listener, int events)


    //实现PhoneStateListener listener并实现相应的方法

    public class MyPhoneCallListener extends PhoneStateListener
    {

    @Override
    public void onCallStateChanged(int state, String incomingNumber)
    {

     switch (state) {
     case TelephonyManager.CALL_STATE_OFFHOOK: //电话通话的状态
     Toast.makeText(Main.this, "正在通话...", Toast.LENGTH_SHORT).show();
     break;

     case TelephonyManager.CALL_STATE_RINGING: //电话响铃的状态
     Toast.makeText(Main.this, incomingNumber, Toast.LENGTH_SHORT).show();
     break;
     }
     super.onCallStateChanged(state, incomingNumber);
    }


第一个参数需要实现PhoneStateListener listener并实现相应的方法,第二个参数是PhoneStateListener的静态常量,此处由于是监听电话状态,所以需要传入LISTEN_CALL_STATE,而同时也需要在AndroidManifest中注册相应的权限

<uses-permission android:name="android.permission.READ_PHONE_STATE" />