2014-07-02 89 views
0

我們有一個使用Android服務的應用程序。 使用LocalBroadcastManager從服務向活動發送意圖不起作用。然而,意圖是從來沒有收到的活動... (它的作品使用context.sendBroadcast()。)如何使用LocalBroadcastManager將服務意圖從服務發送到活動?

任何想法什麼是在這裏失蹤?

服務:

public int onStartCommand(final Intent intent, int flags, int startId) { 
     LocalBroadcastManager.getInstance(TestService.this).sendBroadcast(new Intent("bar")); 

     return START_STICKY; 
} 

活動:

public class MyActivity extends Activity 
{ 
private static final String TAG = MyActivity.class.getName(); 

private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d(TAG, "Recieved message by BroadcastReciever: " + intent.getAction()); 
    } 
}; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    registerReceiver(mReceiver, new IntentFilter("bar")); 

    Button loginButton = (Button) findViewById(R.id.button); 
    loginButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) {     
      Intent serviceIntent = new Intent("foo", null, this, TestService.class); 
      startService(serviceIntent); 
     } 
    }); 
} 

清單:

<service android:name=".TestService"></service> 

回答

2

您需要使用LocalBroadcastManager.getInstance(this).registerReceiver(...)以及LocalBroadcastManager.getInstance(this).unregisterReceiver(...)

正常registerReceiver(...)unregisterReceiver(...)是由Context#sendBroadcast()發送的廣播,不會接收LocalBroadcastManager#sendBroadcast()發送的廣播。

相關問題