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

时间:2015-07-02 20:50:23

标签: android tracking internet-connection

如果我的网络连接不好或如果我丢失连接,如何处理,我无法在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);
    }
}

2 个答案:

答案 0 :(得分:0)

您可以ConnectivityManager使用BroadcastReceiver操作注册ConnectivityManager.CONNECTIVITY_ACTION。如果连接发生变化,将发送广播事件。在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);
}

答案 1 :(得分:0)

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

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

 /**
 * 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();
}

注意:这不会解决您查询的网络资源的可访问性

我建议使用 HttpURLConnection 在AsyncTask中使用并尝试处理 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);
      }
  };

如何从Handler删除待处理的执行

  • mHandler.removeCallbacks(mRunnable);

如何再次安排

  • mHandler.postDelayed(mRunnable,1000);

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

然后你可以使用View.sendPostD Here u got more example