Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Saturday, September 13, 2014

Sensorial android app

 
Sensorial on Google Play

Ow, it's been like forever since i write my last post (too bad for me right).
Since it has been too long, don't think that i was doing nothing (actually play PS4 too some time of my life... :P).

Those last months were a blast! I learn java/android programming and thought: "Why not release some app on the Play Store?". So that what i did! This is my first blog post explain some of the core functions i use in my app, so it can help others.

So, let's start with an idea, you must have an idea to build an app, even if that idea has already been implemented for someone else right? The idea behind Sensorial is very simple: Give you data about sensors that we can find in our daily life.


You must thought, "IoT"[1] right? That's one path... why not. But since we are on the IT space, i learn that baby steps is a great thing, so im starting small. For now the app will give you some sensors information available using the hardware you have on your device and some collected over the internet using your geolocation to get the better value for you in that point of time and space.

So that's what is implemented right now, but the original idea was way more simple, my father just wanted to replace he's old app that give him values of speed, distance and altitude. Very simple right? So i implement some other features that in the end he found very usefull.

But enough of history, lets talk "techie".

In this first post im just listing the libraries used to build Sensorial.
The first one was ButterKnife[2], and what a great lib uhm? It takes out all the trouble of writing over and over the famous Android findViewById[3] method of the Activity.
ButterKnife was my choice because it looks very simple to use (but in the end Eclipse Bundle impose some difficult) and have some good documentation. If you don't know the library or know but never used give that a change, it's good.

Ok, said one lib right, just to be clear im using 7 libraries! You are think, "That's too much! It must be a performance killer!". Well... it's not that much actually, the performance of the app is good, and usage is not bad, some of those libraries have more performance that the original android code! You could try for yourself if want to, anyway, all those libraries add some high level interface on the programming make it easy to do some tasks.
The others libraries im using are the following:

  •  GSON[4]: Great lib to work with json format, since some of the internet services that im using to get sensor info return in json, it was a must have. If you look in the internet the performance is much better that the default android parser. Also you could check jackson, it claims to have better performance that GSON!
  • Http-Request[5]: The android code to make a http request is disgusting, this lib is great, it reminds me python request (which i find awesome!).
  • Joda Time[6]: if you work with date on Java you suffer whole life until Joda was created... :D it is excellent when it comes to parser and transform string into date objects and vice versa.
  • SugarOrm[7]: Awesome, i was checking for orm in android and found this precious lib... what it makes speciall? The simplicity... if you are looking for "Simple is better than Complex", use this and be happy. A plus is that the lib is active on github!!!!
  • ListViewAnimations[8]: This was a life saver for me... android has its ListView component, and im using to make the list of sensors in the main activity. But how one can implement some list special operations? Like Drag and Drop, Swipe to dismiss and stuff like that? Well, enter ListViewAnimations... this lib has all!! And some more! If you are using ListView, check this out and be a little more happy when coding for your users and improve their experiences!
All those libraries will help you a little more to build a great and easy to use app, you should check Sensorial to get a little idea what you could build.
Sensorial is a paid app, but im thinking in release a free version also, the problem in release a free version is that one of the service im using is a paid one, and if the app has too much requests to that service, the app could be down for a few hours...

Anyway, in the next posts i will explain some problems and solutions found to build Sensorial, and perhaps my next android app. 
Sensorial is far from finish its development life cycle, im have much more ideas to implement on it to leave there on the Play Store without updates!


Cheers!!!

[1]: Internet of Thins (IoT)
[2]: ButterKnife
[3]: findViewById
[4]: GSON
[5]: Http-Request
[6]: Joda Time
[7]: SugarORM
[8]: ListViewAnimations
[9]: Sensorial on Google Play

Monday, September 17, 2012

Melhorando a performance de sistemas web.


Melhorando a performance de sistemas web.

Com a grande migração de muitos sistemas para a internet após o ano 2000, muitas técnicas foram propostas para a melhoria no processo de carregamento de sistemas web. Essas melhorias visam, claro, uma melhor performance de acesso para os usuários dos sistemas.
Nesse post irei tratar de algumas técnicas que são principais, de fácil identificação e que podem ser implantadas rapidamente. Um detalhe importante é que todas as informações colocadas aqui são as mais simples possíveis, por conseguinte se forem implantadas em ambientes de produção pode vir a ser necessário algum tipo de análise de segurança (não que todas irão precisar claro!). Por onde começar?


