Android Util类中的最佳实践

时间:2017-04-19 11:22:45

标签: java android static singleton

创建android util类的最佳做法是什么? 用singelton或其他东西创建静态方法或普通方法会更好吗?这些课程应该是可以重复使用的。

使用singelton的正常方法:

public class KeyboardUtils {

    private static final KeyboardUtils instance = new KeyboardUtils();

    private KeyboardUtils() {}

    public static KeyboardUtils getInstance() {
        return instance;
    }

    public void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void focusEt(final EditText et) {
        et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) {
                hideKeyboard(view);
            }
        });
    }
}

静态方法:

public class KeyboardUtils {

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void focusEt(final EditText et) {
        et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) {
                hideKeyboard(view);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

简单,不用担心。
只需导入:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

班级在这里:

public class Utils {
/**
 * Convertim to time format
 *
 * @param unix is time with long value
 * @return string time
 */
public static String convertUnix2Date(long unix) {
    if (unix == 0) return "";
    String result;
    Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
    @SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
    f.setTimeZone(TimeZone.getDefault());
    result = f.format(date);
    return result;
}

/**
 * Handling the keyboard on device
 *
 * @param activity
 */
private static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager =
            (InputMethodManager) activity.getSystemService(
                    Activity.INPUT_METHOD_SERVICE);
    if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
        inputMethodManager.hideSoftInputFromWindow(
                activity.getCurrentFocus().getWindowToken(), 0);
    }
}

/**
 * Handling the listener to dismiss the keyboard on device
 *
 * @param context <br>
 * @param view    is parent view <br>
 */
public static void setupDismissKeyboardListener(Context context, View view) {

    // Set up touch listener for non-text box views to hide keyboard.
    if (!(view instanceof EditText)) {
        view.setOnTouchListener((v, event) -> {
            hideSoftKeyboard((Activity) context);
            return false;
        });
    }

    //If a layout container, iterate over children and seed recursion.
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            View innerView = ((ViewGroup) view).getChildAt(i);
            setupDismissKeyboardListener(context, innerView);
        }
    }
}


/**
 * Converting the DP value to PX to display on device
 *
 * @param context <br>
 * @param value   is DP value
 * @return PX value
 */
public static int parseFromDPtoPX(Context context, float value) {
    Resources resources = context.getResources();
    return (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            value,
            resources.getDisplayMetrics()
    );
}


public static void setupUI(View view, final Activity activity) {
    //Set up touch listener for non-text box views to hide keyboard.
    if(!(view instanceof EditText)) {
        view.setOnTouchListener((v, event) -> {
            hideSoftKeyboard(activity);
            return false;
        });
    }

    //If a layout container, iterate over children and seed recursion.
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            View innerView = ((ViewGroup) view).getChildAt(i);
            setupUI(innerView, activity);
        }
    }
}


/**
 *
 */
protected Utils() {

}

public static final String TAG = "Utils";
public static final int DEFAULT_BUFFER_SIZE = 8192;
private static String sFormatEmail = "^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$";

/**
 * @return true if JellyBean or higher
 */
public static boolean isJellyBeanOrHigher() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}

/**
 * @return true if Ice Cream or higher
 */
public static boolean isICSOrHigher() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}

/**
 * @return true if HoneyComb or higher
 */
public static boolean isHoneycombOrHigher() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}

/**
 * @return true if GingerBreak or higher
 */
public static boolean isGingerbreadOrHigher() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}

/**
 * @return true if Froyo or higher
 */
public static boolean isFroyoOrHigher() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}

/**
 * Check SdCard
 *
 * @return true if External Strorage available
 */
public static boolean isExtStorageAvailable() {
    return Environment.MEDIA_MOUNTED.equals(Environment
            .getExternalStorageState());
}

/**
 * Check internet
 *
 * @param context
 * @return true if Network connected
 */
public static boolean isNetworkConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    if (activeNetworkInfo != null) {
        return activeNetworkInfo.isConnected();
    }
    return false;
}

/**
 * Check wifi
 *
 * @param context
 * @return true if Wifi connected
 */
public static boolean isWifiConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiNetworkInfo = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetworkInfo != null) {
        return wifiNetworkInfo.isConnected();
    }
    return false;
}

/**
 * Check on/off gps
 *
 * @return true if GPS available
 */
public static boolean checkAvailableGps(Context context) {
    LocationManager manager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);

    return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

/**
 * Download data url
 *
 * @param urlString
 * @return InputStream
 * @throws IOException IOException
 */


/**
 * @return an {@link HttpURLConnection} using sensible default settings for
 * mobile and taking care of buggy behavior prior to Froyo.
 * @throws IOException exception
 */
public static HttpURLConnection buildHttpUrlConnection(String urlString)
        throws IOException {
    Utils.disableConnectionReuseIfNecessary();

    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");
    return conn;
}

/**
 * Prior to Android 2.2 (Froyo), {@link HttpURLConnection} had some
 * frustrating bugs. In particular, calling close() on a readable
 * InputStream could poison the connection pool. Work around this by
 * disabling connection pooling.
 */
public static void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (!isFroyoOrHigher()) {
        System.setProperty("http.keepAlive", "false");
    }
}

/**
 * Check an email is valid or not
 *
 * @param email the email need to check
 * @return {@code true} if valid, {@code false} if invalid
 */
public static boolean isValidEmail(Context context, String email) {
    boolean result = false;
    Pattern pt = Pattern.compile(sFormatEmail);
    Matcher mt = pt.matcher(email);
    if (mt.matches()) {
        result = true;
    }
    return result;
}

/**
 * A method to download json data from url
 */
@SuppressWarnings("ThrowFromFinallyBlock")
public static String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception", e.toString());
    } finally {
        assert iStream != null;
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}
}

希望这会有所帮助。