Best example of Abstract class in Android

后端 未结 3 906
孤独总比滥情好
孤独总比滥情好 2020-12-25 08:05

I am trying to design one Abstract class and method in Android and call those methods by extending the class from my parent Activity class but I don\'t how to call my abstra

3条回答
  •  孤城傲影
    2020-12-25 08:50

    Register and Unregister any BroadcastReceiver

    Here is an example which you can use to register and un-register ANY BroadcastReceiver using an Abstract class:

    BaseClass:

    public abstract class BaseReceiverActivity extends AppCompatActivity{
    
        private BroadCastReceiver receiver;
        private IntentFilter filter;
    
        public abstract BroadCastReceiver getReceiver();
        public abstract IntentFilter getFilter();
    
        @Override
        public void onStart(){
            super.onStart();
            configureReceiver()
            registerReceiver(receiver, filter);
        }
    
        @Override
        public void onStop(){
            super.onPause();
            unregisterReceiver(receiver);
        }
    
        private void registerMyReceiver(){        
            registerReceiver(receiver, filter);    
        }
    
        private void configureReceiver(){
             receiver = getReceiver();
             filter   = getFilter();
        }
    
    }
    

    Child class:

    public class WifiScanner extends BaseReceiverActivity{
    
        @Override
        public void onCreate(Bundle sis){
             super.onCreate(sis);
             setContentView(R.layout.yourLayout);
        }
    
        @Override
        public BroadCastReceiver getReceiver(){
             return new YourReceiver();
        }
    
        @Override
        public IntentFilter getFilter(){
             return IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        }
    
    }
    

    Full working code

    Here

提交回复
热议问题