Android Как реализовать AsyncTask? Где EditText не отвечает - PullRequest
0 голосов
/ 14 марта 2020
    package com.example.pinkconnect;
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;
        DatabaseReference pinn;
        String pin;
        String pin1;
        String phoneu;
        int i=0;
        EditText t5;
        ArrayList<String> phoneNo = new ArrayList<String>();
        @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;
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

            getLastLocation();
            Bundle bundle = getIntent().getExtras();

    //Extract the data…
            String ids = bundle.getString("ids");
            pinn= FirebaseDatabase.getInstance().getReference(ids).child("pin");
            pinn.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                     pin= (String) dataSnapshot.getValue();
    //                String t=temp+"°C";
    //                tv2.setText(t);
                Toast.makeText(HomeActivity.this,"pin is "+pin,Toast.LENGTH_LONG).show();
                }
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                }
            });
            do {
                pne = FirebaseDatabase.getInstance().getReference(ids).child("phone").child(String.valueOf(i));
                pne.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        phoneu = (String) dataSnapshot.getValue();
    //                String t=temp+"%";
    //                tv4.setText(t);
    //                    Toast.makeText(HomeActivity.this, "phone numbers are " + phoneu, Toast.LENGTH_LONG).show();
                        //for(int i=0;i<5;i++){
                        phoneNo.add(phoneu);
    //  }
                        //Toast.makeText(HomeActivity.this, "nos" + phoneu.length(), Toast.LENGTH_LONG).show();

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                    }
                });
            i++;}while(i<5);
    //        Toast.makeText(HomeActivity.this, "phone numbers are " + phoneNo, Toast.LENGTH_LONG).show();
    //        Toast.makeText(HomeActivity.this, "nos" + phoneu.length(), Toast.LENGTH_LONG).show();
        }

        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) {
                    counter = 0;
                    SmsManager smsManager = SmsManager.getDefault();
                    //String phoneNumbers[] = {"8220029986", "8431639251","7892096912"};

                    //                String phoneNumbers=phoneu[];
                    //phoneNumbers[]=//get from DB;
                    //get Geolocation and set the custom text

    /* do{//send sms
    //enable the user to enter the pin
    //get the pin from the EditText;
    }while(pin.equals(Firebase pin));
    */
    //                for (String phone : phoneNumbers) {

                    do{

                    for(int m=0;m<5;m++){
                        //smsManager.sendTextMessage(phone, null, "sms message from pink connect" + latitude + longitude, null, null);
                        //https://www.latlong.net/c/?lat=0.000000&long=0.000000
                        //smsManager.sendTextMessage(phone, null, "Hi I'm XYZ, and My Location is..."+"https://www.latlong.net/c/?lat="+latitude.toString()+"&long="+longitude.toString(), null, null);
                        //http://maps.google.com/maps?q=24.197611,120.780512
                        //smsManager.sendTextMessage(phoneNo.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)));
                    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();
    //                t1.setText(latitude);
    //                t.setText(longitude);
                }
            }

            @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();
        }
    }

Уважаемый сэр! В приведенном выше коде, на счетчик встряхивания 3, я отправляю SMS на сохраненные контакты каждые 2 минуты, Чтобы остановить, я использую текст редактирования и кнопку, Вот если Я ввожу пин-код и нажимаю «Остановить» означает, что отправка SMS должна быть остановлена, но приложение не отвечает и закрывается само по себе, а EditText не отвечает

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