如果找到网络,如何将数据上传到服务器?

时间:2015-04-21 08:11:29

标签: android

我的Android应用程序基于网络连接,当我的手机连接到互联网时工作正常但是当互联网连接断开时它停止工作(肥胖),没有自动连接。

我想在互联网可用时将数据发送到服务器上。

任何帮助对我都有帮助。

NetworkBroadcastReceiver.java

public class NetworkBroadcastReceiver extends BroadcastReceiver {
private static ConnectivityManager mConnectivityManager;

public NetworkBroadcastReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving
    // an Intent broadcast.
    if (isNetworkAvailable(context))
        Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context, "Not Connected", Toast.LENGTH_LONG).show();
}

/**
 *
 * @param context
 * @return
 */
public static boolean isNetworkAvailable(Context context) {
    boolean isMobile = false;
    boolean isWifi = false;

    NetworkInfo[] infoAvailableNetworks = getConnectivityManager(context).getAllNetworkInfo();

    if (infoAvailableNetworks != null) {
        for (NetworkInfo network : infoAvailableNetworks) {

            if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                if (network.isConnected() && network.isAvailable())
                    isWifi = true;
            }
            if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                if (network.isConnected() && network.isAvailable())
                    isMobile = true;
            }
        }
    }

    return isMobile || isWifi;
}

/**
 * Return connectivity manager instance.
 * @return mConnectivityManager
 */
public static ConnectivityManager getConnectivityManager(Context context) {

    if (mConnectivityManager == null) {
        mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    return mConnectivityManager;
}

}

的Manifest.xml

<receiver
        android:name=".receiver.NetworkBroadcastReceiver"
        android:enabled="true"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
        </intent-filter>
    </receiver>

1 个答案:

答案 0 :(得分:0)

要检查网络状态,请确保已在清单中声明了ACCESS_NETWORK_STATE权限

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