Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android

Respuesta
 
Herramientas
  #1  
Viejo 23/06/13, 21:49:15
Array

[xs_avatar]
rafaxplayer rafaxplayer no está en línea
Miembro del foro
 
Fecha de registro: jun 2013
Localización: en la barcelona media
Mensajes: 224
Modelo de smartphone: LG-E610
Tu operador: Orange
Duda con servicio

Hola compañeros tengo dudas con el tema de los servicios , resulta que he creado uno el cual usa una tarea asincronica cada intervalo de tiempo ,esta tarea retorna un numero el cual
debo imprimir en un textview de la mainactivity , cual es el mejor procedimiento para este trabajo?

codigo de mi servicio:

Código:
public class StartService extends Service {
	int i=0;
	static private int DELAY = 500;
	private Timer timer;
	
	private String USERNAME;
	SharedPreferences Settings;
	
	
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		this.USERNAME = Settings.getString("username", "");
		Log.i(getClass().getSimpleName(), "Servicio Creado");
		iniciarServicio();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		
		
		
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.finalizarServicio();
		Log.i(getClass().getSimpleName(), "Servicio Finalizado");
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public void iniciarServicio(){
	try{
		
		// Creamos el timer
        this.timer = new Timer();
        Log.i(getClass().getSimpleName(), "Iniciando servicio...");
        // Configuramos lo que tiene que hacer
	        this.timer.scheduleAtFixedRate ( new TimerTask() {
	        	
		        	public void run() {
		        	GetNewPostCount npost = new GetNewPostCount();	
					npost.execute ("http://www.amsspecialist.com/unread_count.php?id=" + Settings.getString("username", ""));
					Log.i(getClass().getSimpleName(), "Temporizando : "+ i++);
					
		        	} 
	        }, 0, DELAY);
	        Log.i(getClass().getSimpleName(), "Temporizador iniciado");
		}
		catch(Exception ex)
		{
			Log.e(getClass().getSimpleName(), ex.getMessage());
		}
		
	}
	
	public void finalizarServicio(){
		
		try{
			if(this.timer != null){
				timer.cancel();
				Log.i(getClass().getSimpleName(), "Temporizador detenido");
			}
			
		}catch(Exception e){
			Log.e(getClass().getSimpleName(), e.getMessage());
		}
		
	}
	
	public class GetNewPostCount extends AsyncTask<String, Integer, Integer> {

		protected void onPreExecute(){
			  
					
		}

		@Override
		protected Integer doInBackground(String... params) {
			HttpURLConnection urlConnection = null;
			int nPost=0;
			try {
				URL url = new URL(params[0]);
				urlConnection = (HttpURLConnection)url.openConnection();
				InputStream in = new BufferedInputStream(urlConnection.getInputStream());
				nPost = Integer.parseInt(readStream(in));
					     
				}
				catch(Exception ex)
				{
					Log.e("Post","Error en la petición de datos",ex);
				}
				finally 
				{
					urlConnection.disconnect();
				}
				return nPost;
			        
		}
				
		protected void onProgressUpdate(Integer... params){
			//Update a progress bar here, or ignore it, it's up to you
		}
				
		protected void onPostExecute(Integer np){
			
			// este deberia ser el textview a actualizar
			//TextView tx=(TextView)actividad.findViewById(R.id.npost);
			Settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
			int oldPost = Settings.getInt("newpost",0);
			
			if( oldPost < np && np > 0)
			{
				NotifyShow(1,R.drawable.ic_launcher,"Nuevos post",USERNAME + " Hay " + String.valueOf(np - oldPost) + " mensajes nuevos desde tu última visita",Settings.getBoolean("notifisound", false),Settings.getBoolean("notifivibrate", false));
				oldPost=np;
			}
			Editor edit = Settings.edit();
			edit.putInt("newpost", np);
			edit.commit();
			//tx.setText(String.valueOf(np));
			this.cancel(true);
		}

		public String readStream(InputStream in) throws Exception{
			String nPost="0";
			BufferedReader r = new BufferedReader(new InputStreamReader(in),1000);
			nPost = r.readLine();
			in.close();
			
			return nPost;
		}
		
	}
	//End Class
	public void NotifyShow(int id,int icon,String title,String msg,boolean sound,boolean bVibrate){
		Intent resultIntent = new Intent(getBaseContext(), MainActivity.class);
		Uri UriSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		long[] vibrate=new long[] {100, 250, 100, 500};
		
		if(!sound){
		UriSound=null;
			}
		if(!bVibrate){
			vibrate=null;
			}
		
		NotificationCompat.Builder mBuilder =new NotificationCompat.Builder(getApplicationContext())
			    .setSmallIcon(icon)
			    .setContentTitle(title)
			    .setContentText(msg)
			    .setVibrate(vibrate)
			    .setAutoCancel(true)
			    .setSound(UriSound);
	
		PendingIntent resultPendingIntent =PendingIntent.getActivity(getApplicationContext(),0,resultIntent ,PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		
		if(Settings.getBoolean("notifishow", true)){
			mNotifyMgr.notify(id, mBuilder.build());
		}else{
			mNotifyMgr.cancelAll();}
	}
	
	
	public boolean networkavailable(){
		boolean connection = false;
		ConnectivityManager conn = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netinfo=conn.getActiveNetworkInfo();
		//final android.net.NetworkInfo wifi= conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		//final android.net.NetworkInfo gmovile= conn.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if(netinfo!= null && netinfo.isConnectedOrConnecting()){
			
			connection=true;
		}else{connection = false;}
		return connection;
	}
}
Responder Con Cita


  #2  
Viejo 23/07/13, 16:44:22
Array

[xs_avatar]
Carlosdelachica Carlosdelachica no está en línea
Miembro del foro
 
Fecha de registro: may 2013
Mensajes: 97
Modelo de smartphone: Samsung Galaxy S III
Tu operador: Movistar
No se si tu código funciona ya que no lo he mirado a fondo, pero usando una tarea asíncrona dentro del hilo parece lo mas sensato ;)
Responder Con Cita
Respuesta

Estás aquí
Regresar   Portal | Indice > Todo sobre Android > Programación y Desarrollo para Android



Hora actual: 06:10:32 (GMT +1)



User Alert System provided by Advanced User Tagging (Lite) - vBulletin Mods & Addons Copyright © 2026 DragonByte Technologies Ltd.

Contactar por correo / Contact by mail / 邮件联系 /