Android - Servicio que se relentiza al desconectar cable usb

   
Vista:

Servicio que se relentiza al desconectar cable usb

Publicado por yordan (1 intervención) el 06/07/2016 21:48:05
Hola a todos estoy desarrollando un servicio que constantemente debe hacer llamadas cada 30 segundos aun servicio web, y obtener la respuestas de true o false, y generar notificaciones en caso de que la respuesta sea false. Logre que mi servicio no muera, es decir aunque la aplicacion se cierre el servicio sigue corriendo en background y notificando incluso con la pantalla apagada. Todo bien hasta alli, pero como es necesario que el servicio cada cierto tiempo mande a leer del web service, he implementado en el servicio un alarmanager. Todo funciona perfecto mientras tengo el cable usb conectado al telefono y verificando los logs. Cuando desconecto el cable las peticiones se relentizan, es decir que en vez de llamar al web service cada 30 segundos como esta programado, lo empieza a llamar cada 2 min, y al transcurrir el tiempo llega un momento en que ya no realiza ninguna petición. en que puedo estarme equivocando, aca va un poco de mi codigo:

servicio background

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class BackgroundService extends Service {
 
	private static final int FIRST_RUN_TIMEOUT_MILISEC = 5 * 1000;
	private static final int SERVICE_STARTER_INTERVAL_MILISEC = 1 * 1000;
	private final int REQUEST_CODE = 1;
 
	private AlarmManager serviceStarterAlarmManager = null;
	//private MyTask asyncTask = null;
 
	private NotificationPublisher alarm;
 
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
 
	@Override
	public void onCreate() {
		super.onCreate();
 
		alarm = new NotificationPublisher();
 
		// Start of timeout-autostarter for our service (watchdog)
		startServiceStarter();
 
		// Start performing service task
		alarm.SetAlarm(getApplicationContext(),20,utils.getAddress(getApplicationContext()));
 
		Toast.makeText(this, "Service Started!", Toast.LENGTH_LONG).show();
	}
 
	private void StopPerformingServiceTask() {
		alarm.CancelAlarm(getApplicationContext());
	}
 
	@Override
	public void onDestroy() {
		StopPerformingServiceTask();
	}
 
	// We should to register our service in AlarmManager service
	// for performing periodical starting of our service by the system
	private void startServiceStarter() {
		Intent intent = new Intent(this, ServiceStarter.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, this.REQUEST_CODE, intent, 0);
 
		if (pendingIntent == null) {
			Toast.makeText(this, "Some problems with creating of PendingIntent", Toast.LENGTH_LONG).show();
		} else {
			if (serviceStarterAlarmManager == null) {
				serviceStarterAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
				serviceStarterAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
						SystemClock.elapsedRealtime() + FIRST_RUN_TIMEOUT_MILISEC,
						SERVICE_STARTER_INTERVAL_MILISEC, pendingIntent);
			}
		}
	}
}


BroadcastReceiver que me posibilita inicializar nuevamente el servicio si es cerrado...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ServiceStarter extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
 
		Context cont = utils.GetExternalContext(context, "technology.wardware.plc");
		String state = utils.getSharedPreferences(cont, "service_state");
		if(state.equals("detenido"))
			return;
		else if(!utils.isMyServiceRunning(BackgroundService.class, context)){
			Intent serviceLauncher = new Intent(context, BackgroundService.class);
			context.startService(serviceLauncher);
		}
	}
}

Clase encargada de hacer las peticiones al servidor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class NotificationPublisher extends BroadcastReceiver {
 
	public void onReceive(Context context, Intent intent) {
		//Log.e("YORDAN", "Llamando");
		try{
			Context cont = utils.GetExternalContext(context, "technology.wardware.plc");
 
			if(!utils.checkWifi(context,cont)){
				if(utils.existVar("MAIN_ACTIVITY")){
					Context contexto = (Context)utils.getVar("MAIN_ACTIVITY");
					((MainActivity)contexto).dopaint("Error","Wifi desconectada");
				}
				return;
			}
 
			Toast.makeText(context, "Llamando", Toast.LENGTH_LONG).show();
			LongOperation a =new LongOperation(context,"SERVER","2","4","8032","1","0");
			a.execute(utils.getAddress(cont));			//utils.getVar("address").toString()	
		}
		catch(Exception e){
			Log.e("YORDAN", "Error");
		}
	}
 
	public void onDestroy() {
		Log.i("yordan","se acaba de destruir");
	}
 
	public void CancelAlarm(Context context)
	{
		Intent intent = new Intent(context, NotificationPublisher.class);
		PendingIntent sender = PendingIntent.getBroadcast(context, 111, intent, 0);
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
	}
 
	public void SetAlarm(Context context,int time, String _address)
	{
		utils.setVar("myaddress", _address);
		AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, NotificationPublisher.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 111, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * time , pi);
	}
 
}

