如何在执行AsyncTask之前检查网络信号强度。
例如,如果用户的电话没有互联网或不稳定的连接,则应弹出一个Toast,通知用户他/她的连接较弱。如果用户的手机具有强大或稳定的连接,则会执行asynctask。
PS。
我所说的就像这种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();
}
}
}
答案 0 :(得分: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
}
答案 1 :(得分:0)
我建议您创建一个定期执行的IntentService
并连接到httpbin.org
等已知网址。 ConnectivityManager
会告诉您设备是否已连接到WiFi或移动数据,但不会告诉您是否有实际可用的互联网连接。
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();
}
//----------------------------------------------------------------------------------------------
}
这是我使用Otto事件总线和OkHttp互联网库的代码。