Home Android Java code organization with classes
Reply: 0

Android Java code organization with classes

user2266
1#
user2266 Published in July 22, 2018, 8:35 am

To keep my code clean, I want to create utilities (classes) that work completely within themselves when instantiated from my project's main class. These utilities provide relevant interfaces and methods to interact with the main class when necessary. I have done this already with my UsbCommunicator and NetowrkCommunicator classes.

I am running into difficulties, however, with my PhoneStateManager class. I already have it passing reference to the interface and main thread through the constructor:

public class PhoneStateManager {
    public PhoneStateManager(Callback callback, AppCompatActivity thread) {
        this.callback = callback;
        this.thread = thread;
    }

    public interface Callback {
        void onPhoneAction(int type);
    }

    public AppCompatActivity thread;
    public Callback callback;
}

I can utilize the reference to the main thread to provide methods to register and unregister a broadcast receiver that listens, records, and reports back to the main class on important user input:

public void register() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_USER_PRESENT);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    thread.registerReceiver(broadcastReceiver, filter);
}
public void unregister() {
    thread.unregisterReceiver(broadcastReceiver);
}

However, some input require an implementation of OnTouchListener on the Activity class to get the appropriate receivers, such as in volume button listeners:

public class MainActivity extends Activity immplements OnTouchListener {
   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event) {
       if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
           event.startTracking();
           return true;
       }
       return super.onKeyDown(keyCode, event);
   }
}

Is there a way to implement these methods in my utility class without having to include all the onTouch, onKeyDown, and onKeyUp methods in the main class?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.313627 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO