具有 phone 呼叫状态的通知

Notification with phone call state

如果phone有来电,我不想播放通知音,如果当时正在播放通知音并且来电正在响铃,则应停止通知音。

我尝试了以下代码,但无法获取当前的 phone 状态。

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;
        }
    }
}

您可以像这样使用 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>

在 phone 调用期间,onCallStateChanged() 我们可以获得 phone 调用的状态。对于停止通知声音试试这个:

try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
ringtone .stop();
} catch (Exception e) {
e.printStackTrace();
}

编码愉快!!