当互联网不可用时,应用程序停止

时间:2018-02-20 22:59:11

标签: android jsoup android-webview

我知道之前可能已经问过这个问题,但我无法理解问题在哪里?

当互联网不可用时,应用程序强制停止。我用不同的方法来解决这个问题,但我不能,问题是什么?

对于检查网络,我使用了以下代码:

  public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
        return true;
    else
        return false;
}

对于show alert,我在OnCreate方法中使用了它:

 if(!isNetworkAvailable(this)) {
        Toast.makeText(this,"No Internet connection",Toast.LENGTH_LONG).show();
    }

所有MainActivity类都是这样的:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

WebView webview;
String url = "http://hut.az/";
private ProgressDialog progressDialog;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if(!isNetworkAvailable(this)) {
        Toast.makeText(this,"No Internet connection",Toast.LENGTH_LONG).show();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    webview = (WebView) findViewById(R.id.webview1);
    webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    webview.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            new MyAsynTask().execute(url);
            return super.shouldOverrideUrlLoading(view, url);
        }

    });

    new MyAsynTask().execute(this.url);

}
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
        return true;
    else
        return false;
    }


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);


    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
    startActivityForResult(myIntent, 0);
    return true;

}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    FragmentManager fragmentManager = getFragmentManager();


    if (id == R.id.nav_camera) {


        url = "http://hut.az/arenda-kvartir/";
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                new MyAsynTask().execute(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        new MyAsynTask().execute(this.url);

        setTitle("Kiraye Evler");


    } else if (id == R.id.nav_gallery) {

        url = "http://hut.az/prodaja-kvartir/";
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                new MyAsynTask().execute(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        new MyAsynTask().execute(this.url);


    } else if (id == R.id.nav_slideshow) {

        url = "http://hut.az/novostroyki/";

        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                new MyAsynTask().execute(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        new MyAsynTask().execute(this.url);

    } else if (id == R.id.ticaret_obyekti) {

        url = "http://hut.az/kommercheskaya/";

        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                new MyAsynTask().execute(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        new MyAsynTask().execute(this.url);

    } else if (id == R.id.torpag_sahedi) {

        url = "http://hut.az/doma-uchastki/";

        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                new MyAsynTask().execute(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        new MyAsynTask().execute(this.url);

    } else if (id == R.id.kend_teserrufati) {

        url = "http://hut.az/garaji/";

        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                new MyAsynTask().execute(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        new MyAsynTask().execute(this.url);

    } else if (id == R.id.nav_manage) {

        url = "http://hut.az/zarubejnaya-nedvijimost/";

        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                new MyAsynTask().execute(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });

        new MyAsynTask().execute(this.url);

    } else if (id == R.id.nav_share) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);


        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, url);
        startActivity(Intent.createChooser(intent, "Share"));

    } else if (id == R.id.nav_send) {

        startActivity(new Intent(MainActivity.this, ElanYerlesdir.class));


    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

private class MyAsynTask extends AsyncTask<String, Void, Document> {
    @Override
    protected Document doInBackground(String... urls) {

        Document document = null;
        try {

            document = Jsoup.connect(urls[0]).get();
            document.getElementsByClass("header1").remove();
            document.getElementsByClass("topbar clearfix").remove();
            document.getElementsByClass("mapandslider").remove();
            document.select("div#right_sidebar").remove();
            document.select("div#left_sidebar").remove();
            document.getElementsByClass("footer1").remove();
            document.getElementsByClass("copyright").remove();


        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    }


    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle("Yüklənir");
        progressDialog.setMessage("Zəhmət olmasa gözləyin...");
        progressDialog.setIndeterminate(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Document document) {

        super.onPostExecute(document);

        webview.loadDataWithBaseURL(url, document.toString(), "text/html", "utf-8", "");
        progressDialog.dismiss();

    }


}
}

P.S Internet权限我也曾使用过:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

1 个答案:

答案 0 :(得分:0)

试试这个,

public static boolean isNetworkAvailable(Context activity) {
    ConnectivityManager connectivity = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}