Close or end a class from another activity

0

I have this that saves the latitude and longitude in a database every 3 min if I go to another screen of the app is still running and then I want to close it with a button and stop saving     package com.example.lab_des_06.student;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {

    ///Esta es la clase del GPS donde muestra los datos de latitud y longitud
    /// y es almacenada en una base de datos de SQLite (por ahora)


    Button btnGPS,bdgps;
    TextView tvUbicacion,tv2,tvmes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        tvUbicacion = (TextView)findViewById(R.id.tvUbicacion);
        tv2 = (TextView)findViewById(R.id.tv2);
        tvmes  = (TextView)findViewById(R.id.tv3);

        btnGPS = (Button)findViewById(R.id.btnGPS);
        bdgps = (Button)findViewById(R.id.bdgps);


        bdgps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Main2Activity.this,mostrarGPS.class);
                startActivity(intent);
                ejecutar();
            }
        });

        btnGPS.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View v) {
                                          // Acquire a reference to the system Location Manager
                                       LocationManager locationManager = (LocationManager) Main2Activity.this.getSystemService(Context.LOCATION_SERVICE);

                                    // Define a listener that responds to location updates
                                     LocationListener locationListener = new LocationListener() {
                                     public void onLocationChanged(Location location) {
                                                  // Called when a new location is found by the network location provider.
                                         // Y pues esto se activa cuando se comprobo que el GPS esta activado
                                           // tvmes.setText("Ubicacion actual");
                                             tvUbicacion.setText(" "+location.getLatitude());
                                              tv2.setText(" "+location.getLongitude());
                                             }

                                        public void onStatusChanged(String provider, int status, Bundle extras) {}

                                        //Este codigo se activa cuando detecta que el GPS asido activado uwu
                                        public void onProviderEnabled(String provider) {
                                            tvmes.setText("Ubicacion actual");
                                           Toast.makeText(Main2Activity.this, "GPS Activado", Toast.LENGTH_LONG).show();
                                        }

                                   //Este codigo se activa cuando el GPS esta desactivado
                                    public void onProviderDisabled(String provider) {
                                        tvUbicacion.setText("00");
                                        tv2.setText("00");
                                      tvmes.setText("GPS desactivado");
                                       Toast.makeText(Main2Activity.this, "Por favor encienda el GPS", Toast.LENGTH_LONG).show();
                                    }
                                      };

                                    // Register the listener with the Location Manager to receive location updates
                                      int permissionCheck = ContextCompat.checkSelfPermission(Main2Activity.this,
                                             Manifest.permission.ACCESS_FINE_LOCATION);
                                      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

                                   }
                                                                          }
        );


        //solicitar permisos

       int permissionCheck = ContextCompat.checkSelfPermission(Main2Activity.this,
                Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionCheck == PackageManager.PERMISSION_DENIED) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_CONTACTS)
                    != PackageManager.PERMISSION_GRANTED) {

                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {

                    // Show an expanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                } else {

                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            1);

                    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                    // app-defined int constant. The callback method gets the
                    // result of the request.
                }


            }

        }
    }


    //hilos para ejecutar una accion cada cierto tiempo
    public void ejecutar() {
        Tiempo a = new Tiempo();
        a.execute();

    }

    public void hilo() {
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

public class Tiempo extends AsyncTask<Void, Integer, Boolean> {

    @Override
    protected Boolean doInBackground(Void... voids) {
        for (int i = 0; i < 3; i++) {
            hilo();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        DB db= new DB(getApplicationContext(),null,null,1);
        String ip = tvUbicacion.getText().toString();
        String servidor = tv2.getText().toString();
        String mensaje = db.guardargps(ip, servidor);
        Toast.makeText(getApplicationContext(),mensaje,Toast.LENGTH_SHORT).show();
        ejecutar();

    }

}

}

I have this that keeps the latitude and longitude in a database every 3 min if I go to another screen of the app is still running and then I want to close it with a button and stop saving

    
asked by Francisco Romero Murillo 27.06.2018 в 17:27
source

2 answers

1

It only occurs to me that you create a global static class that receives as an activity parameter in this case MainActivity2, then from any other class you retrieve the instance of that activity and destroy it with the method finish (), something like this:     public class info {         static public info instance = null;

    public Activity source=null;
    static public info getInstance(){
        if (instance==null){
            instance=new info();
        }
        return instance;
    }
    public info() {
        instance.source = source;
    }

    public info(Activity source) {
        instance.source = source;
    }

    public Activity getSource() {
        return source;
    }

    public void setSource(Activity source) {
        this.source = source;
    }
}

then somewhere in MainActivity2:     info.getInstance ();     info.setsource (this);

then wherever you want in any activity in your case show GPS:

info i=info.getInstance();
info.getsource().finish();

and ready! the activity you want will be finalized

    
answered by 28.06.2018 в 00:16
-1

I see that you want to end a class from another activity. Actually, what you have to do is finish the Activity when you change to a new Activity, using the finish()

method
 bdgps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(Main2Activity.this,mostrarGPS.class);
                startActivity(intent);
                ejecutar();

                finish(); //*Finaliza actual Activity.

            }
        });
  

finish () Called when your activity is complete and you need to   close.

    
answered by 27.06.2018 в 18:07