如何使用LocalBroadcastManager将Service从Service发送到Activity?

时间:2014-07-02 14:42:34

标签: android android-intent android-activity android-service

我们有一个使用Android服务的应用。 将服务中的意图发送到活动并不能使用LocalBroadcastManager。但是,活动从未收到过这样的意图...... (它使用context.sendBroadcast()。)

任何人都知道这里缺少什么?

服务:

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>

1 个答案:

答案 0 :(得分:3)

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

正常registerReceiver(...)unregisterReceiver(...)适用于Context#sendBroadcast()发送的广播,不会接收LocalBroadcastManager#sendBroadcast()发送的广播。