Um start interessante é instalar estas duas ferramentas, as quais irão proporcionar uma visão de como nossa página é carregada e sugerir melhorias a serem feitas:


Após isso, comece realmente a melhorar sua performance!


Minify your files!!!

A primeira técnica e que considero a mais simples de todas, é minificar e agrupar seus arquivos estáticos. Mas o que são arquivos estáticos? Eles são como páginas estáticas (Static Web Pages[1]), ou seja seu conteúdo não muda de acordo com o acesso. Os exemplos mais comuns são arquivos javascript, css e imagens!
Normalmente esses arquivos não são tratados para contemplar esse tipo de situação, e isso pode vir a se tornar um problema de payload[2] conforme vamos adicionando mais e mais bibliotecas, classes e imagens sem otimiza-los.
Algumas soluções para esse problema se resumem em minimizar manualmente os arquivos usando ferramentas como (estes são os top 4 na minha busca do Google) e posteriormente agrupando todos em 1 (um) só arquivo:

Javascript


CSS:


Dentre os outros milhões de ferramentas online, eles podem nos ajudar a melhorar a performance de nossa aplicação no que concerne no carregamento da bibliotecas e códigos que utilizamos, mas não são nem um pouco produtivos, pois devemos fazer manualmente essa cópia e compressão e ainda precisamos manter 2 (dois) arquivos (o original e o minificado).
Como melhorar isso? E sermos mais produtivos?

Podemos utilizar ferramentas automáticas que façam isso, alternativas é o que não faltam também. Particularmente conheço muito poucas ferramentas desse tipo em PHP, mas uma me chamou ultimamente:


A idéia aqui é a mesma, otimizar e automatizar a minificação dos arquivos estáticos, lembrando que ele não serve para imagens, mas sim para javascript e css.
Em outras linguagens temos alternativas ja incorporadas nos frameworks (que não é necessariamente o caso do Zend Framework[3], mas o minify pode ser usado em conjunto[4]), por exemplo em Django[5] temos um app chamado django-compressor[6] que faz a minificação e agrupamento dos arquivos automaticamente, sendo necessário apenas ativar o package.

Para imagens, podemos utilizar de alguns programas para compressão, alguns exemplos bem interessantes, sugeridos pelo Google são [7]:




GZIP[8] on the fly!

Outra técnica bastante utilizada em sistema/sites da web é de comprimir seus arquivos, aqui vale a máxima de que 10% de redução pode diminuir em muito o payload de seu usuário!
Vou dar um exemplo bem simples e surpreendente, eu utilizo a biblioteca ExtJs[9] que tem um arquivo .js de 1Mb! Isso mesmo, e é 1Mb ja minificado! Usando gzip diminuímos esse payload para 400Kb, ainda é muito? Pode ser, mais é um ganho de 50%. Ou seja 50% menos de carga que um usuário terá de carregar em cada acesso ao sistema.
Devo dizer que o gzip não serve apenas para arquivos estáticos, podemos comprimir todos os arquivos e nossas respostas AJAX[10] também, ou seja, todo nosso site será mais leve para o usuário carregar. O lado ruim? nosso servidor deve aguentar a carga para comprimir todos os dados antes de enviar de volta para nosso usuário.

Para habilitar o gzip em nosso servidor apache devemos apenas habilitar o módulo mod_deflate! Simples não? Claro que tem-se muitas configurações, mas de modo simplista devemos apenas executar em shell:

$ a2enmod deflate

Fazendo isso estamos prontos, todo o conteúdo do nosso site será compresso para cada requisição realizada. Outros servidores podem possuir outras configurações.
Em Django podemos habilitar a compressão via gzip sem precisar interagir com o servidor, para isso basta habilitarmos o middleware GZipMiddleware[11], fazendo com que nosso sistema use script’s em python para a compressão!




Finalizando por aqui...
Seus usuários agradecem, mesmo não sabendo disso... :D!

Estas são duas regras muito simples que podemos habilitar em nossos sistemas, fazendo com que a performance de carregamento seja melhorada.
No próximo post vou tratar sobre o varnish cache e cache headers no apache!








falowaer