我有办法每 15 秒测试一次互联网连接。如果设备有互联网连接,则不需要任何东西,但如果您没有互联网连接,我想调用 Fragment。崩溃。如果我无法从 AsyncTask 中调用片段,我可以从 MainActivity 中调用它。我不知道怎么做。
检查InternetAsyncTask.class
public class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private MainActivity activity;
private Context context;
public CheckInternetAsyncTask(Context context) {
this.context = context;
}
@Override
protected Boolean doInBackground(Void... params) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
} catch (Exception e) {
Log.e("TAG", "Error checking internet connection"+ e.getMessage());
return false;
}
} else {
//Log.d("TAG", "No network available!");
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//Log.d("TAG", "result" + result);
if(result){
// do ur code
Toast.makeText(context,"Device is connected to internet.", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context,"Device is not connected to internet!",Toast.LENGTH_LONG).show();
EthernetControlFragment ethernetControlFragment = EthernetControlFragment.newInstance();
ethernetControlFragment.show(activity.getSupportFragmentManager(), "ethernet");
ethernetControlFragment.setCancelable(false);
}
}
}
沧海一幻觉
白衣染霜花
相关分类