📅  最后修改于: 2020-10-10 01:38:43             🧑  作者: Mango
我们还可以使用TelephonyManager类获取呼叫状态信息。为此,我们需要通过传递PhonStateListener实例来调用TelephonyManager类的listen方法。
必须实现PhoneStateListener接口以获取呼叫状态。它提供了一种onCallStateChanged()方法。
让我们看一个示例,在该示例中,我们确定电话是在响铃还是在通话中,或者电话既不在响铃也不在通话中。
在此示例中,此文件中没有任何组件。
让我们编写代码以了解调用状态。
package com.javatpoint.callstates;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager telephonyManager =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber)
{
if(state==TelephonyManager.CALL_STATE_RINGING){
Toast.makeText(getApplicationContext(),"Phone Is Riging",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_OFFHOOK){
Toast.makeText(getApplicationContext(),"Phone is Currently in A call",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_IDLE){
Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call",
Toast.LENGTH_LONG).show();
}
}
};
telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
您需要在AndroidManifest.xml文件中提供READ_PHONE_STATE权限。