0

I am trying to communicate/update UI from Service to activity. The broadcast I receive is not what I had sent. Any ideas why?

Service code:

@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);

Activity code:

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");
                }

I have not registered the receiver in manifest. Is it necessary?

As mentioned in comments: I do not receive the same action in broadcast receiver and the value from intent is NULL.

What am I doing wrong?

Thanks for your help.

4

2 に答える 2

4

You dont need to use getIntent, because it translates to Activity's intent, not received broadcast's intent. So in your case, you need to use intent only which refers to broadcasted intent. And make sure you do make a check before reading the desired value from bundle, because there might be a possibility that you are getting another broadcast first which doesn't contain lol in its bundle.

So in your broadcast receiver, do it like this:

....
String val = getintent.getStringExtra("lol");

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

P.S. no, you dont need to register any broadcast receiver because it is created and being used programmatically

于 2012-05-14T06:15:12.993 に答える
1

If you are making web requests or extended tasks I'd check out the async task. It makes it way easier to update the UI. Just make sure you call onPreExecute() and onPostExecute() to do this. I don't like services and receivers.

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

于 2012-05-14T04:55:15.003 に答える