如果电话有效,我不想播放通知声音,如果当时正在播放通知声音并且通话响铃,则应停止通知声音。
我尝试了以下代码但我无法获得当前的手机状态。
TelephonyManager telephonyManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new CustomPhoneStateListener(context),
PhoneStateListener.LISTEN_CALL_STATE);
public class CustomPhoneStateListener extends PhoneStateListener {
//private static final String TAG = "PhoneStateChanged";
Context context; //Context to make Toast if required
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:
//when Idle i.e no call
Toast.makeText(context, "Phone state Idle", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//when Off hook i.e in call
//Make intent and start your service here
Toast.makeText(context, "Phone state Off hook", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
//when Ringing
Toast.makeText(context, "Phone state Ringing", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
答案 0 :(得分:1)
你可以像这样使用broadcastreceiver,并根据状态禁用通知:
public class PhonecallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
}
}
并在manifest.xml文件中:
<receiver android:name=".PhonecallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
答案 1 :(得分:0)
在通话期间,onCallStateChanged()
我们可以获得通话状态。停止通知声音试试这个:
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
ringtone .stop();
} catch (Exception e) {
e.printStackTrace();
}
快乐的编码!!