I have a service that connects to a database every 10 seconds to verify the existence of certain data, if it exists it sends a notification to the user. everything works correctly. But when I close the app, the service restarts and returns to show the last notification, (showing twice the last notification). To simplify the matter, I decided to modify the service so that it shows me a count, which is displayed by a TOAST. Then I execute the APP, the count starts and for example I close the application when the count goes to 5, and it is restarted and starts again from scratch.
In short, every time the APP is closed, my service is restarted.
public class MiServicio extends Service {
NotificationManager notificationManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
super.onCreate();
}
//////////////////////////////////////////////////////////
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final long vibra[] ={0,100,100};
////////////////////////////////////////////////////
TimerTask task3 = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
try{
//tualiza_mis_preferencias(); // las lee desde base de datos
//s_preferencias(); // las lee desde sharedpreferences para la app
Toast.makeText(getApplicationContext(), String.valueOf(infinito),Toast.LENGTH_SHORT).show();
infinito++;
//Log.i(TAG,infinito);
}catch (EmptyStackException e){
Log.e("error", e.getMessage());
}
}
});
}
};
/*
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
final SharedPreferences preferencias = getSharedPreferences("AutomataSP", Context.MODE_PRIVATE);
final String cadena = "";
final String mialerta_leidaSP = preferencias.getString("miAlerta_leida", "no hay dato");
handler.post(new Runnable()
{
public void run() {
url2 = "http://190.xxx.xxx.xxx:80/regresa_alarmas.php";
parametros2 = "?eid_comu=" + comu + "&eid_alerta=" + mialerta_leidaSP;
//Log.i(TAG,parametros2);
OkHttpClient client = new OkHttpClient();
request = new Request.Builder().url(url2+parametros2).build();
/// ejecutamos el request
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
SharedPreferences.Editor editor = preferencias.edit();
alert = alert + 1;
respuesta2 = response.body().string(); // tomo la respuesta del webservice JSON y la transformo a string
//Log.i(TAG,respuesta2);
//Toast.makeText(getApplicationContext(),response.body().string(), Toast.LENGTH_LONG).show();
if (respuesta2.contains("nomensajes")){
Log.i(TAG,"Sin alertas nuevas");
//Toast.makeText(getApplicationContext(), "sin notificaciones",Toast.LENGTH_SHORT).show();
}else{
try{
JSONArray jsonArray = new JSONArray(respuesta2);
malerta_leida = jsonArray.getJSONObject(0).getString("id_alerta");
mmnombre = jsonArray.getJSONObject(0).getString("nombre");
mtipo_alerta = jsonArray.getJSONObject(0).getString("tipo_alerta");
mmapellido = jsonArray.getJSONObject(0).getString("apellidos");
Log.i(TAG, malerta_leida);
if (mtipo_alerta.contains("1")){
cadena_alerta = "Robo";
}
if (mtipo_alerta.contains("2")){
cadena_alerta = "Panico";
}
if (mtipo_alerta.contains("3")){
cadena_alerta = "Incendio";
}
if (mtipo_alerta.contains("4")){
cadena_alerta = "Emergencia";
}
}catch (JSONException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
//Log.d(TAG, "onResponse: ");
// si la alerta leida es distinta a la almacenada anteriormente
NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.raw.ic_noti_32)
.setContentTitle("Sistema de alertas - Alarmas Comunitarias ")
.setContentText(mmnombre + " " + mmapellido + " - " + cadena_alerta)
.setPriority(Notification.PRIORITY_MAX)
.setVibrate(vibra)
.setLights(Color.CYAN, 1, 0)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setWhen(System.currentTimeMillis());
/*
//activity que se lanza al hacer click en la notificacion
Intent resultIntent = new Intent(getApplicationContext(), ePrincipal.class);
//
PendingIntent resultPendingIntent = PendingIntent.getActivity(getBaseContext(),0,resultIntent,0);
//establece el comportamientl del click de la notificacion
builder.setContentIntent(resultPendingIntent);
notificationManager.notify(ID_NOTI,builder.build());
}
editor.putString("miAlerta_leida", malerta_leida);
editor.commit();
//Log.i(TAG,"alerta leida y registrada");
//////fin noti builder
}///fin Onresponse
});
}///fin run
}
);
}
};
*/
//timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 10000 ms
timer.schedule(task3,0,3000);
return START_STICKY;
}//TERMINA onSTARTCOMMAND
///////////////////////////////////////////////////////////////
@Override
public void onDestroy() {
super.onDestroy();
}
////////////////////////////////////////////////////////////
}