0

how to handle if I have poor internet connection or the if I lost my connection , I can't handle it in java class, In Activity I could check the internet Connection but here NO, So I'm tying to handle the internet connection while tracking

 @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);
    }
}
Aya Radwan
  • 181
  • 5
  • 17

2 Answers2

0

You can use the ConnectivityManager Register a BroadcastReceiver with the action ConnectivityManager.CONNECTIVITY_ACTION. A broadcast event will be sent if the connectivity changes. In the onReceive method you can update flags and use these flags for checking before establishing any connection in your method.

eg.

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);
}
void
  • 187
  • 1
  • 3
  • 13
0

a simple method to check if connection to network is present

u can use it where u wanna jus pass a valid application context

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

note : this not resolves reachability of network resources you querying

i'm advising to use HttpURLConnection to use in AsyncTask and try to handle SocketTimeoutException to avoid problems with poor data connection

as @tyler-sebastian proposes:

  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);
      }
  };

How to remove pending execution from Handler

  • mHandler.removeCallbacks(mRunnable);

How to schedule it again

  • mHandler.postDelayed(mRunnable, 1000);

Runnable works under UI thread so you can update UserInterface in Handler respective Runnable

then u can use View.sendPostD Here u got more example

Community
  • 1
  • 1
ceph3us
  • 7,326
  • 3
  • 36
  • 43