1
我想使用BroadcastReceiver來接收來電。我想在通話結束時註冊通話。下面的代碼給出了每個狀態(空閒,振鈴和摘機)不止一次與相同的號碼(它不是過去的呼叫問題)。是否因爲phonestatelistner在服務中被調用?廣播接收器和phonestatelistener
public class IncomingCallReceiver extends BroadcastReceiver {
int stateString =0;
int prevStat = 0;
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(null == bundle)
return;
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
{
String phonenumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
String info = "Detect Calls sample application\nIncoming number: " + phonenumber;
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
}
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
//CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
PhoneStateListener listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String p = incomingNumber;
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
prevStat = stateString;
stateString = 1;
Log.i("ON CALL STATE CHANGED","IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i("ON CALL STATE CHANGED","OFFFHOOK");
prevStat = stateString;
stateString = 2;
break;
case TelephonyManager.CALL_STATE_RINGING:
prevStat = stateString;
stateString = 3;
Log.i("ON CALL STATE CHANGED","RINGING");
break;
}
if(prevStat == 2 && stateString == 1)
{
Log.i("REGISTER A CALLL","==" +p);
}
}
};
telephony.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
我也試圖與phonestatelistener同樣的事情在一個單獨的類,但它不會被調用,即我的代碼沒有達到那裏。在我的清單文件中,我已經註冊了接收者,但是沒有phonestatelistener的聲明。那是要註冊嗎?
如果解決方案非常明顯,但對於Android的新東西,我很抱歉。 任何幫助表示讚賞:)
檢查這個答案:http://stackoverflow.com/a/5949116/438466 – Rabi
確保你打開你的應用程序在您安裝它之後。在用戶明確打開應用程序之前,應用程序處於停止狀態。 請參閱:http://stackoverflow.com/a/9955247/786462 這可以使它看起來像你的BroadcastReceiver沒有被調用。 – DataDino