相关疑难解决方法(0)

检测Android上是否有可用的Internet连接

我需要检测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对象.但我不知道哪个.

  1. 如何让上面的代码段工作?
  2. 我怎么能找到自己在在线文档中需要的信息?
  3. 你能为这种类型的检测提出更好的方法吗?

android internet-connection android-internet

667
推荐指数
6
解决办法
52万
查看次数

使用SharedPreferences的最安全的方法

我需要一个处理我的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)

java singleton android preferences sharedpreferences

14
推荐指数
1
解决办法
961
查看次数