【问题标题】:How to check whether the android device can connecto to the network or not?如何检查android设备是否可以连接到网络?
【发布时间】:2014-03-14 17:48:29
【问题描述】:

我是Android编程的初学者,我正在尝试向远程服务器发出Http请求,我想检查用户是否可以连接到网络,以避免我的应用程序因失败而崩溃我正在制作的 AsyncTask。

我找到了这个方法:

 private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
 }

但是当我尝试在 doInBackground AsyncTask 方法实现中调用它时,应用程序崩溃了:

 class RemoteThread extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(IMieiDati.this);
        pDialog.setMessage("Caricamento...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }


    protected String doInBackground(String... strings ){
        // checking whether the network is not available
        // but the app crashes here
        if (!isNetworkAvailable()) {
            Log.d("Message", "No Network Connection. Aborting.");   
        } 

       // here I should make the request if the network is available
    }
            ...etc, etc...

我该如何解决,例如向用户显示一条消息,例如“我们很抱歉,为了正确使用该应用程序,您应该连接到网络”或类似的内容?

谢谢!

【问题讨论】:

    标签: java android android-asynctask connection


    【解决方案1】:

    首先最好在执行RemoteThread 类之前检查网络。 并确保您已为您的应用程序添加权限

    &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;

    &lt;uses-permission android:name="android.permission.INTERNET"/&gt;

    还要检查您是否正在导入正确的包 import android.content.Context;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多