【问题标题】:Communicating between Service and Activity using Broadcasts/intents使用广播/意图在服务和活动之间进行通信
【发布时间】:2012-05-14 04:48:27
【问题描述】:

我正在尝试将 UI 从服务通信/更新到活动。我收到的广播不是我发送的。任何想法为什么?

服务代码:

@Override
    //binder returns NULL

    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Intent i = new Intent();
    i.putExtra("lol", "haha");
        i.setAction(MYACTION);
        sendBroadcast(i);

活动代码:

protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
         IntentFilter intentFilter = new IntentFilter(MYACTION);
             registerReceiver(recv, intentFilter);
    }

    BroadcastReceiver recv = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                Intent getintent = getIntent();
String action = getintent.getAction();
//ACTION RECEIVED IS DIFFERENT FROM MYACTION. IT IS ACTION.MAIN

// VALUE RECEIVED IS NULL
                String val = getintent.getStringExtra("lol");
                }

我没有在清单中注册接收器。有必要吗?

如 cmets 中所述:我在广播接收器中没有收到相同的操作,并且意图的值为 NULL。

我做错了什么?

感谢您的帮助。

【问题讨论】:

    标签: android service android-intent broadcastreceiver intentfilter


    【解决方案1】:

    你不需要使用getIntent,因为它转换为Activity的intent,而不是接收到broadcast的intent。因此,在您的情况下,您只需要使用 intent 即可,它指的是广播意图。并确保在从 bundle 中读取所需值之前进行检查,因为您可能首先收到另一个广播,其 bundle 中不包含 lol。

    所以在你的广播接收器中,这样做:

    ....
    String val = getintent.getStringExtra("lol");
    
    if(val.equals("your_action_string"){
        String val = intent.getStringExtra("lol");  //getIntent() replaced by intent
    }
    ....
    

    附:不,您不需要注册任何广播接收器,因为它是通过编程方式创建和使用的

    【讨论】:

      【解决方案2】:

      如果您正在发出网络请求或扩展任务,我会查看异步任务。它使更新 UI 变得更加容易。只需确保调用 onPreExecute() 和 onPostExecute() 即可。我不喜欢服务和接收器。

      http://developer.android.com/reference/android/os/AsyncTask.html

      【讨论】:

        猜你喜欢
        • 2011-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多