Search code examples
androidandroid-activitybroadcastreceiver

A class that extends both Activity and BroadcastReceiver


I have tabhost and if I click on any of of them , a new class and its corresponding xml will launch. Each one class extends Activity, but I also need each of them to extends BroadcastReceiver. Why? right now the wordings of each activity and its view text are in English. But in the picker, if someone choose Spanish then I need to broadcast the Intent of setting Spanish to Num1 , Num2, Num3 class and its views that their wordings to be changed to spanish. Can I have public class Num1 extends Activity, BroadcastReiver, ...etc like that?

 host.addTab(host.newTabSpec("Num1")
            .setIndicator("Num1", getResources().getDrawable(R.drawable.icon_light))
            .setContent(new Intent(this, Num1.class)));

       host.addTab(host.newTabSpec("Num2")
            .setIndicator("Num2", getResources().getDrawable(R.drawable.icon_wrench))
            .setContent(new Intent(this, Num2.class)));

       host.addTab(host.newTabSpec("Num3")
            .setIndicator("Num3", getResources().getDrawable(R.drawable.icon_user))
            .setContent(new Intent(this, Num3.class)));

Solution

  • You cannot extend two classes. The usual way to deal with this is to define an inner class:

    public class MyActivity extends Activity {
        private mBroadcastReceiver;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            . . .
            mBroadcastReceiver = new BroadcastReceiver() {
                // your receiver implementation
            };
            // register the receiver
        }
        . . .
    }
    

    In this code the inner class is an anonymous subclass of BroadcastReceiver. You can also create a separate class that is passed an instance of your activity in the constructor. It can then make call-backs to your activity as needed.