Broadcastreceiver creating multiple instances of TelephonyManager
This is my 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);
}
}
This is my Custom PhoneStateListener Class
public class CustomPhoneSta开发者_如何学JAVAteListener 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;
}
}
}
and this is my service
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");
}
}
My question is that every time I receive data in Broadcast receiver I create a new instance of the TelephonyManager
. So when I view the logcat the first time I get "RINGING", the second time "RINGING" "RINGING" and so on. When should I create my telephonylistener
in order to have only one instance?
Regards, Nicos
You are getting call on your receiver(Asssuming you are listening for PhoneState) every time the phone state change.
You should put some check in your receiver and instatiate the TelephonyManager
for the first time only.
精彩评论