android:应用程序无法连接到服务器时崩溃

dgsult0t  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(378)

我正在尝试创建一个登录应用程序 MySQL database . 它可以完美地登录。但问题是,如果不能连接到服务器应用程序崩溃!我使用asynctask类在后台连接服务器。看下面的代码。

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class Background_Worker extends AsyncTask<String,Void,String> {
    Context context;
    String type;
    Background_Worker(Context context){this.context = context;}

    @Override
    protected String doInBackground(String... strings) {
        type = strings[0];
        String login_url = "http://myserver420.com/user_info/login_user.php";

        if (type.equals("check_login_info")){
            try {
                String username = strings[1];
                String password = strings[2];

                URL url = new URL(login_url);

                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
                        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");

                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();

                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onPostExecute(String result) {

        // login user
        if (type.equals("check_login_info")){
            if (result.equals("login_success")){((Login) context).login_success();}
            else if (result.equals("login_not_success")){((Login) context).login_not_success();}
            else {}
        }
        else{}
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

在这种情况下,当它可以连接到服务器时,它如何才能完美地工作。但如果我关闭设备网络,它就会崩溃!现在我怎样才能解决撞车问题?谢谢你的回复。

slmsl1lt

slmsl1lt1#

将此方法放入代码中。如果它返回true,则执行代码,否则将给出未连接到网络的toast。

public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

相关问题