这是我的BroadcastReceiver
public class PlayAudio extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(new CustomPhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);
}
}
这是我的Custom PhoneStateListener Class
public class CustomPhoneStateListener extends PhoneStateListener {
Context context;
public CustomPhoneStateListener(Context context) {
super();
this.context = context;
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("PHONEA", "IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("PHONEA", "OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d("PHONEA", "RINGING");
Intent intent = new Intent(this.context, AudioService.class);
context.startService(intent);
break;
default:
break;
}
}
}
这是我的服务
public class AudioService extends Service{
private static final String TAG = "PHONEA";
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate -> TODO");
}
}
我的问题是每次我在广播接收器中接收数据时,我都会创建一个TelephonyManager的新实例。所以当我第一次看到logcat时,我得到“RINGING”,第二次“RINGING”“RINGING”等等。我应该创建我的telephonylistener,以便只有一个实例?
此致 尼科斯
答案 0 :(得分:2)
每次手机状态发生变化时,您都会接听电话(假设您正在收听PhoneState)。
您应该在接收器中进行一些检查,并且仅在第一次启动TelephonyManager
。