要识别Android设备的SIM1或SIM2接收到的电话,您可以使用TelephonyManager类和PhoneStateListener类来监听电话状态。以下是一个示例代码:
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private TelephonyManager telephonyManager;
private PhoneStateListener phoneStateListenerSim1;
private PhoneStateListener phoneStateListenerSim2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// 创建监听器1,用于监听SIM1的电话状态
phoneStateListenerSim1 = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
if (state == TelephonyManager.CALL_STATE_RINGING) {
Log.d("SIM1", "Incoming call from: " + incomingNumber);
}
}
};
// 创建监听器2,用于监听SIM2的电话状态
phoneStateListenerSim2 = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
if (state == TelephonyManager.CALL_STATE_RINGING) {
Log.d("SIM2", "Incoming call from: " + incomingNumber);
}
}
};
// 注册监听器1,监听SIM1的电话状态
telephonyManager.listen(phoneStateListenerSim1, PhoneStateListener.LISTEN_CALL_STATE);
// 注册监听器2,监听SIM2的电话状态
telephonyManager.listen(phoneStateListenerSim2, PhoneStateListener.LISTEN_CALL_STATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 取消注册监听器,避免内存泄漏
telephonyManager.listen(phoneStateListenerSim1, PhoneStateListener.LISTEN_NONE);
telephonyManager.listen(phoneStateListenerSim2, PhoneStateListener.LISTEN_NONE);
}
}
以上代码中,我们创建了两个PhoneStateListener对象,分别用于监听SIM1和SIM2的电话状态。在onCallStateChanged方法中,我们可以根据电话状态来进行相应的处理。在这个示例中,我们只是简单地打印来电号码。
请注意,在使用这段代码之前,您需要确保您的设备确实支持双卡,并且在AndroidManifest.xml文件中已经添加了所需的权限。