0

How I can possibly check the network signal strength before executing the AsyncTask.

For example If user's Phone has no Internet or Unstable Connection A toast should popup notifying the user that he/she has a weak connection. And if the user's phone has a strong or stable connection the asynctask will be executed.

PS.

what I am talking about is like this kind of asynctask

class AttemptGetData extends AsyncTask<String, String, String>{
        String ID = att_id.toString();
        String Stud_id = stud_no.toString();
        String remarks = RadioAttBtn.getText().toString();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AddStudentAttendance.this);
            pDialog.setMessage("In Progress...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected String doInBackground(String... params) {
            List<NameValuePair> mList = new ArrayList<NameValuePair>();
            mList.add(new BasicNameValuePair("att_list_id", ID));
            mList.add(new BasicNameValuePair("student_no", Stud_id));
            mList.add(new BasicNameValuePair("remark", remarks));

            Log.d("starting", "fetch");

            JSONObject json = jsonParser.makeHttpRequest(url1, "POST", mList);

            try {
                verify = json.getString("Message");
                return verify;
            }catch (JSONException e){
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pDialog.dismiss();
            if (s != null){
                Toast.makeText(getApplicationContext(), verify, Toast.LENGTH_LONG).show();
            }
        }
    }

2 Answers2

0
WifiManager wifiManger= (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); 
// in Activity replace getActivity() by Context in above line
WifiInfo wifiInfo = wifiManger.getConnectionInfo();
int speedMbps = wifiInfo.getLinkSpeed();
int myspeed=2000;  //mention your speed 
if(speedMbps>2000)
{
   // start  AsyncTask
}
else
{
// your Toast message for weak connection 
}
sasikumar
  • 12,540
  • 3
  • 28
  • 48
  • hi sir I find your answer interesting but I think I also need the code for wifiManager –  Mar 09 '16 at 14:02
  • oh I almost forgot sir its not only in wifi but with mobile data also –  Mar 09 '16 at 14:12
  • thanks for the response sir, I found a solution that satisfies my need :) –  Mar 09 '16 at 15:11
0

I would suggest that you create an IntentService that executes periodically and connects to a known URL like httpbin.org. ConnectivityManager will tell you if the device is connected to WiFi or mobile data but that won't tell you if you have actual usable Internet connection.

import android.app.IntentService;
import android.content.Intent;

import com.squareup.otto.Bus;

import java.io.IOException;

import chat.example.app.App;
import chat.example.app.events.NetworkStatusEvent;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand.
 * Our app uses this service to find out if we have internet connection or not.
 *
 * Why do we prefer this approach over using ConnectivityManager?
 * This is because having an active network interface doesn't guarantee that a particular networked
 * service is available. Network issues, server downtime, low signal, captive portals, content filters
 * and the like can all prevent your app from reaching a server.
 * For instance you can't tell for sure if your app can reach Twitter until you receive a valid response
 * from the Twitter service.
 * Source: http://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android
 *
 * We will use https://httpbin.org/ to check for network connectivity
 * httpbin(1): HTTP Request & Response Service
 *
 */
public class NetworkStatusService extends IntentService{
    private static final String url = "https://httpbin.org/ip";
    private static final String TAG = "NetworkStatusService";
    //----------------------------------------------------------------------------------------------
    public NetworkStatusService(){
        super(TAG);
    }
    //----------------------------------------------------------------------------------------------
    @Override
    protected void onHandleIntent(Intent intent) {
        Logger.d(TAG,"NetworkStatusService Invoked");
        Bus bus = App.getInstance().getEventBus();
        bus.register( this );
        NetworkStatusEvent status = new NetworkStatusEvent();
        try{
            if( makeRequest().isSuccessful() ){
                Logger.d(TAG,"Network Available");
                status.isAvailable = true;
                bus.post( status );
            }else{
                Logger.d(TAG,"Network Unavailable");
                status.isAvailable = false;
                bus.post( status );
            }
        }catch(IOException e){
            Logger.d(TAG,"Network Unavailable");
            bus.post( status );
        }finally{
            bus.unregister( this );
        }
    }
    //----------------------------------------------------------------------------------------------
    private Response makeRequest() throws IOException {
        OkHttpClient client = App.getInstance().getOkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        return client.newCall( request ).execute();
    }
    //----------------------------------------------------------------------------------------------
}  

This is my code using Otto event bus and OkHttp internet library.

An SO User
  • 24,612
  • 35
  • 133
  • 221
  • hi sir is this gonna be useful If I use this code? what I am trying to accomplish is the app checks the signal strength of the internet connection both wifi and mobile data. after checking the signal if the connection is too slow it wont execute the asynctask –  Mar 09 '16 at 14:04
  • @CallMeJeo Will this be useful ? Depends on your use case. Whenever the user wants the asynctask executed, start this service and wait for the event. If there is network, executed the async task. If not, display a toast or whatever – An SO User Mar 09 '16 at 14:15
  • oh see. this maybe work, but no offense sir this is not what I am trying to accomplish. as I've mention earlier the app must check the signal strength if it is weak or strong not only checks if there is an internet connection. –  Mar 09 '16 at 14:26
  • thanks for the response sir, I found a solution that satisfies my need :) –  Mar 09 '16 at 15:11