重新连接互联网排球后从服务器获取响应

时间:2019-04-11 12:03:28

标签: android android-volley network-connection

虽然我在访问网络时断开URL时却要通过URL到达URL以获取服务器的响应。

我的问题是如何在重新连接Internet连接后如何从服务器获取数据,而不会再次点击url

 private void PostRequest(String Url) {

mRequest = new ServiceRequest(HomeActivity.this);
mRequest.makeServiceRequest(Url, Request.Method.GET, null, new ServiceRequest.ServiceListener() {
    @Override
    public void onCompleteListener(String response) {

        Log.d("reponse", response);

            JSONObject object = new JSONObject(response);

    }


    @Override
    public void onErrorListener() {
        indicator.setVisibility(View.GONE);
    }
});



 public void makeServiceRequest(final String url, int method, final 
 HashMap<String, String> param,ServiceListener listener) {

this.mServiceListener=listener;

stringRequest = new StringRequest(method, url, new Response.Listener<String> 
 () {
    @Override
    public void onResponse(String response) {
        try {
            mServiceListener.onCompleteListener(response);

        } catch (Exception e) {
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        try {
            if (error instanceof TimeoutError || error instanceof 
  NoConnectionError) {
            } else if (error instanceof AuthFailureError) {
            } else if (error instanceof ServerError) {
            } else if (error instanceof NetworkError) {
            } else if (error instanceof ParseError) {
            }
        } catch (Exception e) {
        }

         mServiceListener.onErrorListener();
    }
     }) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return param;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        return headers;
    }
};

     //to avoid repeat request Multiple Time
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, 
 DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
stringRequest.setShouldCache(false);
AppController.getInstance().addToRequestQueue(stringRequest);
 }
 }

请提出建议,在点击url之前我已经检查过互联网连接

2 个答案:

答案 0 :(得分:1)

您可以做一件事,创建失败请求的集合。注册CONNECTIVITY_CHANGE和WIFI_STATE_CHANGED的广播接收器,以在互联网连接可用时得到通知。设备连接到互联网后,您会在注册的广播接收器中收到通知,然后重试发送收藏集中的所有请求。请求成功后,从集合中删除请求。

答案 1 :(得分:1)

您可以使用网络更改广播接收器。

创建一个新的类 NetWorkChangeReceiver

public class NetWorkChangeReceiver extends BroadcastReceiver {

    @NonNull
    private final NetworkConnectionRestoredListener mListener;

    public NetWorkChangeReceiver(@NonNull NetworkConnectionRestoredListener listener) {
        mListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (NetworkUtil.isDeviceConnectedToInternet(context)) {
            mListener.onNetworkRestored();
        }
    }

    public interface NetworkConnectionRestoredListener {
        void onNetworkRestored();
    }
}

创建一个 NetworkUtil

@SuppressWarnings("deprecation")
public class NetworkUtil {

    private NetworkUtil() {
        // no instances
    }

    public static boolean isDeviceConnectedToInternet(@NonNull Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(
                CONNECTIVITY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            for (Network network : connManager.getAllNetworks()) {
                if (network != null) {
                    final NetworkInfo networkInfo = connManager.getNetworkInfo(network);

                    if (networkInfo != null && networkInfo.isConnected()) {
                        return true;
                    }
                }
            }
            return false;
        } else {
            NetworkInfo mWifi = connManager.getNetworkInfo(TYPE_WIFI);
            if (mWifi != null && mWifi.isConnected()) {
                return true;
            }

            NetworkInfo m3G = connManager.getNetworkInfo(TYPE_MOBILE);
            if (m3G != null && m3G.isConnected()) {
                return true;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                NetworkInfo mEthernet = connManager.getNetworkInfo(TYPE_ETHERNET);
                return mEthernet != null && mEthernet.isConnected();
            } else {
                return false;
            }
        }
    }
}

在您的活动中,实现 NetWorkChangeReceiver.NetworkConnectionRestoredListener

public class HomeActivity extends AppCompatActivity implements NetWorkChangeReceiver.NetworkConnectionRestoredListener {

NetWorkChangeReceiver mNetworkChangeReceiver;

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

//Use this to register the receiver while making the server call.
context.registerReceiver(mNetworkChangeReceiver = new NetWorkChangeReceiver(this), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
    public void onNetworkRestored() {
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
        if (mNetworkChangeReceiver != null) {
            try {
                unregisterReceiver(mNetworkChangeReceiver);
                mNetworkChangeReceiver = null;
            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

@Override
    protected void onStop() {
        super.onStop();
        if (mNetworkChangeReceiver != null) {
            try {
                unregisterReceiver(mNetworkChangeReceiver);
                mNetworkChangeReceiver = null;
            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }
}