我需要检测Android设备是否已连接到Internet.
本NetworkInfo类提供了一个非静态方法isAvailable()听起来很完美.
问题是:
NetworkInfo ni = new NetworkInfo();
if (!ni.isAvailable()) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
抛出此错误:
The constructor NetworkInfo is not visible.
Run Code Online (Sandbox Code Playgroud)
安全的赌注是有另一个类返回一个NetworkInfo对象.但我不知道哪个.
我需要一个处理我的SharedPreferences的类,我想出了3种方法,但经过一些研究后,似乎大多数都被认为是"反模式".
输入1
public final class MyPrefs {
private MyPrefs(){ throw new AssertionError(); }
public static void setFavoriteColor(Context context, String value){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("color_key", value).apply();
}
public static void setFavoriteAnimal(Context context, String value){
// ...
}
// ...
}
/* Usage */
MyPrefs.setFavoriteColor(this, "yellow");
// Reason why it might be considered "Bad"
// Class is not OO, just collection of static methods. "Utility Class"
Run Code Online (Sandbox Code Playgroud)
类型2
public class MyPrefs {
private SharedPreferences mPreferences;
private static volatile MyPrefs sInstance;
public static …Run Code Online (Sandbox Code Playgroud)