I would like to know how I can maintain a service connected to mysql from an android service and extract information. So far I make an HttpURLConnection towards a php file that makes the process, but only the service is executed only once, after closing the application the service is not running, it appears running but it does not do anything.
public String verificarDatosNuevos(String us){
String parametros = "user="+us;
HttpURLConnection conexion = null;
String result ="";
try{
URL url = new URL(urlb+"nuevosDatos.php");
conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestMethod("POST");
conexion.setDoOutput(true);
Scanner inStream = new Scanner(conexion.getInputStream());
while(inStream.hasNextLine()){
result += (inStream.nextLine());
}
}catch (Exception e){e.printStackTrace();}
return result.toString();
}
public int cantMsg (String user){
int resp = 0;
try {
JSONArray json = new JSONArray(verificarDatosNuevos(user));
if(json.length() > 0){
resp = json.length();
}
} catch (JSONException e) {
e.printStackTrace();
}
return resp;
}
I use these two functions to extract the data and in the service I do the following:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
verificarNuevo();
onDestroy();
return START_STICKY;
}
public void verificarNuevo(){
Thread tr = new Thread(){
@Override
public void run() {
int r = db.cantMsg(userFy);
if(r > 0){
Toast.makeText(getApplicationContext(),"Tienes "+r+" mensaje(s)...",Toast.LENGTH_SHORT).show();
}
}
};
tr.start();
}
In the php file I return a json array to know how many messages have not been seen yet:
<?php
$usuario = $_POST['user'];
$cnx = new PDO("mysql:host=localhost;dbname=bddayton","root","root");
$res = $cnx->query("select * from newmsg where user = '".$usuario."' and condicion_visto = 0 ");
$datos = array();
foreach ($res as $row){
$datos[]=$row;
}
echo json_encode($datos);
?>
What I do not achieve is that he shows me the Toast, he simply destroys himself and starts infinitely without doing anything.
What I want is that when there is a new record (the table has a condition field where 0 is not seen and any other data is seen), the application alerts me to that record. Help please !!.