Android: Как проверить три условия (логические переменные) перед продолжением работы с приложением? - PullRequest
0 голосов
/ 12 апреля 2020

У меня есть приложение, которое требует обнаружения служб определения местоположения (FINE_LOCATION), для которого необходимо включить либо данные, либо Wi-Fi, а также местоположение и (GPS).

Мне удалось чтобы обойти это, если одно условие отключено, но что мне нужно, если все три службы отключены, приложение должно пройти через пользователя, чтобы включить их все один за другим. Есть ли способ создать al oop или какой-нибудь слушатель переменных, чтобы увидеть, все ли условия выполнены?

public class dblogin extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

MaterialEditText email, password;
Button login, register, anon;
CheckBox loginState,tacState;
TextView tacAgree;
int responseData = 0;
SharedPreferences sharedPreferences;
private final int REQUEST_LOCATION_PERMISSION = 1;
boolean GPS_ACCESS = false;
boolean WLAN_ACCESS = false;




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

    if(GPS_ACCESS&&WLAN_ACCESS)
    {
        requestLocationPermission(); //Requires Permission to Location
    }
    else
    {
        requestWLANAccess(); //WIFI IS OFF
        requestGPSAccess();  //LOCATION is OFF
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    // Forward results to EasyPermissions
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}

@Override
public void onPermissionsGranted(int requestCode, List<String> list) {
    register= findViewById(R.id.register);
    login= findViewById(R.id.login);
    anon= findViewById(R.id.anon);
    login.setEnabled(true);
    register.setEnabled(true);
    anon.setEnabled(true);

    login.setText("Login");
    register.setBackgroundColor(Color.parseColor("#008577"));
    anon.setBackgroundColor(Color.parseColor("#008577"));
    // Some permissions have been granted
    // ...
    //Toast.makeText(this, "Permission is already granted", Toast.LENGTH_SHORT).show();
}

@Override
public void onPermissionsDenied(int requestCode, List<String> list) {
    // Some permissions have been denied
    // ...
    Toast.makeText(this, "Please allow access to location to continue using the app.", Toast.LENGTH_SHORT).show();
    ViewGroup vg =findViewById(R.id.myView);
    vg.invalidate();
    register= findViewById(R.id.register);
    login= findViewById(R.id.login);
    anon= findViewById(R.id.anon);
    register.setEnabled(false);
    anon.setEnabled(false);
    login.setText(R.string.grantpermission);
    register.setBackgroundColor(Color.parseColor("#ffffff"));
    anon.setBackgroundColor(Color.parseColor("#ffffff"));

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            requestLocationPermission();

        }
    });
    }

public void requestLocationPermission() {
    String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
    if(EasyPermissions.hasPermissions(this, perms)) {
        //Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
        onAccessGranted();
    }
    else {
        EasyPermissions.requestPermissions(this, "PLEASE GRANT ACCESS TO LOCATION SERVICES", REQUEST_LOCATION_PERMISSION, perms);
    }
}

public void requestGPSAccess(){
    //GPS is not ON
    LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;
    disbaleButtons();

    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch(Exception ex) {}

    try {
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch(Exception ex) {}

    if(!gps_enabled && !network_enabled) {
        // notify user
        new AlertDialog.Builder(this)
                .setMessage(R.string.gps_network_not_enabled)
                .setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton(R.string.Cancel,null)
                .show();
    }
    else
    {
        //GPS is ON
        GPS_ACCESS=true;
        //requestWLANAccess();
    }
}

public void requestWLANAccess(){
    //WIFI is not ON
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        // wifi is enabled
        WLAN_ACCESS=true;
    }
    else
    {
        new AlertDialog.Builder(this)
                .setMessage(R.string.wifi_network_not_enabled)
                .setPositiveButton(R.string.open_WIFI_settings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    }
                })
                .setNegativeButton(R.string.Cancel,null)
                .show();

    }


}


@Override
protected void onResume() {
    super.onResume();
    //setContentView(R.layout.activity_dblogin);
    requestLocationPermission();
}

private void disbaleButtons()
{
    register= findViewById(R.id.register);
    login= findViewById(R.id.login);
    anon= findViewById(R.id.anon);
    login.setEnabled(false);
    register.setEnabled(false);
    anon.setEnabled(false);
}

private void enableButtons()
{
    register= findViewById(R.id.register);
    login= findViewById(R.id.login);
    anon= findViewById(R.id.anon);
    login.setEnabled(true);
    register.setEnabled(true);
    anon.setEnabled(true);
}

private void onAccessGranted()
{
    final String idDevice = Settings.Secure.getString(this.getContentResolver(),
            Settings.Secure.ANDROID_ID);

    sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);

    email =findViewById(R.id.email);
    password= findViewById(R.id.password);
    register= findViewById(R.id.register);
    login= findViewById(R.id.login);
    loginState= findViewById(R.id.checkbox);
    anon= findViewById(R.id.anon);
    tacState= findViewById(R.id.agree);
    tacAgree =findViewById(R.id.terms);


    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                startActivity(new Intent(dblogin.this, register.class));
                finish();
        }
    });


    anon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //continue as guest
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.putString("guestmode","anon");
            editor.commit();
            checkScore(idDevice);
        }
    });


    tacAgree.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(dblogin.this, agreement.class));
        }
    });



    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (tacState.isChecked()) {
                // Agreed to TAC
                String txtEmail =email.getText().toString();
                String txtPassword =password.getText().toString();

                if ( TextUtils.isEmpty(txtEmail) || TextUtils.isEmpty(txtPassword))
                {
                    Toast.makeText(dblogin.this, "Please fill all the required fields", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    login(txtEmail,txtPassword);
                }
            }
            else
            {
               //Please agree
                Toast.makeText(dblogin.this, "Please agree to the terms and conditions of usage and privacy", Toast.LENGTH_LONG).show();
            }
        }
    });

    String loginStatus = sharedPreferences.getString(getResources().getString(R.string.prefLoginState),"");
    String getEmail = sharedPreferences.getString("prefEmail","");
    if(loginStatus.equals("loggedin"))
    {
        checkScore(getEmail);
    }
    else
        {
           //TODO what happens when logged out is the state in the shared preferences
        }
}

// END OF ON CREATE METHOD


private void checkScore(final String mEmail)
{
    final ProgressDialog progressDialog2 = new ProgressDialog(dblogin.this);
    progressDialog2.setCancelable(false);
    progressDialog2.setIndeterminate(false);
    progressDialog2.setTitle("Checking Login Data");
    progressDialog2.show();

    String URL = "https://innosens.com.my/dboard/check.php";
    StringRequest request = new StringRequest(com.android.volley.Request.Method.POST, URL, new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.equals("No Score"))
            {
                progressDialog2.dismiss();
                saveScore("-1",mEmail.toString());
                //Toast.makeText(dblogin.this, response, Toast.LENGTH_SHORT).show();
            }
            else
            {
                saveScore(response,mEmail.toString());
                progressDialog2.dismiss();
                //Toast.makeText(dblogin.this, response, Toast.LENGTH_LONG).show();
            }

        }
    }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            progressDialog2.dismiss();
            Toast.makeText(dblogin.this, error.toString(), Toast.LENGTH_LONG).show();

        }
    })
    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> param = new HashMap<>();
            param.put("email", mEmail);
            return param;
        }
    };

    request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MySingleton.getInstance(dblogin.this).addToRequestQueue(request);

}


public void saveScore(String score, String email)
{
    if ((Integer.parseInt(score))>=0) {
        responseData=Integer.parseInt(score);
        Intent intent = new Intent(dblogin.this, finalscore.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("SCORE", responseData);
        intent.putExtra("EMAIL", email);
        dblogin.this.startActivity(intent);
        finish();

    }
    else
    {
        Intent intent = new Intent(dblogin.this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        dblogin.this.startActivity(intent);
        finish();
    }

}


private void login(final String email, final String password)
{
    final ProgressDialog progressDialog = new ProgressDialog(dblogin.this);
    progressDialog.setCancelable(false);
    progressDialog.setIndeterminate(false);
    progressDialog.setTitle("Loggin In ");
    progressDialog.show();
    String URL = "https://www.innosens.com.my/dboard/login.php";
    StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.equals("Login Success"))
            {
                progressDialog.dismiss();
                //Toast.makeText(dblogin.this, response, Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = sharedPreferences.edit();
                if (loginState.isChecked())
                {
                    editor.clear();
                    editor.putString("prefEmail",email);
                    editor.putString(getResources().getString(R.string.prefLoginState),"loggedin");
                    editor.commit();
                }
                else
                {
                    editor.clear();
                    editor.putString("prefEmail",email);
                    editor.putString(getResources().getString(R.string.prefLoginState),"loggedout");
                    editor.commit();
                }


                checkScore(email);

            }
            else
            {
                progressDialog.dismiss();
                Toast.makeText(dblogin.this, response, Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            progressDialog.dismiss();
            Toast.makeText(dblogin.this, error.toString(), Toast.LENGTH_LONG).show();

        }
    }){

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> param = new HashMap<>();
            param.put("email", email);
            param.put("password", password);

            return param;
        }

    };
    request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MySingleton.getInstance(dblogin.this).addToRequestQueue(request);

} // END OF METHOD LOGIN }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...