Android的广播从服务到活动 [英] Android Broadcast from Service To Activity

查看:100
本文介绍了Android的广播从服务到活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个服务出来发送一个广播到活动中。我可以确认的广播从服务中发送,但活动不拿起任何东西。

I am trying to send a Broadcast from a service out to an Activity. I can verify the broadcast is sent from within the service, but the Activity doesn't pick up anything.

下面是相关服务code:

Here is the relevant service code:

   Intent i = new Intent(NEW_MESSAGE);  
   i.putExtra(FriendInfo.USERNAME, StringUtils.parseBareAddress(message.getFrom()));
   i.putExtra(FriendInfo.MESSAGE, message.getBody());
   i.putExtra("who", "1");
   sendBroadcast(i);

而在活动类接收端:

And the receiving end in the activity class:

public class newMessage extends BroadcastReceiver 
{
@Override
   public void onReceive(Context context, Intent intent) 
   {    
    String action = intent.getAction();
       if(action.equalsIgnoreCase(IMService.NEW_MESSAGE)){    
          Bundle extra = intent.getExtras();
          String username = extra.getString(FriendInfo.USERNAME);   
          String message = extra.getString(FriendInfo.MESSAGE);
          String who = extra.getString("who");
         }
   }
}

该BroadcastReceiver的是一个活动中定义的。我注册了接收器在活动的onCreate方法,而不是在清单文件。

The BroadcastReceiver is defined within an Activity. I am registering the receiver in the onCreate method of the Activity, not in the Manifest file.

我难倒,为什么它不会拍摄。任何事情。

I'm stumped as to why it won't rec. anything.

任何见解?

修改
注册方式如下:

EDIT
Registering takes place as follows:

 registerReceiver(messageReceiver, new IntentFilter(IMService.NEW_MESSAGE));

在哪里的messageReceiver被定义为

Where "messageReceiver" is defined as

private newMessage messageReceiver = new newMessage();

IMService.NEW_MESSAGE仅仅是一个字符串=NewMessage作为

IMService.NEW_MESSAGE is merely a string = "NewMessage"

推荐答案

我不知道这是否是特定的设置,或者如果它是在普通的修复,但移动寄存器/注销 onResume /的onPause _respectively _ ,而不是注册在的onCreate 解决了这个问题对我来说。

I'm not sure if it is specific to the set up, or if it is a fix in general, but moving the register/unregister to the onResume/onPause _respectively_ and not registering in the onCreate solved the problem for me.

这篇关于Android的广播从服务到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