0

我正在尝试确定我的应用程序是否已连接到互联网。我将超时设置为 3 秒。有时 Internet 检查会以“未连接”的形式返回(即使我确实有 Internet 连接),有时它不会。为什么有时检查比其他人需要更长的时间?在检查时,我可以弹出一个对话框或其他东西吗?

public void isNetworkAvailable(final Handler handler)
{
    new Thread()
    {
        private boolean responded = false;

        @Override
        public void run()
        {
            new Thread()
            {
                @Override
                public void run()
                {
                    HttpGet requestForTest = new HttpGet("http://m.google.com");
                    try
                    {
                        new DefaultHttpClient().execute(requestForTest);
                        responded = true;
                    }
                    catch (Exception e)
                    {
                    }
                }
            }.start();

            try
            {
                int waited = 0;
                while (!responded && (waited < 3000))
                {
                    sleep(100);
                    if (!responded)
                    {
                        waited += 1000;
                    }
                }
            }
            catch (InterruptedException e)
            {
            } // do nothing
            finally
            {
                if (!responded)
                {
                    handler.sendEmptyMessage(0);
                }
                else
                {
                    handler.sendEmptyMessage(1);
                }
            }
        }
    }.start();
}

Handler h = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    { 
        if (msg.what != 1)
        { // code if not connected
            Log.i("Internet check", "Not connected");
        }
        else
        { // code if connected
            Log.i("Internet check", "Connected");
        }
    }
};
4

5 回答 5

0
    public static Boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if(ni != null && ni.isConnected())
            return true;

        //Toast.makeText(context, context.getString(R.string.no_internet_connection), Toast.LENGTH_SHORT).show();
        return false;
     }

需要权限:

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

编辑:

正如您正确指出的那样,这不是一个可靠的解决方案。就我而言(我确实没有提到),这足以作为与 LocationClient.isConnected() 配对的第一次检查。

查看您的代码,我认为值得一看 LocationClient,即使您不打算使用您的应用程序的位置感知。

我的理由是,您无需重复使用资源来检查您是否有有效的连接。LocationClient 使用与 Google Play 的现有通信来告诉您是否已连接。

当然,此解决方案仅在您假设您的用户已将 Google 帐户添加到他们的设备时才有效。

这是官方指南的链接:http: //developer.android.com/training/location/retrieve-current.html onConnected 和 onDisconnected 部分位于定义位置服务回调部分。

于 2013-09-26T13:47:51.610 回答
0

你考虑使用这个http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html / 或注册一个 BroadcastReceiver 以在连接断开/启动时通知它,然后您可以在应用程序的任何位置处理它?

public class CustomApplication extends Application {

    public static final String INTERNET_ACTION = "internet_action";
    public static final String EXTRA_STATUS = "status";

    @Override
    public void onCreate() {
        super.onCreate();


        monitorNetworkAvailability();
    }

    private void monitorNetworkAvailability() {

        //
        // Improve the way to handle Thread
        // 
        new Thread() {

            private boolean responded = false;

            @Override
            public void run() {

                while (true) {

                    new Thread() {
                        @Override
                        public void run() {
                            HttpGet requestForTest = new HttpGet("http://m.google.com");
                            try {
                                new DefaultHttpClient().execute(requestForTest);
                                responded = true;
                            } catch (Exception e) {
                            }
                        }
                    }.start();

                    try {
                        int waited = 0;
                        while (!responded && (waited < 3000)) {
                            sleep(100);
                            if (!responded) {
                                waited += 1000;
                            }
                        }
                    } catch (InterruptedException e) {
                    } // do nothing
                    finally {
                        Intent i = new Intent(INTERNET_ACTION);
                        i.putExtra(EXTRA_STATUS, responded);
                        sendBroadcast(i);
                    }

                    try {
                        Thread.sleep(1 * 60 * 1000);
                    } catch (InterruptedException e) {
                    }

                }


            }


        }.start();
    };
}

class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, i);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    IntentFilter i = new IntentFilter(CustomApplication.INTERNET_ACTION);
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean responded = intent.getBooleanExtra(CustomApplication.EXTRA_STATUS, false);
            if (!responded) {
                Toast.makeText(MyActivity.this, "No connection", Toast.LENGTH_SHORT).show();
            }
        }
    };

}
于 2013-09-26T13:48:46.450 回答
0

使用以下代码

if(!haveInternet()){

                    <Your Alert Dialog Here>

                }





private boolean haveInternet() {
            NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
            .getActiveNetworkInfo();
            if (info == null || !info.isConnected()) {
                return false;
            }
            if (info.isRoaming()) {
                return true;
            }
            return true;
        }
于 2013-09-26T13:50:44.693 回答
0

你说的对。您的问题是,设备会检查互联网连接,有时会从路由器那里得到一个响应,说它无法连接到互联网,但这本身就是一个响应,所以您的代码可能会认为有一个响应。以下是测试您是否真的可以连接到互联网的示例方法。

public static boolean hasActiveInternetConnection()
{
    try
    {
        new Socket().connect(new InetSocketAddress("google.com", 80), 4000);

        return true;
    } catch (Exception e)
    {
        return false;
    }
}

然后在您的活动中,您可以调用。(确保不要在 MAIN/UI 线程中运行它。使用异步或线程/处理程序/可运行策略)

if(hasActiveInternetConnection())
{
//yey I have internet
}
else
{
//no internet connection
}
于 2013-09-26T20:12:07.263 回答
0

我可以通过将其放入 AsyncTask 中来完成此操作。

class online extends AsyncTask<String, String, String> 
{
    boolean responded = false;
    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();
        pDialog2 = new ProgressDialog(Main.this);
        pDialog2.setMessage("Checking internet, please wait...");
        pDialog2.setIndeterminate(false);
        pDialog2.setCancelable(false);
        pDialog2.show();
    }

    protected String doInBackground(String... args) 
    {

        HttpGet requestForTest = new HttpGet("http://m.google.com");
        try
        {
            new DefaultHttpClient().execute(requestForTest); // can
            responded = true;
        }
        catch (Exception e)
        {
        }

        try
        {
            int waited = 0;
            while (!responded && (waited < 5000))
            {
                mHandler.postDelayed(new Runnable() 
                {
                    public void run() 
                    {
                    }
                }, 100);
                waited += 100;
            }
        }
        finally
        {
            if (!responded)
            {
                h.sendEmptyMessage(0);
            }
            else
            {
                h.sendEmptyMessage(1);
            }
        }
        return null;
    }

    protected void onPostExecute(String file_url) 
    {
        pDialog2.dismiss();
    }
}
于 2013-09-29T20:54:53.177 回答