我正在开发必须自动检测网络何时可用的应用程序。我正在考虑在计时器的基础上运行后台线程以检测网络何时可用,这是“正确”方法还是有任何标准程序来检查它?

最佳答案

    you can use android.net.conn.CONNECTIVITY_CHANGE broadcast

    Add in your manifest



     <receiver android:name="com.example.utils.CheckInternetConnection"
        android:enabled="true" android:label="ConnectivityActionReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>



    public class CheckInternetConnection extends BroadcastReceiver {


        @Override
        public void onReceive(final Context arg0, Intent arg1) {

    if (haveNetworkConnection(arg0)) {
    //TODO iF INTERNET IS CONNECTED
    }else{
    //TODO iF INTERNET IS DISCONNECTED


    }
}
        private boolean haveNetworkConnection() {
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;

            try {
                android.net.ConnectivityManager cm = (android.net.ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                android.net.NetworkInfo[] netInfo = cm.getAllNetworkInfo();
                for (android.net.NetworkInfo ni : netInfo) {
                    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                        if (ni.isConnected())
                            haveConnectedWifi = true;
                    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        if (ni.isConnected())
                            haveConnectedMobile = true;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return haveConnectedWifi || haveConnectedMobile;
        }
}

关于java - 用于检测网络的后台线程可用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23386780/

10-10 07:11