如何在Android中检查我的设备是否与互联网连接?

时间:2017-07-07 09:53:53

标签: android

说明:            大家好,我正在尝试检查我的设备是否与互联网连接。我正在解释我所做的所有步骤。

步骤1:我创建了一个接收器类来检查连接状态何时发生变化。

Step-2:我还创建了一个接口,其中我有获取连接状态的方法(true / false)

步骤3:在我的Activity上实现此侦听器,然后覆盖侦听器方法。

步骤4:如果我的互联网已连接,请继续。如果我的互联网没有连接,我把你的互联网没有连接的消息。

步骤5:最后,我在AndroidManifest.xml文件中注册此接收器。

注意:以上所有步骤都正常工作,直到SDK_VERSION Marshmallow。当我用Nougt(7.0)检查它时,它不起作用。

接收机



监听

int channels = I.channels();

int nRows = I.rows;
int nCols = I.cols * channels;

if (I.isContinuous())
{
    nCols *= nRows;
    nRows = 1;
}

int i, j;
uchar* p;
for (i = 0; i < nRows; ++i)
{
    p = I.ptr<uchar>(i);
    for (j = 0; j < nCols; ++j)
    {
        I.at<uchar>(10, 10) = 255;
    }
}
return I;

互联网连接状态方法

diff = ScanImageAndReduceC(diff);

namedWindow("Difference", WINDOW_AUTOSIZE);// Create a window for display.
imshow("Difference", diff);                   // Show our image inside it.

waitKey(0);                                          // Wait for a keystroke in the window
return 0;

Manifest.xml中的权限和注册接收器

public class ConnectivityReceiver extends BroadcastReceiver {

    public static ConnectivityReceiverListener connectivityReceiverListener;

    public ConnectivityReceiver(){
        super();
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (connectivityReceiverListener != null) {
            connectivityReceiverListener.onNetworkConnectionChanged(Utils.isInternetConnected(context));
        }
    }
    public static boolean isConnected(Context context) {
        if(Utils.isInternetConnected(context)){
            return true;
        }else{
            return false;
        }
    }
}

以下方法是检查互联网连接

public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}

以下方法检查是否已连接

public static boolean isInternetConnected(final Context _context) {
        ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                return true;
            }
            return true;
        } else {
            return false;
        }
    }

以下方法调用侦听器

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

<receiver
            android:name="com.durian.receivers.ConnectivityReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

这是我的Application类,它在android中注册了name参数

private boolean checkConnection() {
    boolean isConnected = ConnectivityReceiver.isConnected(CustomerActivity.this);
    showSnack(isConnected);
    return isConnected;
}

注意:在 naught 操作系统版本之下,一切正常。但问题是,当我在 naught 中进行测试时,它无法正常工作。请提供适用于所有操作系统的正确解决方案。

供参考,您可以查看snapdeal应用程序

我想要与snapdeal Android应用程序完全一样。

1 个答案:

答案 0 :(得分:0)

/**You can simply use below code Snippet**/

/**Below code Check 2 condition that Your device is connected to Wifi or Data - Connection or not. If yes then will also check that Internet is working or not..**/

/**ConnectivityReceiver Class**/

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ConnectivityReceiver
{
   private static ConnectivityReceiver.AsyncResponse asyncResponse;

/************************************************    for checking internet connection*******/
public static boolean isNetworkAvailable(Context context)
{

    ConnectivityManager connectivity = null;
    boolean isNetworkAvail = false;
    try
    {
        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;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (connectivity != null)
        {
            connectivity = null;
        }
    }
    return isNetworkAvail;
}

private static class ConnectionCheck extends AsyncTask<String,Void,Boolean>
{

    @Override
    protected Boolean doInBackground(String... params)
    {
        HttpURLConnection urlConnection = null;
        try
        {
            if(params[0].endsWith("") || params[0] == null)
            {
                params[0] = "http://www.google.com/";
            }

            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            if (!url.getHost().equals(urlConnection.getURL().getHost()))
            {
                // we were redirected! Kick the user out to the browser to sign on?

                return true;
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();

            return false;
        }
        finally
        {
            urlConnection.disconnect();
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean)
    {
        super.onPostExecute(aBoolean);
        asyncResponse.processFinish(aBoolean);

    }
}


public interface AsyncResponse
{
    void processFinish(boolean output);
}
public static void speedTest(String url,ConnectivityReceiver.AsyncResponse asyncResponse)
{
    ConnectivityReceiver.asyncResponse = asyncResponse;
    new ConnectivityReceiver.ConnectionCheck().execute(url);
}
 }


/**Code implementation in your class**/

String ConnectionCheck_Url = "http://www.google.com/";

if(ConnectivityReceiver.isNetworkAvailable(MainActivity.this))
    {
        ConnectivityReceiver.speedTest(ConnectionCheck_Url,new ConnectivityReceiver.AsyncResponse()
        {
            @Override
            public void processFinish(boolean output)
            {
                if (output)
                {

                    /* * If The output Value --->"True" Then Only 
              request will Execute
                     * NOTE: Here "True" Value Means Intenet is Working*/

                    // Implement your code here
                }
                else
                {
                   //Please_Check_Your_Internet_Connection
                }
            }
        });
    }
    else
    {
      //  Please_Connect_to_your_Wifi_or_Data_Connection
    }
}

/**Android MainifestFile.xml**/

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