3

我需要检测 Android 设备在启动时是否已连接或断开互联网...如果没有连接,应用程序将无法打开..我尝试了很多次..但我失败了..这是我启动的来源代码 :

private Handler splashHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Runnable r = new Runnable(){
        public void run(){
            Intent brain = new Intent(Splash.this, MainMenu.class);
            startActivity(brain);
            finish();
        }
    };
    setContentView(R.layout.splashscreen);
    splashHandler.postDelayed(r, 2000);
}

public void onResume(Bundle savedInstanceState){
    super.onResume();
}

}

如果有人帮助我并给我一个源代码..告诉我我必须把它放在哪里..

4

2 回答 2

3

从此 SO 帖子:检测 Android 上是否有可用的 Internet 连接

这是您的代码应如下所示:

private Handler splashHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Runnable r = new Runnable(){
        public void run(){
            Intent brain = new Intent(Splash.this, MainMenu.class);
            startActivity(brain);
            finish();
        }
    };
    setContentView(R.layout.splashscreen);
    if(isNetworkAvailable())
        splashHandler.postDelayed(r, 2000);
    else {
        //Notify user they aren't connected
        Toast.makeText(getApplicationContext(), "You aren't connected to the internet.", Toast.LENGTH_SHORT).show();
        //close the app
        finish();
    }
}

public void onResume(Bundle savedInstanceState){
    super.onResume();
}

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

如上面的链接所述,您还需要添加:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

到你的AndroidManifest.xml文件...

于 2012-07-25T22:40:07.190 回答
0

看看这个。这是一个BroadcastReciver附带动作ConnectivityManager.CONNECTIVITY_ACTION.,它允许系统在网络连接发生变化时进行更改。

我希望它有所帮助。

于 2012-07-25T22:41:33.573 回答