Выполняйте действия над событием с определенной c временной задержкой несколько раз в al oop, пока условие не станет истинным? Использование рабочего потока, такого как Post delay runnable - PullRequest
0 голосов
/ 19 марта 2020
public class HomeActivity extends AppCompatActivity {
    private SensorManager sm;
    private float acelVal,
            acelLast,
            shake;
    private static int counter = 0;
    int PERMISSION_ID = 44;
    FusedLocationProviderClient mFusedLocationClient;
    String latitude = "",
            longitude = "";
    DatabaseReference pne;
    Button btnLogout;
    DatabaseReference pinn;
    String pin = "";
    String pin1 = "";
    String phoneu = "";
    String ids;
    int i = 0;
    EditText t5;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        t5 = findViewById(R.id.t5);
        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sm.registerListener(sensorListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        acelVal = SensorManager.GRAVITY_EARTH;
        acelLast = SensorManager.GRAVITY_EARTH;
        shake = 0.00f;
        btnLogout = findViewById(R.id.logout);
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        getLastLocation();
        btnLogout.setOnClickListener(new View.OnClickListener() {@Override
        public void onClick(View v) {
            FirebaseAuth.getInstance().signOut();
            Intent intToMain = new Intent(HomeActivity.this, MainActivity.class);
            startActivity(intToMain);
        }
        });
        Bundle bundle = getIntent().getExtras();
        //Extract the data…
        ids = bundle.getString("ids");
//        do {
//            pne = FirebaseDatabase.getInstance().getReference(String.valueOf(ids)).child("phone").child(String.valueOf(i));
//            pne.addValueEventListener(new ValueEventListener() {@Override
//            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//                phoneu = (String) dataSnapshot.getValue();
//                phoneNo.add(phoneu);
//            }@Override
//            public void onCancelled(@NonNull DatabaseError databaseError) {}
//            });
//            i++;
//        } while ( i < 5 );
    }

    private final SensorEventListener sensorListener = new SensorEventListener() {@Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        acelLast = acelVal;
        acelVal = (float) Math.sqrt((double)(x * x) + (y * y) + (z * z));
        float delta = acelVal - acelLast;
        shake = shake * 0.9f + delta;
        if (shake > 12) {
            counter++;
        }
        if (counter >= 3) {
            pinn = FirebaseDatabase.getInstance().getReference(ids);
            pinn.addValueEventListener(new ValueEventListener() {@Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                pin = (String) dataSnapshot.child("pin").getValue(String.class);
                GenericTypeIndicator < ArrayList < String >> t = new GenericTypeIndicator < ArrayList < String >> () {};
                final ArrayList < String > phone = dataSnapshot.child("phone").getValue(t);
                Toast.makeText(HomeActivity.this, "pin is " + pin, Toast.LENGTH_LONG).show();
                counter = 0;
                final SmsManager smsManager = SmsManager.getDefault();
                do {
                        for (int m = 0; m < 5; m++) {
                            smsManager.sendTextMessage(phone.get(m), null, "Hey It's an emergency at this location" + "http://maps.google.com/maps?q=" + latitude.toString() + "," + longitude.toString(), null, null);
                        }
                    try {
                        Thread.sleep(120000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } while (( pin1 . equals ( pin . toString ())));
                Toast t3 = Toast.makeText(getApplicationContext(), "Your Location has been sent to Your loved ones!!! Don't panic, Help will arrive soon", Toast.LENGTH_LONG);
                t3.show();
            }@Override
            public void onCancelled(@NonNull DatabaseError databaseError) {}
            });
        }
    }@Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    };@SuppressLint("MissingPermission")
    private void getLastLocation() {
        if (checkPermissions()) {
            if (isLocationEnabled()) {
                mFusedLocationClient.getLastLocation().addOnCompleteListener(
                        new OnCompleteListener < Location > () {@Override
                        public void onComplete(@NonNull Task < Location > task) {
                            Location location = task.getResult();
                            if (location == null) {
                                requestNewLocationData();
                            } else {
                                latitude = location.getLatitude() + "";
                                longitude = location.getLongitude() + "";
                            }
                        }
                        });
            } else {
                Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        } else {
            requestPermissions();
        }
    }@SuppressLint("MissingPermission")
    private void requestNewLocationData() {
        LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(0);
        mLocationRequest.setFastestInterval(0);
        mLocationRequest.setNumUpdates(1);
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mFusedLocationClient.requestLocationUpdates(
                mLocationRequest, mLocationCallback, Looper.myLooper());
    }
    private LocationCallback mLocationCallback = new LocationCallback() {@Override
    public void onLocationResult(LocationResult locationResult) {
        Location mLastLocation = locationResult.getLastLocation();
        latitude = mLastLocation.getLatitude() + "";
        longitude = mLastLocation.getLongitude() + "";
    }
    };
    private boolean checkPermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        return false;
    }
    private void requestPermissions() {
        ActivityCompat.requestPermissions(
                this, new String[] {
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION
                },
                PERMISSION_ID);
    }
    private boolean isLocationEnabled() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
                LocationManager.NETWORK_PROVIDER);
    }@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_ID) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLastLocation();
            }
        }
    }@Override
    public void onResume() {
        super.onResume();
        if (checkPermissions()) {
            getLastLocation();
        }

    }
    //get pin
    public void stop(View view) {
        pin1 = t5.getText().toString();
    }
class sendMessage implements Runnable{

    @Override
    public void run() {

    }
}
}

Здесь, в приведенном выше коде, при получении телефонных номеров из базы данных firebase и при встряхивании устройства 3 раза, устройство должно отправлять пользовательское сообщение для контактных номеров, извлеченных из базы данных, каждые 2 минуты. задержки И это не должно влиять на пользовательский интерфейс, и отправка сообщений должна прекратиться, если пользователь введет правильный вывод в «t5» EditText

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