I am developing a tracking application with the class LocationManager
accessing the latitudes and longitudes of the gps and uploading to the server with jsonparser
every minute by means of a Handler
.
I want to make a local database with SQlite
for when there is no internet connection. My question is which tool to synchronize (Service, Asyntask, broadcast) with the web server and how to make the local database not so heavy (delete records already uploaded).
Use AndroidStudio, api 23 .
I enclose my MainActivity.java
:
public class MainActivity extends Activity {
TextView mensaje1;
TextView mensaje2;
TextView hora;
String id;
TextView uno;
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
String REGISTER_URL = "http://www.syan.cl/musicminguzzi.cl/gps/gps.php";
String TAG_SUCCESS = "success";
String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mensaje1 = (TextView) findViewById(R.id.mensaje_id);
mensaje2 = (TextView) findViewById(R.id.mensaje_id2);
uno = (TextView) findViewById(R.id.ide);
hora = (TextView) findViewById(R.id.hour);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
id = (String) extras.get("user");
uno.setText(id);
}
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
new CreateUser().execute();
handler.postDelayed(this, 60000); //now is every 2 minutes
}
}, 60000); //Every 120000 ms (2 minutes)
/* Uso de la clase LocationManager para obtener la localizacion del GPS */
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Localizacion Local = new Localizacion();
Local.setMainActivity(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
(LocationListener) Local);
mensaje1.setText("Localizacion agregada");
mensaje2.setText("");
}
public void setLocation(Location loc) {
//Obtener la direccion de la calle a partir de la latitud y la longitud
}
/* Aqui empieza la Clase Localizacion */
public class Localizacion implements LocationListener {
MainActivity mainActivity;
public MainActivity getMainActivity() {
return mainActivity;
}
public void setMainActivity(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
@Override
public void onLocationChanged(Location loc) {
// Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
// debido a la deteccion de un cambio de ubicacion
loc.getLatitude();
loc.getLongitude();
Double Text = loc.getLatitude();
Double Text1 = loc.getLongitude();
mensaje2.setText(Text1.toString());
mensaje1.setText(Text.toString());
this.mainActivity.setLocation(loc);
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String dateString = sdf.format(date);
hora.setText(dateString);
}
@Override
public void onProviderDisabled(String provider) {
// Este metodo se ejecuta cuando el GPS es desactivado
mensaje1.setText("GPS Desactivado");
}
@Override
public void onProviderEnabled(String provider) {
// Este metodo se ejecuta cuando el GPS es activado
mensaje1.setText("GPS Activado");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// Este metodo se ejecuta cada vez que se detecta un cambio en el
// status del proveedor de localizacion (GPS)
// Los diferentes Status son:
// OUT_OF_SERVICE -> Si el proveedor esta fuera de servicio
// TEMPORARILY_UNAVAILABLE -> Temporalmente no disponible pero se
// espera que este disponible en breve
// AVAILABLE -> Disponible
// admin data base result
}
}
class CreateUser extends AsyncTask<String, String, String> {
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String dateString = sdf.format(date);
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Subiendo Coordenadas...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = mensaje2.getText().toString();
String password = mensaje1.getText().toString();
String ide = uno.getText().toString();
String hora = dateString;
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("ide", ide));
params.add(new BasicNameValuePair("hora", hora));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}