猿问

如何在AsyncTask中调用fragment?

我有办法每 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);

        }


    }

}

凤凰求蛊
浏览 116回答 2
2回答

沧海一幻觉

activity您从未设置异步任务的属性。你 AsyncTask 的构造函数应该是:public CheckInternetAsyncTask(Activity activity) {&nbsp; &nbsp;this.context = activity.getApplicationContext();&nbsp; &nbsp;this.activity = activity;}并将您的任务称为:new CheckInternetAsyncTask(MainActivity.this).execute();

白衣染霜花

在 Giorgos 代码的基础上,尝试这个小改动:&nbsp; &nbsp; public CheckInternetAsyncTask(AppCompatActivity activity) {&nbsp; &nbsp; &nbsp; &nbsp; this.context = activity.getApplicationContext();&nbsp; &nbsp; &nbsp; &nbsp; this.activity = activity;&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答