我希望我的应用能够检测到我的设备是否有互联网连接。我写了这段代码,但它不起作用。这是代码:
package mi.internet;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;
public class navegando extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
comprobar();
}
private void comprobar() {
Context context = null;
// TODO Auto-generated method stub
if(navegando.isOnline(context)== false) {
new AlertDialog.Builder(this).setTitle("Advertencia").setMessage("No hay internet").setNeutralButton("Close", null).show();
finish();
}
}
public static boolean isOnline(Context ctx) {
ConnectivityManager connectivity = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] network_info = connectivity.getAllNetworkInfo();
if (network_info != null)
for (int i = 0; i < network_info.length; i++)
if (network_info[i].getState() == NetworkInfo.State.CONNECTED)
return true;
}
return false;
}
}
谢谢你!
感谢您的所有答案。我是新手,我不知道如何使用此代码。当我的应用程序启动时,我希望如果没有互联网连接,屏幕上会显示一条消息,表示没有互联网连接并完成活动。
再次坦克!
答案 0 :(得分:6)
请尝试以下代码。它检查设备中是否存在Internet连接。
public boolean CheckInternet()
{
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Here if condition check for wifi and mobile network is available or not.
// If anyone of them is available or connected then it will return true, otherwise false;
if (wifi.isConnected() || mobile.isConnected()) {
return true;
}
return false;
}
请在android清单文件中添加以下权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
答案 1 :(得分:4)
private boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
答案 2 :(得分:1)
首先给予许可
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
然后在您的活动中
private boolean isNetworkAvailable() {
ConnectivityManager cm
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni= cm.getActiveNetworkInfo();
return ni != null;
}
希望这对你有用