tarea asincrona que realiza la peticion al servidor y obtiene la respuesta

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
public class LongOperation  extends AsyncTask<String, Void, Void> {
 
	// Required initialization
 
	Context contexto;
 
	private String Content;
	private String modbus_address = null;
	private String function_code = null;
	private String address_reading = null;
	private String number_registers = null;
	private String register_values = null;
	private String target = null;
	private String Error = null;
	private String data;
 
	//TextView uiUpdate;
 
 
	public LongOperation(Context context,String _target, String m_address, String f_code, String a_reading, String n_registers, String r_values){
 
		this.contexto = context;
		this.modbus_address = m_address;
		this.function_code = f_code;
		this.address_reading = a_reading;
		this.number_registers = n_registers;
		this.register_values = r_values;
		this.target = _target;
		Log.e("YORDAN", "Constructor");
	}
 
	protected void onPreExecute() {
		try{
			data ="&" + URLEncoder.encode("imei", "UTF-8") + "=" + utils.getIMEI(contexto) +
					"&" + URLEncoder.encode("target", "UTF-8") + "=" + this.target +
					"&" + URLEncoder.encode("modbus_address", "UTF-8") + "=" + this.modbus_address +
					"&" + URLEncoder.encode("function_code", "UTF-8") + "=" + this.function_code +
					"&" + URLEncoder.encode("address_reading", "UTF-8") + "=" + this.address_reading +
					"&" + URLEncoder.encode("number_registers", "UTF-8") + "=" + this.number_registers +
					"&" + URLEncoder.encode("register_values", "UTF-8") + "=" + this.register_values;
 
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Log.e("YORDAN", "onPreExecute");
	}
 
 
	// Call after onPreExecute method
	protected Void doInBackground(String... urls) {
		Log.e("YORDAN", "doInBackground");
		/************ Make Post Call To Web Server ***********/
		BufferedReader reader=null;
 
		// Send data
		try
		{
 
			// Defined URL  where to send data
			URL url = new URL(urls[0]);
 
			// Send POST data request
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
 
			// Get the server response
 
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String line = null;
 
			// Read Server Response
			while((line = reader.readLine()) != null){
				sb.append(line);
			}
 
			// Append Server Response To Content String
			Content = sb.toString();
		}
		catch(SocketTimeoutException ex){
			Error = ex.getMessage();
		}
		catch(Exception ex){
			Error = ex.getMessage();
		}
		finally{
			try{
				reader.close();
			}
			catch(Exception ex) {}
		}
 
		/*****************************************************/
		return null;
	}
 
	protected void onPostExecute(Void unused) {
		Log.e("YORDAN", "onPostExecute");
		Context maincont = utils.GetExternalContext(contexto, "technology.wardware.plc");
		ArrayList<String> response = null;
		if(Error == null){
			response = utils.decodeJson(Content);
			utils.saveSharedPreferences(maincont, "key", response.get(0));
			utils.saveSharedPreferences(maincont, "value", response.get(1));
			utils.checkNotification(response, maincont, this.contexto);
		}
		else{
			response = new ArrayList<String>();
			response.add("ERROR");
			response.add("Error de conexión");
			utils.saveSharedPreferences(maincont, "key", response.get(0));
			utils.saveSharedPreferences(maincont, "value", response.get(1));
			utils.checkNotification(response, maincont, this.contexto);
		}
		if(utils.existVar("MAIN_ACTIVITY")){
			Context contexto = (Context)utils.getVar("MAIN_ACTIVITY");
			if(Error != null)
				Toast.makeText(maincont, Error, Toast.LENGTH_LONG).show();
			((MainActivity)contexto).dopaint(response.get(0), response.get(1));
		}
		this.cancel(true);
	}
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder