我有办法每 15 秒测试一次互联网连接。如果设备有互联网连接,则不需要任何东西,但如果您没有互联网连接,我想调用 Fragment。崩溃。如果我无法从 AsyncTask 中调用片段,我可以从 MainActivity 中调用它。我不知道怎么做。检查InternetAsyncTask.classpublic 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); } }}
2 回答
沧海一幻觉
TA贡献1824条经验 获得超5个赞
activity您从未设置异步任务的属性。
你 AsyncTask 的构造函数应该是:
public CheckInternetAsyncTask(Activity activity) {
this.context = activity.getApplicationContext();
this.activity = activity;
}
并将您的任务称为:
new CheckInternetAsyncTask(MainActivity.this).execute();
白衣染霜花
TA贡献1796条经验 获得超10个赞
在 Giorgos 代码的基础上,尝试这个小改动:
public CheckInternetAsyncTask(AppCompatActivity activity) {
this.context = activity.getApplicationContext();
this.activity = activity;
}
添加回答
举报
0/150
提交
取消