如何在Android的Java类中处理Internet连接



如果我的互联网连接不好,或者如果我失去了连接,我无法在java类中处理,在活动中,我可以检查互联网连接,但这里没有,所以我要在追踪的同时处理互联网连接

 @Override
public void onLocationChanged(Location location) {
    sharedPreferences = mContext.getSharedPreferences(PREFS_NAME, 0);
    editor = sharedPreferences.edit();
    emailSharedPref = sharedPreferences.getString("email", "");
    Log.e("emailLocation", emailSharedPref);
    Log.i("long", "" + location.getLongitude() + " TIME: " + t.time());
    getAdress(location.getLatitude(),location.getLongitude());
        JSONObject jsonObject = new JSONObject();
        URLPath urlPath = new URLPath();
        String serverURL = urlPath.trackEmployee;
        WebServiceRequest request = new WebServiceRequest();
        request.setUrl(serverURL);
        try {
            jsonObject.put("latitude", location.getLatitude());
            jsonObject.put("longitude", location.getLongitude());
            jsonObject.put("street", street);
            jsonObject.put("district", district);
            jsonObject.put("city", city);
            jsonObject.put("time", t.time());
            jsonObject.put("date", t.date());
            jsonObject.put("email", sharedPreferences.getString("email", ""));
            Log.e("jsonLocation", jsonObject.toString());
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        request.setRequestBody(jsonObject);
        WebServiceAsyncTask webService = new WebServiceAsyncTask();
        WebServiceRequest[] requestArr = {request};
        webService.execute(requestArr);

}

    public void getAdress(double longt, double lat) {
    try {
        addresses = geocoder.getFromLocation(longt, lat, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (addresses != null) {
        street = addresses.get(0).getAddressLine(0);
        district = addresses.get(0).getAddressLine(1);
        city = addresses.get(0).getAddressLine(2);
       connection="on";
        Log.d("connection",connection+".."+addresses.toString());
    }else{
        connection="off";
        Log.d("connection",connection);
    }
}

您可以使用ConnectivityManager通过操作ConnectivityManager.CONNECTIVITY_ACTION注册BroadcastReceiver。如果连接发生更改,将发送广播事件。在onReceive方法中,您可以更新标志,并在方法中建立任何连接之前使用这些标志进行检查。

例如。

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        checkStatus();
    }
};
private void checkStatus(){
    ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); 
    //for airplane mode, networkinfo is null
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    //connection details
    String status = networkInfo.getState().toString();
    String type = networkInfo.getTypeName();
    boolean isConnected = networkInfo.isConnected();
    //update flags here and check them before establishing connection
}
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    IntentFilter intentFilter =new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mBroadcastReceiver,intentFilter);
}

检查是否存在网络连接的简单方法

你可以在想要传递有效应用程序上下文的地方使用它

 /**
 * check for network connection
 */
public static boolean isOnline(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

注意:这不能解决您查询的网络资源的可达性

我建议在AsyncTask中使用HttpURLConnection,并尝试处理SocketTimeoutException以避免数据连接不良的问题

正如@tyler sebastian提议的那样:

  Handler mHandler;
  public void useHandler() {
    mHandler = new Handler();
    mHandler.postDelayed(mRunnable, 1000);
  }
  private Runnable mRunnable = new Runnable() {
      @Override
      public void run() {
          Log.e("Handlers", "Calls");
          /** Do something **/
          mHandler.postDelayed(mRunnable, 1000);
      }
  };

如何从处理程序中删除挂起的执行

  • mHandler.removeCallbacks(mRunnable(

如何再次安排

  • mHandler.postDelayed(mRunnable,1000(

Runnable在UI线程下工作,因此您可以在处理程序中更新各自的Runnable 中的UserInterface

那么你可以使用View.sendPostD这里你得到了更多的例子

相关内容

最新更新