有什么方法可以在互联网重新连接时发送http帖子吗? 以下是情景。
情境: 1.发送http帖子,例如没有互联网连接时的json数据 2.一旦互联网连接,邮政请求将自动发送到服务器。
答案 0 :(得分:0)
<强> 1。创建自定义广播接收器:
private BroadcastReceiver connectionListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if ((networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) & (networkInfo.isConnected())){
sendBroadcastMessage(getString(R.string.FORCED_NETWORK_CONNECTION_ESTABLISHED));
Log.w(LOG, "wifi connection established");
}
else{
sendBroadcastMessage(getString(R.string.FORCED_NETWORK_CONNECTION_LOST));
Log.e(LOG, "no wifi connection");
}
}
};
<强> 2。注册广播接收器:
registerReceiver(connectionListener, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
第3。取决于您需要添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />