【问题标题】:Checking for internet connectivity in Android在 Android 中检查互联网连接
【发布时间】:2015-09-29 21:24:58
【问题描述】:

我在 android 中创建了一个表单,其中包括名字、姓氏、手机号码等字段。 我正在使用网络服务将此数据发送到服务器并且它完美地发生。现在我想检查互联网连接,如果用户在填写表格并且用户提交表格时没有连接到互联网,表格应该上传到服务器每当用户回到互联网连接时。 谁能告诉我实现此功能的方法。 我尝试使用广播接收器检查互联网连接,但无法上传表单。我还必须将表单字段保存在永久存储中。目前我将它们保存在 bean 类中。

我正在粘贴我的完整表单活动类代码。 如果需要任何更改,请告诉我

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Boolean isValidEmail = false;
            String first_name = firstname.getText().toString().trim();
            String last_name = lastname.getText().toString().trim();
            String country = nation.getText().toString().trim();
            String mail = email.getText().toString().trim();
            String firm = company.getText().toString().trim();
            String mobile = phone.getText().toString().trim();
            String post = title.getText().toString().trim();
            String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
            if (first_name.equalsIgnoreCase("")) {
                Toast.makeText(getApplicationContext(), "Please enter your first name.", Toast.LENGTH_LONG).show();
            } else {
                registrationBean.setFname(first_name);
                if (last_name.equalsIgnoreCase("")) {
                    Toast.makeText(getApplicationContext(), "Please enter your last name.", Toast.LENGTH_LONG).show();
                } else {
                    registrationBean.setLname(last_name);
                    if (firm.equalsIgnoreCase("")) {
                        Toast.makeText(getApplicationContext(), "Please enter your company name.", Toast.LENGTH_LONG).show();
                    } else {
                        registrationBean.setCompany(firm);
                        if (post.equalsIgnoreCase("")) {
                            Toast.makeText(getApplicationContext(), "Please enter your designation", Toast.LENGTH_LONG).show();
                        } else {
                            registrationBean.setTitle(post);
                            if (mobile.equalsIgnoreCase("")) {
                                Toast.makeText(getApplicationContext(), "Please enter your phone number", Toast.LENGTH_SHORT).show();
                            } else {
                                registrationBean.setPhone(mobile);

                                if (mail.equalsIgnoreCase("") && !mail.matches(emailPattern)) {
                                    Toast.makeText(getApplicationContext(), "Invalid Email", Toast.LENGTH_LONG).show();

                                } else {
                                    registrationBean.setMail(mail);

                                    if (country.equalsIgnoreCase("")) {
                                        Toast.makeText(getApplicationContext(), "Please enter your country of residence", Toast.LENGTH_SHORT).show();
                                    } else {
                                        registrationBean.setNation(country);
                                        if (checked==true && registrationBean!=null)
                                        {

                                        }
                                        else {
                                            Toast.makeText(getApplicationContext(),"Please accept terms and conditions",Toast.LENGTH_LONG).show();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


    });
    if (img_path.equalsIgnoreCase("")) {
        retake_photo.setAlpha((float) 0.6);
    }
}

private void selectImage() {
    final CharSequence[] options = {"Take a Picture", "Choose from Gallery", "Cancel"};
    AlertDialog.Builder builder = new AlertDialog.Builder(ActivityForm.this);
    builder.setCancelable(false);
    builder.setTitle("Select Profile Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take a Picture")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                file = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                img_path = Environment.getExternalStorageDirectory() + "/temp.jpg";
                startActivityForResult(intent, 1);
            } else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
            if (options[item].equals("Choose from Gallery")) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                    Intent photoPickerIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    photoPickerIntent.setType("image/*");
                    photoPickerIntent.addCategory(photoPickerIntent.CATEGORY_OPENABLE);
                    startActivityForResult(photoPickerIntent, 2);
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                } else {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    img_path = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString();
                    startActivityForResult(intent, 2);
                }
            }
        }
    });
    builder.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch (requestCode) {
        case 1:
            try {
                bitmap = AppUtils.decodeFile(file.getPath(), 100, 100);
                registrationBean.setImage(file.getPath());
                //  ExifInterface ei = new ExifInterface(file.getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (bitmap != null) {

                iv_profile.setImageBitmap(bitmap);
                retake_photo.setAlpha(1);
            }


            break;
        case 2:
            try {
                String uriImage;
              imageUri = imageReturnedIntent.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                imageStream.close();
                if (selectedImage != null) {
                    iv_profile.setImageBitmap(selectedImage);
                    retake_photo.setAlpha(1);

                }


                 uriImage=imageUri.toString();
                registrationBean.setImage(uriImage);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
    }
}
private void callRegistrationService()
{
    String fname=registrationBean.getFname();
    String lname=registrationBean.getLname();
    String company=registrationBean.getCompany();
    String mobile=registrationBean.getPhone();
    String designation=registrationBean.getTitle();
    String image=getPath(imageUri);
    String email=registrationBean.getMail();
    String country=registrationBean.getNation();
    //email,firstName,lastName,userImage,company,title,phone,country
    new RegistrationAsyncTask(this, email, fname, lname, image, company, designation, mobile, country).execute();
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Do something
            callRegistrationService();
        }
    }
}

【问题讨论】:

  • 如此讨厌的if...else..if...else 构造。您需要实现某种验证器,它将以适当的方式实现这一点。或者,至少,您将其更改为 if (!check) { Toast.makeText(); return; } 序列。
  • 这是表单字段的验证器

标签: android broadcastreceiver


【解决方案1】:

“现在我想检查互联网连接以及用户是否未连接到互联网”

这可能会对你有所帮助。

 public void isOnline() {
            ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

            if(!(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable())){
                isInternetAvailable=true;
            }
            else
                isInternetAvailable=false;
        }

【讨论】:

    【解决方案2】:

    试试这个,

    创建类 Global.java

    import java.text.DecimalFormat;
    
    import com.affinity.affinityrescue.R;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    
    public class Global
    {
        public static String _useremail;
        public static String _user_id;
        public static final String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
        public static String regId = "";
        static Context context;
        static DecimalFormat decimalFormat = new DecimalFormat("#.#");
    
        public static boolean isNetworkconn(Context ctx)
        {
            context = ctx;
    
            ConnectivityManager connectivity = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null)
            {
                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;
        }
    
        // THIS METHOD IS USED FOR SHOW DIALOG WHEN NO INTERNET
        public static void showDialogOnNoInternet(final Activity activity)
        {
            AlertDialog.Builder alt_bld = new AlertDialog.Builder(activity);
            alt_bld.setIcon(R.drawable.ic_launcher);
            alt_bld.setTitle("No Internet Connection");
            alt_bld.setMessage("Please check your internet connection");
            alt_bld.setCancelable(false);
            alt_bld.setIcon(R.drawable.ic_launcher);
            alt_bld.setNeutralButton("OK", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.dismiss();
                }
            });
            alt_bld.show();
        }
    }
    

    在需要的地方编写代码。

    if (Global.isNetworkconn(getActivity())) {
    //code for success.
    }
    else
    {
       Global.showDialogOnNoInternet(getActivity());
    }
    

    就是这样。

    【讨论】:

      【解决方案3】:

      我希望即使在应用关闭时,应用也应该检查互联网连接,当互联网可用时,它应该使用网络服务将表单上传到服务器。

      我认为这种行为无法实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-16
        • 2016-08-28
        相关资源
        最近更新 更多