2013-02-03 174 views
0

我有一個MyService類實現自定義CallReceiver.Listener。問題是在MyService中調用的監聽器註冊不起作用。 mListenerCallReceiver始終爲空。它證明聽衆沒有註冊,但我不知道爲什麼。自定義聽衆沒有註冊

爲MyService類(摘錄):

public class MyService extends Service implements CallReceiver.Listener { 

CallReceiver mCallReceiver; 

    public int onStartCommand (Intent intent, int flags, int startId) { 

    serviceStart(); 
    return startId; 
    } 

    // starting service 
    public void serviceStart() { 

    mCallReceiver = new CallReceiver(); 

    // registering listener for CallReceiver 
    mCallReceiver.registerListener(this); 
    } 


    public void onPhoneStateChange(boolean state) { 
    if (state) { 
     Log.v("onPhoneStateChange", "service destroyed"); 
     serviceDestroy(); 
    } else { 
     // serviceStart(); 
    } 
    } 

} 

CallReceiver類:

public class CallReceiver extends BroadcastReceiver { 

private boolean isRinging = false; 
private Listener mListener = null; 

// interface declaration 
public interface Listener { 
     public void onPhoneStateChange(boolean state); 
    } 

// listener registration 
public void registerListener (Listener listener) { 
     mListener = listener; 
    } 


@Override 
public void onReceive(Context context, Intent intent) { 

     String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); 

     if(TelephonyManager.EXTRA_STATE_RINGING.equals(state)) { 
      // do something while ringing 
       Log.v("phone", "ringing"); 
       isRinging = true; 
     } 


     else if(TelephonyManager.EXTRA_STATE_IDLE.equals(state)) { 
      //do something when the call ends 
      Log.v("phone", "idle"); 
      isRinging = false; 
     } 


     if(mListener != null) { 
      // onPhoneStateChange is not called because mListener is null 
      mListener.onPhoneStateChange(isRinging); 
     } 

    } 

} 
+1

您從未註冊Receiver,這可能是一個問題。此外,如果此Receiver是Manifest的一部分,系統很可能會創建一個與您的服務無關的單獨實例,這會將'mListener'留空。 –

+0

CallReceiver現在在AndroidManifest.xml中靜態註冊。 – Kristopher

+0

我會說它不應該在清單中。相反,您的服務應該使IntentFilter動態註冊。我會很快發佈代碼示例。我不知道你的接收器需要什麼「Intent」動作。 –

回答

1

你應該動態地註冊您的接收器。

// registering listener for CallReceiver 
    mCallReceiver.registerListener(this); 
    IntentFilter filter = new IntentFilter("your.Intent"); 
    registerReceiver (mCallReceiver, filter); 

此外,在您的服務onDestroy(),不要忘記取消註冊它。

@Override 
public void onDestroy() 
{ 
    try { 
    unregisterReceiver (broadcastReceiver); 
    } 
    catch (IllegalArgumentException e){} 
    catch (NullPointerException ne){} 
    super.onDestroy(); 
} 
+0

我能說什麼......你說得對! :) – Kristopher