如果连接到互联网/ wifi,Android运行代码

时间:2014-09-19 14:26:38

标签: java android

我有一个在启动时运行的应用程序,运行良好,我的新问题是我的应用程序需要互联网连接,我的应用程序在互联网连接之前启动,因此我的应用程序内部出现404错误,

是否可以将此代码放在循环中,如果互联网连接失败,他们会再次尝试代码,就像尝试捕获sorta一样。我是java的新手,不知道如何做到这一点。这是我的代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Loop Here to test if internet connection, if not try again

        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("http://example.com");

    }

我还尝试了以下尝试,现在我的应用程序将无法完全运行:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Socket socket = new Socket();
        InetSocketAddress address = new InetSocketAddress("www.google.com",80);
        try{
            socket.connect(address, 3000);
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setWebViewClient(new WebViewClient());
            myWebView.getSettings().setJavaScriptEnabled(true);
            myWebView.loadUrl("http://example.com");
        } catch (Exception e){
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setWebViewClient(new WebViewClient());
            myWebView.getSettings().setJavaScriptEnabled(true);
            myWebView.loadUrl("http://example.com");

        } finally {
            try {socket.close();}
            catch (Exception e){}
        }


    }

请帮助:(

我也一直在玩这个:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread t = new Thread();
        try{
            while(!isConnected(WifiExplorerActivity.this)){
                Thread.sleep(1000);
            }
        } catch (Exception e){

        }
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("http://example.com");

    }

并将其添加到我的Manifest:

<activity android:name=".WifiExplorerActivity" >        
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </activity>

3 个答案:

答案 0 :(得分:1)

你最好试试BroadcastReceiver:

use:要么使用整个类,要么只调用静态方法

public class NetworkManager extends BroadcastReceiver {

    protected static final String   TAG                 = NetworkManager.class.getSimpleName(); // log
    protected Context               mContext;
    protected boolean               mNoConnectivity;
    protected String                mReason;
    protected boolean               mIsFailover;
    protected static boolean        mIsConnected        = false;
    protected static boolean        mIsConnectivityGood = true;

    public NetworkManager(Context context) {
        this.mContext = context;
    }

    public void registerReceivers() {
        mContext.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) mContext.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;
    }

    /**
     * @param context
     * @return
     */
    public static NetworkInfo getNetworkInfo(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    /**
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected());
    }

    /**
     * @param context
     * @return
     */
    public static boolean isConnectedWifi(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
    }

    /**
     * @param context
     * @return
     */
    public static boolean isConnectedMobile(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    /**
     * @param context
     * @return
     */
    public static boolean isConnectedFast(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected() && isConnectionFast(info.getType(), info.getSubtype()));
    }

    protected static boolean isConnectionFast(int type, int subType) {
        if (type == ConnectivityManager.TYPE_WIFI) {
            return true;
        } else if (type == ConnectivityManager.TYPE_MOBILE) {
            switch (subType) {
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_CDMA:
                    return false; // ~ 14-64 kbps
                case TelephonyManager.NETWORK_TYPE_EDGE:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    return true; // ~ 400-1000 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    return true; // ~ 600-1400 kbps
                case TelephonyManager.NETWORK_TYPE_GPRS:
                    return false; // ~ 100 kbps
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                    return true; // ~ 2-14 Mbps
                case TelephonyManager.NETWORK_TYPE_HSPA:
                    return true; // ~ 700-1700 kbps
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                    return true; // ~ 1-23 Mbps
                case TelephonyManager.NETWORK_TYPE_UMTS:
                    return true; // ~ 400-7000 kbps
                case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                default:
                    return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        mNoConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
        mIsFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
        //
        if (mNoConnectivity) {
            mIsConnected = false;
        } else {
            if (isConnectedFast(mContext)) {
                mIsConnectivityGood = true;
            } else {
                mIsConnectivityGood = false;
            }
            mIsConnected = true;
        }
    }
}

答案 1 :(得分:1)

它应该工作:

public class SMSReceiver extends BroadcastReceiver
{
    public void onReceive(Context context, Intent intent)
    {
         WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(true);//make it enabled
       if(wifiManager.isWifiEnabled()){//if its enabled
//your code...
                 }
        }
    }

你应该在你的清单上:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>//if you want to change it

答案 2 :(得分:0)

这种方法对我有用:

public static boolean isConnectivityOn(Context ctx) {
    boolean resCode = false;

    try {
        ConnectivityManager cm =
                (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

        resCode = cm.getActiveNetworkInfo().isConnectedOrConnecting();

    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();

    }

    return resCode;
}

照顾

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
清单中的