我在将一个Intent从服务发送到Activity时遇到了一些麻烦。这是代码:
Intent intent = new Intent(context,
MessagingActivity.NewMessageReceiver.class);
intent.setAction(XMPPService.NEW_MESSAGE);
intent.putExtra("MESSAGE", body);
intent.putExtra("FROM", from);
context.sendBroadcast(intent);
context是一个服务 接收者代码(它是活动中的内部类):
public class NewMessageReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(XMPPService.NEW_MESSAGE))
{
String message = intent.getStringExtra("MESSAGE");
String from = intent.getStringExtra("FROM");
// TODO: add screen switch
addMessage(true, from, message);
}
}
}
Android清单条目:
<receiver
android:name=".MessagingActivity.NewMessageReceiver">
<intent-filter>
<action android:name="com.someapp.XMPPService.NEW_MESSAGE"/>
</intent-filter>
</receiver>
问题是虽然发送了Intent,但是没有调用onReceive()方法。
谢谢,伊万。
答案 0 :(得分:0)
试试这个
Intent intent = new Intent(XMPPService.NEW_MESSAGE);
intent.putExtra("MESSAGE", body);
intent.putExtra("FROM", from);
sendBroadcast(intent);
在活动中
IntentFilter filter = new IntentFilter(XMPPService.NEW_MESSAGE);
BroadcastReceiver mReceiver = new MessageReceiver(getApplicationContext());
registerReceiver(mReceiver, filter);