2012-12-28 67 views
0

我一直在嘗試使用LocalBroadcastManager,但它似乎不工作。基本上我希望我的intentService在運行時廣播一個intent。 然後,我希望我的活動在用戶正在使用該活動時接收廣播。intentService使用LocalBroadcastManager的活動

我試圖在這裏按照指示: how to use LocalBroadcastManager?

,但它並不適用於某些原因。我沒有得到任何接收者的日誌條目。

這裏是我的代碼的相關部分:

public class MainActivity extends Activity { 
    // Debug log tag 
    private static final String tag = "PhoneControlMainActivity"; 

    // Broadcast receiver 
    PhoneControlBroadcastReceiver receiver; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    // Register the receiver with the local broadcast manager 
    receiver = new PhoneControlBroadcastReceiver(); 
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(PhoneControlBroadcastReceiver.SERVICE_OUTPUT)); 

    // Start IntentService 
    try { 
     serviceName = startService(new Intent(this, PhoneControlIntentService.class)); 
    } 
    catch(SecurityException e) 
    { 
     Log.d(tag,"SecurityException occured when starting IntentService: "+ e.getMessage()); 
     return; 
    } 

    if(serviceName != null) { 
     Log.d(tag,"serviceName NOT NULL"); 
    } 
    else { 
     Log.d(tag,"serviceName NULL"); 
    } 
    } 
} 

public class PhoneControlIntentService extends IntentService { 
    public PhoneControlIntentService() { 
    super("PhoneControlIntentService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) {  
    Intent msgIntent = new Intent(PhoneControlBroadcastReceiver.SERVICE_OUTPUT); 
    msgIntent.putExtra("message", "This is my message!"); 
    LocalBroadcastManager.getInstance(this).sendBroadcast(msgIntent); 
    } 
} 

public class PhoneControlBroadcastReceiver extends BroadcastReceiver{ 
    // Action 
    public static final String SERVICE_OUTPUT = "com.axr0284.phonecontrol.SERVICE_OUTPUT"; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
    Log.d(tag,"onReceive called");  
    } 
} 

任何幫助將高度讚賞? 感謝 阿米什

回答

0

這裏是我做錯了什麼,我service declaraion在AndroidManifest.xml有這條線

android:process=":PhoneControlIntentService_process"

<service 
    android:name=".PhoneControlIntentService" 
    android:label="@string/IntentService_name" 
    android:process=":PhoneControlIntentService_process"** 
    android:exported="false"/> 

這應該啓動service作爲一個單獨的進程。我想不知怎麼它阻止了localBroadcastManager正確發送。我不太明白,但是當我刪除那條線時,它開始工作。

3

LocalBroadcastManager無法在自己的進程外進行廣播。

相關問題