2014-03-12 61 views
0

如果我能夠註冊一個接收器,像這樣:爲什麼LocalBroadcastManager.getInstance(Context context)需要上下文作爲參數?

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("myStringFilter")); 

,併發送一個廣播,像這樣:

Intent intent = new Intent("myStringFilter"); 
LocalBroadcastManager.getInstance(new Activity()).sendBroadcast(intent); 

爲什麼還要要求文脈的getInstance?如果我只能說new Activity(),它仍然有效,那有什麼意義?

回答

3

現在,LocalBroadcastManager使用提供的Context就是撥打getApplicationContext()就可以了。雖然new Activity()目前可以在您測試它的任何地方工作,但我不會依賴於必須在Android的所有過去/現在/未來版本上工作的行爲。

LocalBroadcastManager需要Context爲了與HandlerLooper主應用程序線程工作,並且它使用Application爲(而不是其他Context),以防止內存泄漏。

歡迎您檢查the source code to LocalBroadcastManager以瞭解更多關於其內部工作原理的信息。

+0

鏈接到源代碼已損壞。 – barq

+0

@ barq:修正,謝謝! – CommonsWare

相關問題