Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/182.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何检查android设备是否可以连接到网络?_Java_Android_Android Asynctask_Connection - Fatal编程技术网

Java 如何检查android设备是否可以连接到网络?

Java 如何检查android设备是否可以连接到网络?,java,android,android-asynctask,connection,Java,Android,Android Asynctask,Connection,我是Android编程的初学者,我正在尝试向远程服务器发出Http请求,我想检查用户是否可以连接到网络,以避免我的应用程序因我正在执行的异步任务失败而崩溃 我发现这个方法: private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

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

我发现这个方法:

 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...
类RemoteThread扩展异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(imeidati.this);
pDialog.setMessage(“Caricamento…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
受保护的字符串背景(字符串…字符串){
//检查网络是否不可用
//但是应用程序在这里崩溃了
如果(!isNetworkAvailable()){
Log.d(“消息”,“没有网络连接。正在中止”);
} 
//如果网络可用,我应该在这里提出请求
}
……等等,等等。。。
我如何解决并向用户显示一条消息,如“很抱歉,为了正确使用应用程序,您应该连接到网络”或诸如此类的内容


谢谢!

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

还要检查您是否导入了正确的软件包
导入android.content.Context;