手机中一般有设置黑名单的功能。此例通过设置电话黑名单,当黑名单中的电话打来时,手机铃声为变成静音。
程序如下:
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class A11Activity extends Activity {
private EditText et;//添加输入框,输入并设置黑名单
private TextView tv01,tv02; //tv01用来显示EditText中输入的黑名单;tv02用来显示当前手机电话所处的状态
/** Called when the activity is first created. */
@SuppressWarnings("static-access")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv01=(TextView)findViewById(R.id.tv01);
tv02=(TextView)findViewById(R.id.tv02);
et=(EditText)findViewById(R.id.et);
/**创建PhoneCallListener的对象;其中PhoneCallListener是
* 扩展了PhoneStateListener的类*/
PhoneCallListener pcl=new PhoneCallListener();
TelephonyManager tm=(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
//设置监听电话的功能
tm.listen(pcl, pcl.LISTEN_CALL_STATE);
}
public class PhoneCallListener extends PhoneStateListener{
public void onCallStateChanged(int state,String incomingNumber){
switch(state){
//手机状态为待机时,手机铃声为正常模式
case TelephonyManager.CALL_STATE_IDLE:
tv02.setText("CALL_STATE_IDLE");
AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL);
am.getStreamVolume(AudioManager.STREAM_RING);
break;
//手机状态为通话中
case TelephonyManager.CALL_STATE_OFFHOOK:
tv02.setText("CALL_STATE_OFFHOOK");
break;
//手机模式为响铃时
case TelephonyManager.CALL_STATE_RINGING:
tv02.setText("CALL_STATE_RINGING");
//当来电号码与黑名单中的电话号码相同时,设置电话铃声为静音
if(incomingNumber.equals(tv01.getText().toString())){
AudioManager am01=(AudioManager)getSystemService(AUDIO_SERVICE);
am01.setRingerMode(AudioManager.RINGER_MODE_SILENT);
am01.getStreamVolume(AudioManager.STREAM_RING);
Toast.makeText(A11Activity.this, "黑名单中的电话静音!!", Toast.LENGTH_LONG).show();
}
}
super.onCallStateChanged(state, incomingNumber);
et.setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
tv01.setText(et.getText());
et.setText("");
return true;
}
});
}
}
}