在android中如何定期检查互联网连接

时间:2014-06-02 07:17:24

标签: android android-layout android-intent android-fragments androidhttpclient

我需要的是我的代码应该定期检查互联网状态(每隔30或40秒说一次)。如何做到这一点..我应该使用恶魔线程或Android中可用的任何其他组件。希望很清楚。< / p>

3 个答案:

答案 0 :(得分:1)

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

并添加此

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

答案 1 :(得分:1)

public boolean isOnline() {
        ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

        if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
            /*
             * Toast.makeText(getActivity(), "No Internet connection!",
             * Toast.LENGTH_LONG).show();
             */
            return false;
        }
        return true;
    }

并将其称为

if (isOnline()) {
//code if net available
}
else
{
Toast.makeText(MainActivity.this,"No Internet connection available  ",
                            Toast.LENGTH_SHORT).show();
}

如果你想检查Interval,那么将if条件放入线程

答案 2 :(得分:1)

尝试这个检查互联网连接可用性

public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity =   (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
    for (int i = 0; i < info.length; i++)
        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
            return true;
        }
    }
    return false;
}

使用此选项每40秒检查一次

Timer  networkTimer = new Timer();
NetWorkTimerTask networkTimerTask = new NetWorkTimerTask();
networkTimer.schedule(networkTimerTask, 0,40*1000);
public class NetWorkTimerTask extends TimerTask {

    @Override
    public void run() {
        networkHandler.sendEmptyMessage(0);
    }
}; 
@SuppressLint("HandlerLeak")
Handler networkHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        isOnline = isNetworkAvailable(getApplicationContext());
    }
};

在AndroidManifest.xml中添加权限

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