複製代碼 代碼如下:
public class UniteqService {
public static final String LOG_TAG = "UniteqService";
public boolean DEBUG = true;
private boolean hasService = false;//是否有服務
private PhoneStateListener[] mPhoneStateListener;//監聽雙卡
private TelephonyManager mPhone;
//監聽類
private PhoneStateListener getPhoneStateListener(final int sub) {
PhoneStateListener sPhoneStateListener = new PhoneStateListener(sub) {
@Override
public void onServiceStateChanged(ServiceState serviceState) {
// TODO Auto-generated method stub
if (serviceState != null) {
if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) {
hasService = true;
} else {
hasService = false;
}
} else {
if (DEBUG) Log.d(TAG, "no service state...may be the balance is not enough" + sub);
}
super.onServiceStateChanged(serviceState);
}
};
return sPhoneStateListener;
}
//註冊監聽
private void registerPhoneListener() {
//擷取卡號數,MSimTelephonyManager 這個類API沒有開放,可以通過編譯源碼
//得到frameworks.jar包並匯入你的工程, 然後import android.telephony.MSimTelephonyManager;
mSub = MSimTelephonyManager.getDefault().getPhoneCount();
mPhoneStateListener = new PhoneStateListener[mSub];
for (int i = 0; i < mSub; i++) {
mPhoneStateListener[i] = getPhoneStateListener(i);
mPhone.listen(mPhoneStateListener[i], PhoneStateListener.LISTEN_SERVICE_STATE);
}
}
//取消監聽
private void unregisterPhoneListener() {
mSub = MSimTelephonyManager.getDefault().getPhoneCount();
for (int i = 0; i < mSub; i++) {
if(mPhoneStateListener[i] != null){
mPhone.listen(mPhoneStateListener[i], PhoneStateListener.LISTEN_NONE);
}
}
}
}