How to Reuse getExternalStorageState?

五迷三道 提交于 2019-11-28 14:27:57

I would do this:

public static boolean performExternalStorageOperation(Runnable doIfMounted) {
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED)) {

        orderASC();// Loads the list
        if(doIfMounted != null) {
            doIfMounted.run();
        }
        return true;
    } else if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_UNMOUNTED)) {
        Alerts.sdCardMissing(this);
    }
    return false;
}

You can replace the Runnable with any kind of generic Listener (I use OnClickListeners a lot for actions that aren't necessarily clicks) or write your own callback class with a common method to call, but that would be my general approach.

This seems a little trivial for it's own class, but one approach is:

class StorageStateChecker  {
  static void storageState(XXX param, Listener l) {
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED)) {
        l.orderASC();// Loads the list

    } else if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_UNMOUNTED)) {
        Alerts.sdCardMissing(this);
    }
  }

  public interface Listener {
    public void orderASC();
  }
}

Note that XXX param needs replacing with whatever this represents in the call Alerts.sdCardMissing(this); as Alerts isn't an Android SDK class, I could only guess.

To use the code, just call StorageStateChecker(param /* was 'this' */, callbackClass /* implements StorageStateChecker.Listener */);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!