52

I'm just trying this little sample project, all it does: Activity one has a Button that sends a Broadcast. Activity two displays a toast when received. Below is the code, the Broadcast is never received. What do I do wrong?

Sending the Broadcast

public class SendBroadcast extends Activity {

    public static String BROADCAST_ACTION = "com.unitedcoders.android.broadcasttest.SHOWTOAST";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void sendBroadcast(View v){
        Intent broadcast = new Intent();
        broadcast.setAction(BROADCAST_ACTION);
        sendBroadcast(broadcast);
    }
}

Receiving it

public class ToastDisplay extends Activity {

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);
        }
    };

    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SendBroadcast.BROADCAST_ACTION);
        registerReceiver(receiver, filter);
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(receiver);
        super.onPause();
    }
}

Manifest

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".SendBroadcast" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ToastDisplay">
        <intent-filter>
            <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"></action>
        </intent-filter>
    </activity>
</application>
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
nheid
  • 1,088
  • 2
  • 11
  • 17
  • So did you ever find an answer to this? I'm having the same problem. I actually have a local service that broadcasts and intent that the currently open activity listens for (registering a broadcast receiver, as you do above). The activity never gets the message. I didn't put anything in the manifest, but since I'm registering the broadcast receiver, I didn't think I needed to. Did you ever get yours working? – Garret Wilson Nov 12 '11 at 23:39
  • Thanks. Turns out my [issue](http://stackoverflow.com/questions/8112164/android-activity-not-getting-broadcast-from-local-service/8115723#8115723) was a different one involving specifying MIME types. – Garret Wilson Nov 30 '11 at 13:30
  • hi nheid i am also seraching for the same .. and also implementing ur above code but its not working means Broadcat is sending to other activity..pls help.. – SRam Apr 24 '12 at 09:33
  • Broadcat is not sending to other activity – SRam Apr 24 '12 at 11:28
  • hi Garret Wilson have u find soln of above mentioned? – shyam Apr 25 '12 at 13:28
  • Hehhe.. you will never see the `Toast` with this code since you didnt call `show();` – Nezam Apr 30 '14 at 03:03
  • **Please see this Link** very good https://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app/44881551#44881551 –  Sep 12 '17 at 12:15

7 Answers7

42

What do I do wrong?

The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.

Instead you probably want to startActivity ToastDisplay from the first activity?

BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).

There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in BroadcastReceiver documentation:

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.

geekQ
  • 29,027
  • 11
  • 62
  • 58
  • How to check from within BroadcastReceiver's onReceive() method which activity is in the foreground? – zmeda Feb 21 '12 at 11:37
  • 2
    @zmeda that is not how you should think: either you know which activities can be impacted by a boradcastreceiver and you register a receiver for all of them, or you do not want to interact with activities and register the receiver in the app manifest. – Vince Dec 24 '14 at 22:39
  • One question. Is there any reason to call the super at the end of both methods? Or it doesn't matter? Thanks. – Ricardo Jul 19 '15 at 09:19
39
 Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);

makes the toast, but doesnt show it.

You have to do Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

rfsk2010
  • 8,571
  • 4
  • 32
  • 46
5

Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .

<application
  ....
  <receiver android:name=".ToastDisplay">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

if you want to register in activity then register in the onCreate() method e.g:

onCreate(){

    sentSmsBroadcastCome = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
        }
    };
    IntentFilter filterSend = new IntentFilter();
    filterSend.addAction("m.sent");
    registerReceiver(sentSmsBroadcastCome, filterSend);
}
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Tushar Bapte
  • 121
  • 1
  • 4
4

You need to define the receiver as a class in the manifest and it will receive the intent:

<application
  ....
  <receiver android:name=".ToastReceiver">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

And you don't need to create the class manually inside ToastDisplay.

In the code you provided, you must be inside ToastDisplay activity to actually receive the Intent.

m_vitaly
  • 11,856
  • 5
  • 47
  • 63
  • ok I had that. that works. but what do i do if i want it to be an activity, because for example i want to change some labels? – nheid Dec 29 '10 at 15:17
  • Please explain more about what are you trying to do. May be you don't need to use BroadcastReceiver and just start another Thread for that (AsyncTask is the best) ? Or you may send back an intent to the Activity. – m_vitaly Dec 29 '10 at 15:21
  • lets pretend activity two (the receiving part) is an activity displaying statistic data. whenever a user does some special event in activity one or a background service has new info i want to update the info in activity two. – nheid Dec 29 '10 at 15:40
  • Send an Intent with special attribute, to only deliver the intent if the activity is already open. See the javadocs for Intent for how to do this. – m_vitaly Dec 29 '10 at 15:52
  • Another hint: take a look at `samples/android-8/ApiDemos/src/com/example/android/apis/app/OneShotAlarm.java` from the SDK. – Steve Pomeroy Dec 29 '10 at 15:59
1

You forget to write .show() at the end, which is used to show the toast message.

Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

It is a common mistake that programmer does, but i am sure after this you won't repeat the mistake again... :D

Anu
  • 89
  • 1
  • 6
1

I think your problem is that you send the broadcast before the other activity start ! so the other activity will not receive anything .

  1. The best practice to test your code is to sendbroadcast from thread or from a service so the activity is opened and its registered the receiver and the background process sends a message.
  2. start the ToastDisplay activity from the sender activity ( I didn't test that but it may work probably )
daigoor
  • 685
  • 8
  • 21
0

Your also have to register the receiver in onCreate(), like this:

IntentFilter filter = new IntentFilter();
filter.addAction("csinald.meg");
registerReceiver(receiver, filter);
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28
keybee
  • 1,498
  • 20
  • 32