本文实例讲述了Android基于AudioManager、PhoneStateListener实现设置黑名单功能。分享给大家供大家参考,具体如下:
手机中一般有设置黑名单的功能。此例通过设置电话黑名单,当黑名单中的电话打来时,手机铃声为变成静音。
程序代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
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 ;
}
});
}
}
}
|
希望本文所述对大家Android程序设计有所帮助。