Android: How do I create broadcast receiver as an internal class of an activity

3.7k Views Asked by At

I have the following activity class:

public class Main extends TabActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public class LocationUpdateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "broadcast received", Toast.LENGTH_LONG).show();
        Log.e("ADNAN", "received");
    }

    }

}

and following entry in my manifest file:

<receiver android:name=".LocationUpdateReceiver" android:enabled="true"/>

and I use the following code to send a broadcast to my class:

Intent intent = new Intent(this,LocationUpdateReceiver.class);
        sendBroadcast(intent);

but the receiver doesn't receive the broadcast. However if I take my receiver class into its own file i.e LocationUpdateReceiver.java then it works as expected. What am I doing wrong here? do i need to specify my receiver in some different way in my manifest file? How do I create broadcast receiver as an internal class?

2

There are 2 best solutions below

2
On BEST ANSWER

If you want to have it as the member of Activity, you should register it in some of Activity's callbacks(onCreate(), for example) like this.

0
On

Android won't find the ".LocationUpdateReceiver" from the manifest file, since there isn't one (unless you create it like you said that worked).

Dont' know if it works, but try using ".TabActivity$LocationUpdateReceiver" instead in the manifest file. Inner classses's filenames are refered to this way.