Search code examples
androidbroadcastreceiverinternal-class

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


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?


Solution

  • 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.