SlideShare ist ein Scribd-Unternehmen logo
1 von 127
Optimisation and Performance 
Rakesh Kumar Jha 
M. Tech, MBA 
Delivery Manager
Optimisation and Performance 
 What is Optimisation and Performance 
 Memory Efficiently 
 Networking 
 Location 
 Optimizing Graphics and UI 
Optimizing Layouts 
 Layout Tools 
 Benchmarking And Profiling 
 Tracing 
 Logging 
 Q & A
What is Optimization 
• Finding an alternative with the most cost 
effective or highest achievable performance 
under the given constraints, by maximizing 
desired factors and minimizing undesired 
ones.
What is Optimization 
• In comparison, maximization means trying to 
attain the highest or maximum result or 
outcome without regard to cost or expense. 
• Practice of optimization is restricted by the 
lack of full information, and the lack of time to 
evaluate what information is available.
What is Optimization 
• In computer simulation (modeling) of business 
problems, optimization is achieved usually by 
using linear programming techniques of 
operations research.
Optimization in Android 
• Android devices having limited 
– Memory 
• Clean RAM and 
• Dirty RAM. 
– Processor
Clean RAM 
• Unlike PCs, Android does not offer swap space 
for memory, however it does use paging and 
memory-mapping. 
• Any files or resources which are present on 
the disk, such as code, are kept in mmap’ed 
pages. 
• Android knows these pages can be recovered 
from the disk, so they can be paged out if the 
system needs memory somewhere else
Dirty RAM 
• Dirty RAM is the memory that cannot be 
paged out. 
• It can be expensive, especially when running 
in a background process. 
• Most of the memory in a running application 
is dirty memory and this is the one you should 
watch out for.
Dirty RAM 
• In order to optimize the memory usage, 
Android tries to share some framework 
resources or common classes in memory 
across processes.
Dirty RAM 
• whenever a device boots up, a process called 
zygote loads the common framework code.
Dirty RAM 
• Every new application process is then forked 
from the zygote process so it is able to access 
all the shared RAM pages loaded by it.
Dirty RAM 
• While investigating an application’s RAM 
usage, it is important to keep shared memory 
usage in mind since we should only be looking 
at the private dirty memory that is being used 
by our application. 
• This is reflected by USS (unique set size) and 
PSS (proportional set size) in ‘meminfo.’
Memory Optimization, Best Practices 
For Android 
• So what can you do to keep your system from 
running out of memory?
Memory Optimization, Best Practices 
For Android 
• So what can you do to keep your system from 
running out of memory? 
• I’ll discuss about 30 points, we have to keep in 
mind while developing mobile/handheld 
applications.
Memory Optimization, Best Practices 
For Android 
1. ScrollViews and ListViews are an easy win. 
2. Use the folder structures 
3. 160dp = 1 inch. 320 dp = 2 inches. dp == dip 
4. Resource rules of thumb: 
5. you don’t have to tailor all your layout files, 
you could instead tailor the dimens.xml files. 
6. Let whitespace scale more than graphics. Let 
graphics scale more than buttons.
Memory Optimization, Best Practices 
For Android 
7. Use the GraphicalLayout tool for fast previews 
GraphicalLayout is the WYSIWG editor for XML 
files
Memory Optimization, Best Practices 
For Android 
8. Don’t scale all your images 
The conceptually simplest way of doing this is to 
produce a whole host of images and pop them 
into a matching plethora of drawable folders
Memory Optimization, Best Practices 
For Android 
9. Avoid bitmaps (jpg, png). 
Try to avoid .jpg or png images, this images are 
easy to implement, but you can save lot of space 
and achieve much sharper result by 9-patch 
image, even better to use xml
Memory Optimization, Best Practices 
For Android 
10.Use XML Drawables. 
Wherever you can use XML drawables instead of 
bitmaps. XML drawables won’t let you do 
everything, but improve your performance.
Memory Optimization, Best Practices 
For Android 
11. Use XML Drawables. 
Wherever you can use XML drawables instead of bitmaps. XML drawables won’t let you do 
everything, but improve your performance. 
<shape 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle" > 
<corners 
android:bottomRightRadius="14dp" 
android:bottomLeftRadius="14dp" 
android:topLeftRadius="14dp" 
android:topRightRadius="14dp"/> 
<gradient 
android:startColor="@color/off_white" 
android:endColor="@color/pale_yellow" 
android:angle="270" 
android:type="linear"/> 
<stroke 
android:width="4dp" 
android:color="@color/osm_darkerblue"/> 
</shape>
Memory Optimization, Best Practices 
For Android 
12. Why use 9-patch (when you can use XML 
drawables)
Memory Optimization, Best Practices 
For Android 
13. Create custom views by overriding onDraw() 
There are some things XML just isn’t so great at, we 
draw a lot of graphs in OpenSignal and 
WeatherSignal and there are libraries for this, but 
we coded our graphs custom. 
It’s kind of fun. 
You might never need to do it, but to make graphics 
that are highly dynamic and custom it is often the 
only way to go.
Memory Optimization, Best Practices 
For Android 
14. Use SVG where you can’t use XML 
Sometimes overriding onDraw() and 
painstakingly coding up all the lines and arcs you 
need to draw your custom view is overkill. 
After all, there is a language for vector graphics, 
it’s called … Scalable Vector Graphics
Memory Optimization, Best Practices 
For Android 
15. GZip your SVG files. 
Makes them smaller and they parse quicker.
Memory Optimization, Best Practices 
For Android 
16. Customise your UI widgets. 
To make sure your app looks the same on all 
devices, you’ll need to customise everything, it’s 
not as hard as you might think and in doing so 
you’ll get a lot more control over how your app 
looks.
Memory Optimization, Best Practices 
For Android 
17. Selectors are super for building buttons. 
what do you do to create a button that changes 
when clicked? Easy: define the background to be 
an XML file as below, which will receive the 
button state and serve up the appropriate 
drawable.
Memory Optimization, Best Practices 
For Android 
17. Selectors are super for building buttons. 
<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_pressed="true" 
android:drawable="@drawable/btn_bg_selected" /> 
<item android:state_focused="true" 
android:drawable="@drawable/btn_bg" /> 
<item android:drawable="@drawable/btn_bg" /> <!-- default --> 
</selector>
Memory Optimization, Best Practices 
For Android 
18. The ActionBar and many animation styles 
didn’t exist pre Honeycomb, use 
ActionBarSherlock and NineOldAndroids 
instead.
Targeting speed
Memory Optimization, Best Practices 
For Android 
19. Test on slow phones. 
You’ll not only see any problems with slowness, 
but they’ll drive you nuts, no-one likes a slow 
app.
Memory Optimization, Best Practices 
For Android 
20. Keep your XML layout hierarchy flat. 
More layers means the system does a lot more 
work parsing your code and it can take views 
longer to deploy.
Memory Optimization, Best Practices 
For Android 
21.Use Android Lint. 
Right click on project folder in Eclipse>Android 
Tools>Run Lint. This can catch a host of things 
that can improve speed, or just make your code 
cleaner.
Memory Optimization, Best Practices 
For Android 
22. Android Lint can get it wrong. 
It can suggest things that will break your code in 
subtle ways, so do understand what it suggests 
before you make changes
Memory Optimization, Best Practices 
For Android 
23. Using <merge> can help flatten your view 
hierarchy. 
Simple way of getting rid of superfluous layers. 
http://android-developers. 
blogspot.com.ar/2009/03/android-layout- 
tricks-3-optimize-by.html
Memory Optimization, Best Practices 
For Android 
24. Use HierarchyViewer to see your layout 
hierarchy. 
This is a brilliant tool which shows just how 
many layers of layouts you have and which of 
them are slowing things down.
Memory Optimization, Best Practices 
For Android 
25. Use RelativeLayout whenever you can.
Memory Optimization, Best Practices 
For Android 
26. Use external profilers as well as DDMS
Memory Optimization, Best Practices 
For Android 
27. Use AsyncTasks
Targeting low file size
Memory Optimization, Best Practices 
For Android 
28. Some Android devices have a 100mb limit
Memory Optimization, Best Practices 
For Android 
29. Use XML resources (last time I recommend 
this, I promise)
Memory Optimization, Best Practices 
For Android 
30. When you must use PNGs always optimize 
(with PNGCrush or ImageOptim)
Targeting bugs
Memory Optimization, Best Practices 
For Android 
31. On the Android developer console check for 
any bugs that have been sent automatically.
Memory Optimization, Best Practices 
For Android 
32. ProGuard is turned on by default now. 
Proguard is awesome (speeds up your app and 
reduces filesize) but it can make StackTraces 
very obscure.
Memory Optimization, Best Practices 
For Android 
33. Adjust ProGuard config to show line 
numbers in StackTraces. 
Make sure your proguard.cfg has a line: 
-keepattributes SourceFile,LineNumberTable
Networking
Background Data and Data Transfer
ConnectivityManager 
• Class that answers queries about the state of 
network connectivity. 
• It also notifies applications when network 
connectivity changes. Get an instance of this 
class by 
calling Context.getSystemService(Context.CON 
NECTIVITY_SERVICE).
ConnectivityManager 
• The primary responsibilities of this class are to: 
• Monitor network connections (Wi-Fi, GPRS, 
UMTS, etc.) 
• Send broadcast intents when network 
connectivity changes 
• Attempt to "fail over" to another network when 
connectivity to a network is lost 
• Provide an API that allows applications to query 
the coarse-grained or fine-grained state of the 
available networks
ConnectivityManager 
• https://developer.android.com/training/efficie 
nt-downloads/efficient-network-access.html
Checking Network Connection
Checking Network Connection 
• Android lets your application connect to the 
internet or any other local network and allows 
you to perform network operations.
Checking Network Connection 
• A device can have various types of network 
connections. 
• We will focuses on using either a Wi-Fi or a 
mobile network connection.
Checking Network Connection 
• Before you perform any netowrk operations, 
you must first check that are you connected to 
that network or internet e.t.c. 
• For this android 
provides ConnectivityManager class. 
• You need to instantiate an object of this class 
by calling getSystemService() method. Its 
syntax is given below:
Checking Network Connection 
ConnectivityManager check = (ConnectivityManager) 
this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
Checking Network Connection 
Once you instantiate the object of ConnectivityManager class, 
you can use getAllNetworkInfo method to get the information of 
all the networks. 
This method returns an array of NetworkInfo. So you have to 
recieve it like this.
Checking Network Connection 
NetworkInfo[] info = check.getAllNetworkInfo();
Checking Network Connection 
The last thing you need to do is to check Connected State of the 
network. Its syntax is given below: 
for (int i = 0; i<info.length; i++){ 
if (info[i].getState() == NetworkInfo.State.CONNECTED){ 
Toast.makeText(context, "Internet is connected 
Toast.LENGTH_SHORT).show(); 
} 
}
Checking Network Connection 
Apart from this connected states, there are other states 
a network can achieve. They are listed below: 
Sr.No State 
1 Connecting 
2 Disconnected 
3 Disconnecting 
4 Suspended 
5 Unknown
Performing Network Operations 
After checking that you are connected to the internet, 
you can perform any network operation. Here we are 
fetching the html of a website from a url.
Performing Network Operations 
Android provides HttpURLConnection and URL class to 
handle these operations. You need to instantiate an 
object of URL class by providing the link of website. Its 
syntax is as follows:
Performing Network Operations 
String link = "http://www.google.com"; 
URL url = new URL(link);
Performing Network Operations 
After that you need to call openConnection method of 
url class and recieve it in a HttpURLConnection object. 
After that you need to call the connect method of 
HttpURLConnection class.
Performing Network Operations 
HttpURLConnection conn = (HttpURLConnection) 
url.openConnection(); 
conn.connect();
Performing Network Operations 
And the last thing you need to do is to fetch the HTML 
from the website. For this you will use InputStream and 
BufferedReader class. Its syntax is given below: 
InputStream is = conn.getInputStream(); 
BufferedReader reader =new BufferedReader(new 
InputStreamReader(is, "UTF-8")); 
String webPage = "",data=""; 
while ((data = reader.readLine()) != null){ 
webPage += data + "n"; 
}
Performing Network Operations 
And the last thing you need to do is to fetch the HTML 
from the website. For this you will use InputStream and 
BufferedReader class. Its syntax is given below: 
InputStream is = conn.getInputStream(); 
BufferedReader reader =new BufferedReader(new 
InputStreamReader(is, "UTF-8")); 
String webPage = "",data=""; 
while ((data = reader.readLine()) != null){ 
webPage += data + "n"; 
}
PHP - MYSQL
• we are going to explain, how you can integrate 
PHP and MYSQL with your android 
application. 
• This is very useful in case you have a 
webserver, and you want to access its data on 
your android application.
CREATING DATABASE 
<?php 
$con=mysqli_connect("example.com","username"," 
password"); 
$sql="CREATE DATABASE my_db"; 
if (mysqli_query($con,$sql)) 
{ 
echo "Database my_db created successfully"; 
} 
?>
CREATING TABLES 
<?php 
$con=mysqli_connect("example.com","username"," 
password","my_db"); 
$sql="CREATE TABLE table1(Username 
CHAR(30),Password CHAR(30),Role CHAR(30))"; 
if (mysqli_query($con,$sql)) 
{ 
echo "Table have been created successfully"; 
} 
?>
INSERTING VALUES IN TABLES 
<?php 
$con=mysqli_connect("example.com","username"," 
password","my_db"); 
$sql="INSERT INTO table1 (FirstName, LastName, 
Age) VALUES ('admin', 'admin','adminstrator')"; 
if (mysqli_query($con,$sql)) 
{ 
echo "Values have been inserted successfully"; 
} 
?>
PHP - GET AND POST METHODS 
<?php 
$con=mysqli_connect("example.com","username","password","database name"); 
if (mysqli_connect_errno($con)) 
{ 
echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 
$username = $_GET['username']; 
$password = $_GET['password']; 
$result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and 
Password='$password'"); 
$row = mysqli_fetch_array($result); 
$data = $row[0]; 
if($data){ 
echo $data; 
} 
mysqli_close($con); 
?>
Android - Connecting MYSQL 
• There are two ways to connect to MYSQL via 
PHP page. 
• The first one is called Get method. We will 
useHttpGet and HttpClient class to connect. 
Their syntax is given below: 
URL url = new URL(link); 
HttpClient client = new DefaultHttpClient(); 
HttpGet request = new HttpGet(); 
request.setURI(new URI(link));
Android - Connecting MYSQL 
• After that you need to call execute method of 
HttpClient class and recieve it in a 
HttpResponse object. 
• After that you need to open streams to 
recieve the data. 
HttpResponse response = client.execute(request); 
BufferedReader in = new BufferedReader 
(new InputStreamReader(response.getEntity().getContent()));
CONNECTING VIA POST METHOD 
• In the Post method , 
the URLEncoder,URLConnection class will be 
used. 
• The urlencoder will encode the information of 
the passing variables. 
• It's syntax is given below: 
URL url = new URL(link); String data = 
URLEncoder.encode("username", "UTF-8") + "=" + 
URLEncoder.encode(username, "UTF-8"); data += "&" + 
URLEncoder.encode("password", "UTF-8") + "=" + 
URLEncoder.encode(password, "UTF-8"); URLConnection conn = 
url.openConnection();
CONNECTING VIA POST METHOD 
• The last thing you need to do is to write this 
data to the link. 
• After writing , you need to open stream to 
recieve the responded data. 
OutputStreamWriter wr = new 
OutputStreamWriter(conn.getOutputStream()); 
wr.write( data ); 
BufferedReader reader = new BufferedReader(new 
InputStreamReader(conn.getInputStream()));
Type of web services 
• Web service is a system that enables 
applications to communicate with an API. 
• Web service helps to expose business logic 
through an API interface where different 
systems communicate over network.
Type of web services
Type of web services 
• Application to application communication. 
• Interoperability between disparate systems. 
• Communication over network. 
• Exposed interface is platform independent and 
internal implementation is abstracted. 
• Enables loosely coupled design. 
• Open protocol is used for establishing 
communication. 
• Web services are self contained.
Components of a Web Service 
wsdl
Type of web services 
• Web Services Description Language (WSDL) is 
used to describe a web service in an XML file. 
• It covers all the aspects of a web service like 
what is the message format, communication 
protocol, endpoint, security etc. 
• This is a standard provided by W3C 
consortium and widely accepted for web 
services description.
Type of web services 
• A wsdl xml file for a web service is generally 
expected to be published publicly so that 
parties seeking to utilize its services can 
understand the nature of service and 
consume it accordingly.
Type of web services 
• Types is an important element in WSDL. It is 
used to describe the message attributes and 
respective types. 
• XSD is the preferred format to describe the 
types. 
• Type definition can be given in a separate XSD 
file and imported in WSDL.
Type of web services 
<definitions .... > 
<types> 
<xsd:schema .... />* 
</types> 
</definitions>
UDDI
• Universal Description, Discovery and 
Integration (UDDI) is a directory service. 
• Web services can register with a UDDI and 
make themselves available through it for 
discovery.
Stub and Skeleton 
• Stub and skeleton are counterparts in a web 
service setup. Skeleton belongs to service 
provider side and stub belongs to receiver 
side. 
• At lower level stub and skeleton communicate 
with each other.
Endpoint 
• An endpoint is a particular network location 
with associated protocol which includes 
message format mapping using which we can 
access that instance of web service. 
• This is described in WSDL file. Consider this as 
a handle using which we will access the web 
service.
Binding 
• Associating an interface with a protocol and 
message format is binding. 
• It is used in endpoint definition. Binding is 
described in WSDL.
Operation 
• A single logical grouping of a meaningful 
action which comprises a request and 
response is an operation. Group of operations 
forms a web service.
SOAP 
• Simple Object Access Protocol is a XML based 
specification for web services message format 
and communication over network. That is it 
helps to describe the transport method and 
message format in a web service.
Web Service Design 
• As given in diagram a web service has logic 
and an interface. 
• Logic is the actual service provided and 
interface is used to communicate with the 
web service. Interface definition is given in 
WSDL. 
• There are two approaches in implementing a 
web service and they are bottom-up and top-down.
Bottom Up Approach 
• Bottom up approach is where we first define 
the logic of a web service and then using that 
we will build the interface. 
• Service code is written first and then the 
WSDL is created using the service code. 
• There are tools available to generate the wsdl 
file automatically based on it.
Top Down Approach 
• Top down is the reverse of bottom up 
approach. 
• First the service definition is written up. WSDL 
is created first. 
• The complete service definition, message 
format, transport protocol, security and 
everything is described in WSDL.
REST web services 
• Top down is the reverse of bottom up 
approach. 
• First the service definition is written up. WSDL 
is created first. 
• The complete service definition, message 
format, transport protocol, security and 
everything is described in WSDL.
How to create RESTFul webservice in 
Java? 
• RESTful webservice in Java and in the next 
post will be discussing how to consume 
RESTful webservice we are about to create in 
Android application.
How to create RESTFul webservice in 
Java?
How to create RESTFul webservice in 
Java? 
• RESTful webservice in Java and in the next 
post will be discussing how to consume 
RESTful webservice we are about to create in 
Android application.
Jersey – RESTfulWebservice 
• use Jersey framework to design RESTful 
webservice. 
Reference: http://www.vogella.com/tutorials/RE 
ST/article.html#installation_jersey
Jersey – RESTfulWebservice 
• Goto https://jersey.java.net/download.html a 
nd download Jersey 1.18 ZIP bundle as shown 
below:
Jersey – RESTfulWebservice 
• Unzip the bundle, you can see list of Jars 
under lib folder as shown below:
Jersey – RESTfulWebservice 
• Create Dynamic web project in Eclipse as 
shown below:Choose File>>New>>Dynamic 
Web Project
Jersey – RESTfulWebservice 
• Enter project name as ‘useraccount’ and Click 
Finish
Jersey – RESTfulWebservice 
• Add unzipped Jersey library JARs to WEB-INF/ 
lib folder
Jersey – RESTfulWebservice 
• Register Jersey as Servlet dispatcher by adding below code into web.xml 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
id="WebApp_ID" version="2.5"> 
<display-name>useraccount</display-name> 
<servlet> 
<servlet-name>Jersey REST Service</servlet-name> 
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> 
<init-param> 
<param-name>com.sun.jersey.config.property.packages</param-name> 
<param-value>com.prgguru.jersey</param-value> 
</init-param> 
<load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
<servlet-name>Jersey REST Service</servlet-name> 
<url-pattern>/*</url-pattern> 
</servlet-mapping> 
</web-app>
Jersey – RESTfulWebservice 
• Create a package called ‘com.prgguru.jersey’ 
under src folder
Jersey – RESTfulWebservice 
• Create a class called ‘Constants.java’ under the 
package ‘com.example.jersey’ and add below 
code to it: 
//Change these parameters according to your DB 
public class Constants { 
public static String dbClass = "com.mysql.jdbc.Driver"; 
private static String dbName= "users"; 
public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName; 
public static String dbUser = "root"; 
public static String dbPwd = "password"; 
}
Jersey – RESTfulWebservice 
• Create a class called ‘DBConnection.java’ 
under the package ‘com.prgguru.jersey’ and 
add below code to it:
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
public class DBConnection { 
/** 
* Method to create DB Connection 
* 
* @return 
* @throws Exception 
*/ 
@SuppressWarnings("finally") 
public static Connection createConnection() throws Exception { 
Connection con = null; 
try { 
Class.forName(Constants.dbClass); 
con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); 
} catch (Exception e) { 
throw e; 
} finally { 
return con; 
} 
}
public static boolean checkLogin(String uname, String pwd) throws Exception { 
boolean isUserAvailable = false; 
Connection dbConn = null; 
try { 
try { 
dbConn = DBConnection.createConnection(); 
} catch (Exception e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
Statement stmt = dbConn.createStatement(); 
String query = "SELECT * FROM user WHERE username = '" + uname 
+ "' AND password=" + "'" + pwd + "'"; 
//System.out.println(query); 
ResultSet rs = stmt.executeQuery(query); 
while (rs.next()) { 
//System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3)); 
isUserAvailable = true; 
}
} catch (SQLException sqle) { 
throw sqle; 
} catch (Exception e) { 
// TODO Auto-generated catch block 
if (dbConn != null) { 
dbConn.close(); 
} 
throw e; 
} finally { 
if (dbConn != null) { 
dbConn.close(); 
} 
} 
return isUserAvailable; 
}
public static boolean insertUser(String name, String uname, String pwd) throws SQLException, 
Exception { 
boolean insertStatus = false; 
Connection dbConn = null; 
try { 
try { 
dbConn = DBConnection.createConnection(); 
} catch (Exception e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
Statement stmt = dbConn.createStatement(); 
String query = "INSERT into user(name, username, password) values('"+name+ "',"+"'" 
+ uname + "','" + pwd + "')"; 
//System.out.println(query); 
int records = stmt.executeUpdate(query); 
//System.out.println(records); 
//When record is successfully inserted 
if (records > 0) { 
insertStatus = true; 
}
} catch (SQLException sqle) { 
//sqle.printStackTrace(); 
throw sqle; 
} catch (Exception e) { 
//e.printStackTrace(); 
// TODO Auto-generated catch block 
if (dbConn != null) { 
dbConn.close(); 
} 
throw e; 
} finally { 
if (dbConn != null) { 
dbConn.close(); 
} 
} 
return insertStatus; 
} 
}
Create a class called ‘Utility.java’ under the package ‘com.prgguru.jersey’ and add below code to 
it: 
Utility.java 
import org.codehaus.jettison.json.JSONException; 
import org.codehaus.jettison.json.JSONObject; 
public class Utitlity { 
/** 
* Null check Method 
* 
* @param txt 
* @return 
*/ 
public static boolean isNotNull(String txt) { 
// System.out.println("Inside isNotNull"); 
return txt != null && txt.trim().length() >= 0 ? true : false; 
} 
/** 
* Method to construct JSON 
* 
* @param tag 
* @param status 
* @return 
*/
public static String constructJSON(String tag, boolean status) { 
JSONObject obj = new JSONObject(); 
try { 
obj.put("tag", tag); 
obj.put("status", new Boolean(status)); 
} catch (JSONException e) { 
// TODO Auto-generated catch block 
} 
return obj.toString(); 
} 
/** 
* Method to construct JSON with Error Msg 
* 
* @param tag 
* @param status 
* @param err_msg 
* @return 
*/
public static String constructJSON(String tag, boolean status,String err_msg) { 
JSONObject obj = new JSONObject(); 
try { 
obj.put("tag", tag); 
obj.put("status", new Boolean(status)); 
obj.put("error_msg", err_msg); 
} catch (JSONException e) { 
// TODO Auto-generated catch block 
} 
return obj.toString(); 
} 
}
Jersey – RESTfulWebservice 
• Create a class called Register.java under the 
package ‘com.example.jersey’ and add below 
code to it. 
Register.java
Register.java 
import java.sql.SQLException; 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.QueryParam; 
import javax.ws.rs.core.MediaType; 
//Path: http://localhost/<appln-folder-name>/register 
@Path("/register") 
public class Register { 
// HTTP Get Method 
@GET 
// Path: http://localhost/<appln-folder-name>/register/doregister 
@Path("/doregister") 
// Produces JSON as response 
@Produces(MediaType.APPLICATION_JSON) 
// Query parameters are parameters: http://localhost/<appln-folder-name>/ 
register/doregister?name=pqrs&username=abc&password=xyz
public String doLogin(@QueryParam("name") String name, 
@QueryParam("username") String uname, @QueryParam("password") String pwd){ 
String response = ""; 
//System.out.println("Inside doLogin "+uname+" "+pwd); 
int retCode = registerUser(name, uname, pwd); 
if(retCode == 0){ 
response = Utitlity.constructJSON("register",true); 
}else if(retCode == 1){ 
response = Utitlity.constructJSON("register",false, "You are already registered"); 
}else if(retCode == 2){ 
response = Utitlity.constructJSON("register",false, "Special Characters are not 
allowed in Username and Password"); 
}else if(retCode == 3){ 
response = Utitlity.constructJSON("register",false, "Error occured"); 
} 
return response; 
}
private int registerUser(String name, String uname, String pwd){ 
System.out.println("Inside checkCredentials"); 
int result = 3; 
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){ 
try { 
if(DBConnection.insertUser(name, uname, pwd)){ 
System.out.println("RegisterUSer if"); 
result = 0; 
} 
} catch(SQLException sqle){ 
System.out.println("RegisterUSer catch sqle"); 
//When Primary key violation occurs that means user is already registered 
if(sqle.getErrorCode() == 1062){ 
result = 1; 
} 
//When special characters are used in name,username or password 
else if(sqle.getErrorCode() == 1064){ 
System.out.println(sqle.getErrorCode()); 
result = 2; 
} 
}
catch (Exception e) { 
// TODO Auto-generated catch block 
System.out.println("Inside checkCredentials catch e "); 
result = 3; 
} 
}else{ 
System.out.println("Inside checkCredentials else"); 
result = 3; 
} 
return result; 
} 
}
Create a class called ‘Login.java’ under the package ‘com.example.jersey’ and add below 
code to it. 
Login.java 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.QueryParam; 
import javax.ws.rs.core.MediaType; 
//Path: http://localhost/<appln-folder-name>/login 
@Path("/login") 
public class Login { 
// HTTP Get Method 
@GET 
// Path: http://localhost/<appln-folder-name>/login/dologin 
@Path("/dologin") 
// Produces JSON as response 
@Produces(MediaType.APPLICATION_JSON) 
// Query parameters are parameters: http://localhost/<appln-folder-name>/ 
login/dologin?username=abc&password=xyz
public String doLogin(@QueryParam("username") String uname, 
@QueryParam("password") String pwd){ 
String response = ""; 
if(checkCredentials(uname, pwd)){ 
response = Utitlity.constructJSON("login",true); 
}else{ 
response = Utitlity.constructJSON("login", false, "Incorrect Email or Password"); 
} 
return response; 
}
private boolean checkCredentials(String uname, String pwd){ 
System.out.println("Inside checkCredentials"); 
boolean result = false; 
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){ 
try { 
result = DBConnection.checkLogin(uname, pwd); 
//System.out.println("Inside checkCredentials try "+result); 
} catch (Exception e) { 
// TODO Auto-generated catch block 
//System.out.println("Inside checkCredentials catch"); 
result = false; 
} 
}else{ 
//System.out.println("Inside checkCredentials else"); 
result = false; 
} 
return result; 
} 
}
• Deploy the web application:Right click on the project ‘useraccount’ >> Run As >> 
Run on Server
• http://opensignal.com/blog/2013/07/30/40- 
developer-tips-for-android-optimization/ 
• http://blog.hsc.com/android/technology-trends/ 
android-memory-optimization/ 
• https://www.google.co.in/search?q=optimization 
+in+android&rlz=1C1CHMO_enIN570IN570&oq= 
optimization+in+android&aqs=chrome..69i57.80 
19j0j7&sourceid=chrome&es_sm=122&ie=UTF- 
8#q=what+is+optimization+

Weitere ähnliche Inhalte

Ähnlich wie Optimisation and performance in Android

The Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with androidThe Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with androidStanojko Markovik
 
Big Trouble in Little Networks, new and improved
Big Trouble in Little Networks, new and improvedBig Trouble in Little Networks, new and improved
Big Trouble in Little Networks, new and improvedStacy Devino
 
Tuning android for low ram devices
Tuning android for low ram devicesTuning android for low ram devices
Tuning android for low ram devicesDroidcon Berlin
 
Sidiq Permana - Building For The Next Billion Users
Sidiq Permana - Building For The Next Billion UsersSidiq Permana - Building For The Next Billion Users
Sidiq Permana - Building For The Next Billion UsersDicoding
 
How to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidHow to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidSingsys Pte Ltd
 
Beating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett DuncavageBeating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett DuncavageXamarin
 
Performance as UX with Justin Howlett
Performance as UX with Justin HowlettPerformance as UX with Justin Howlett
Performance as UX with Justin HowlettFITC
 
Optimizing Browser Rendering
Optimizing Browser RenderingOptimizing Browser Rendering
Optimizing Browser Renderingmichael.labriola
 
Improving Drupal Performances
Improving Drupal PerformancesImproving Drupal Performances
Improving Drupal PerformancesVladimir Ilic
 
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...Padma shree. T
 
How to deal with Fragmentation on Android
How to deal with Fragmentation on AndroidHow to deal with Fragmentation on Android
How to deal with Fragmentation on AndroidSittiphol Phanvilai
 
Debug, Analyze and Optimize Games with Intel Tools
Debug, Analyze and Optimize Games with Intel Tools Debug, Analyze and Optimize Games with Intel Tools
Debug, Analyze and Optimize Games with Intel Tools Matteo Valoriani
 
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...Codemotion
 
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...Codemotion
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices Amgad Muhammad
 
Thinking cpu & memory - DroidCon Paris 18 june 2013
Thinking cpu & memory - DroidCon Paris 18 june 2013Thinking cpu & memory - DroidCon Paris 18 june 2013
Thinking cpu & memory - DroidCon Paris 18 june 2013Paris Android User Group
 
Yahoo - Web Images optimization
Yahoo - Web Images optimizationYahoo - Web Images optimization
Yahoo - Web Images optimizationEduard Bondarenko
 
Top 13 best front end web development tools to consider in 2021
Top 13 best front end web development tools to consider in 2021Top 13 best front end web development tools to consider in 2021
Top 13 best front end web development tools to consider in 2021Samaritan InfoTech
 

Ähnlich wie Optimisation and performance in Android (20)

The Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with androidThe Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with android
 
Big Trouble in Little Networks, new and improved
Big Trouble in Little Networks, new and improvedBig Trouble in Little Networks, new and improved
Big Trouble in Little Networks, new and improved
 
Tuning android for low ram devices
Tuning android for low ram devicesTuning android for low ram devices
Tuning android for low ram devices
 
Sidiq Permana - Building For The Next Billion Users
Sidiq Permana - Building For The Next Billion UsersSidiq Permana - Building For The Next Billion Users
Sidiq Permana - Building For The Next Billion Users
 
How to do Memory Optimizations in Android
How to do Memory Optimizations in AndroidHow to do Memory Optimizations in Android
How to do Memory Optimizations in Android
 
Beating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett DuncavageBeating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett Duncavage
 
Performance as UX with Justin Howlett
Performance as UX with Justin HowlettPerformance as UX with Justin Howlett
Performance as UX with Justin Howlett
 
Optimizing Browser Rendering
Optimizing Browser RenderingOptimizing Browser Rendering
Optimizing Browser Rendering
 
Improving Drupal Performances
Improving Drupal PerformancesImproving Drupal Performances
Improving Drupal Performances
 
Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
 
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
 
How to deal with Fragmentation on Android
How to deal with Fragmentation on AndroidHow to deal with Fragmentation on Android
How to deal with Fragmentation on Android
 
Debug, Analyze and Optimize Games with Intel Tools
Debug, Analyze and Optimize Games with Intel Tools Debug, Analyze and Optimize Games with Intel Tools
Debug, Analyze and Optimize Games with Intel Tools
 
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
 
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
Debug, Analyze and Optimize Games with Intel Tools - Matteo Valoriani - Codem...
 
Front-end performances
Front-end performancesFront-end performances
Front-end performances
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
 
Thinking cpu & memory - DroidCon Paris 18 june 2013
Thinking cpu & memory - DroidCon Paris 18 june 2013Thinking cpu & memory - DroidCon Paris 18 june 2013
Thinking cpu & memory - DroidCon Paris 18 june 2013
 
Yahoo - Web Images optimization
Yahoo - Web Images optimizationYahoo - Web Images optimization
Yahoo - Web Images optimization
 
Top 13 best front end web development tools to consider in 2021
Top 13 best front end web development tools to consider in 2021Top 13 best front end web development tools to consider in 2021
Top 13 best front end web development tools to consider in 2021
 

Mehr von Rakesh Jha

Whitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trendsWhitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trendsRakesh Jha
 
Ways to be a great project manager
Ways to be a great project managerWays to be a great project manager
Ways to be a great project managerRakesh Jha
 
What is mobile wallet
What is mobile walletWhat is mobile wallet
What is mobile walletRakesh Jha
 
Cordova vs xamarin vs titanium
Cordova vs xamarin vs titaniumCordova vs xamarin vs titanium
Cordova vs xamarin vs titaniumRakesh Jha
 
Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)Rakesh Jha
 
Mobile testing practices
Mobile testing practicesMobile testing practices
Mobile testing practicesRakesh Jha
 
Advanced programing in phonegap
Advanced programing in phonegapAdvanced programing in phonegap
Advanced programing in phonegapRakesh Jha
 
Introduction phonegap
Introduction phonegapIntroduction phonegap
Introduction phonegapRakesh Jha
 
Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap Rakesh Jha
 
Basics of css3
Basics of css3 Basics of css3
Basics of css3 Rakesh Jha
 
Introduction to jquery mobile with Phonegap
Introduction to jquery mobile with PhonegapIntroduction to jquery mobile with Phonegap
Introduction to jquery mobile with PhonegapRakesh Jha
 
Basics of HTML5 for Phonegap
Basics of HTML5 for PhonegapBasics of HTML5 for Phonegap
Basics of HTML5 for PhonegapRakesh Jha
 
Introduction of phonegap installation and configuration of Phonegap with An...
Introduction of phonegap   installation and configuration of Phonegap with An...Introduction of phonegap   installation and configuration of Phonegap with An...
Introduction of phonegap installation and configuration of Phonegap with An...Rakesh Jha
 
Android ndk - Introduction
Android ndk  - IntroductionAndroid ndk  - Introduction
Android ndk - IntroductionRakesh Jha
 
Native development kit (ndk) introduction
Native development kit (ndk)  introductionNative development kit (ndk)  introduction
Native development kit (ndk) introductionRakesh Jha
 
User experience and interactions design
User experience and interactions design User experience and interactions design
User experience and interactions design Rakesh Jha
 
Android coding standard
Android coding standard Android coding standard
Android coding standard Rakesh Jha
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Advance ui development and design
Advance ui  development and design Advance ui  development and design
Advance ui development and design Rakesh Jha
 
Android Design Architecture
Android Design ArchitectureAndroid Design Architecture
Android Design ArchitectureRakesh Jha
 

Mehr von Rakesh Jha (20)

Whitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trendsWhitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trends
 
Ways to be a great project manager
Ways to be a great project managerWays to be a great project manager
Ways to be a great project manager
 
What is mobile wallet
What is mobile walletWhat is mobile wallet
What is mobile wallet
 
Cordova vs xamarin vs titanium
Cordova vs xamarin vs titaniumCordova vs xamarin vs titanium
Cordova vs xamarin vs titanium
 
Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)
 
Mobile testing practices
Mobile testing practicesMobile testing practices
Mobile testing practices
 
Advanced programing in phonegap
Advanced programing in phonegapAdvanced programing in phonegap
Advanced programing in phonegap
 
Introduction phonegap
Introduction phonegapIntroduction phonegap
Introduction phonegap
 
Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap
 
Basics of css3
Basics of css3 Basics of css3
Basics of css3
 
Introduction to jquery mobile with Phonegap
Introduction to jquery mobile with PhonegapIntroduction to jquery mobile with Phonegap
Introduction to jquery mobile with Phonegap
 
Basics of HTML5 for Phonegap
Basics of HTML5 for PhonegapBasics of HTML5 for Phonegap
Basics of HTML5 for Phonegap
 
Introduction of phonegap installation and configuration of Phonegap with An...
Introduction of phonegap   installation and configuration of Phonegap with An...Introduction of phonegap   installation and configuration of Phonegap with An...
Introduction of phonegap installation and configuration of Phonegap with An...
 
Android ndk - Introduction
Android ndk  - IntroductionAndroid ndk  - Introduction
Android ndk - Introduction
 
Native development kit (ndk) introduction
Native development kit (ndk)  introductionNative development kit (ndk)  introduction
Native development kit (ndk) introduction
 
User experience and interactions design
User experience and interactions design User experience and interactions design
User experience and interactions design
 
Android coding standard
Android coding standard Android coding standard
Android coding standard
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Advance ui development and design
Advance ui  development and design Advance ui  development and design
Advance ui development and design
 
Android Design Architecture
Android Design ArchitectureAndroid Design Architecture
Android Design Architecture
 

Optimisation and performance in Android

  • 1. Optimisation and Performance Rakesh Kumar Jha M. Tech, MBA Delivery Manager
  • 2. Optimisation and Performance  What is Optimisation and Performance  Memory Efficiently  Networking  Location  Optimizing Graphics and UI Optimizing Layouts  Layout Tools  Benchmarking And Profiling  Tracing  Logging  Q & A
  • 3. What is Optimization • Finding an alternative with the most cost effective or highest achievable performance under the given constraints, by maximizing desired factors and minimizing undesired ones.
  • 4. What is Optimization • In comparison, maximization means trying to attain the highest or maximum result or outcome without regard to cost or expense. • Practice of optimization is restricted by the lack of full information, and the lack of time to evaluate what information is available.
  • 5. What is Optimization • In computer simulation (modeling) of business problems, optimization is achieved usually by using linear programming techniques of operations research.
  • 6. Optimization in Android • Android devices having limited – Memory • Clean RAM and • Dirty RAM. – Processor
  • 7. Clean RAM • Unlike PCs, Android does not offer swap space for memory, however it does use paging and memory-mapping. • Any files or resources which are present on the disk, such as code, are kept in mmap’ed pages. • Android knows these pages can be recovered from the disk, so they can be paged out if the system needs memory somewhere else
  • 8. Dirty RAM • Dirty RAM is the memory that cannot be paged out. • It can be expensive, especially when running in a background process. • Most of the memory in a running application is dirty memory and this is the one you should watch out for.
  • 9. Dirty RAM • In order to optimize the memory usage, Android tries to share some framework resources or common classes in memory across processes.
  • 10. Dirty RAM • whenever a device boots up, a process called zygote loads the common framework code.
  • 11. Dirty RAM • Every new application process is then forked from the zygote process so it is able to access all the shared RAM pages loaded by it.
  • 12. Dirty RAM • While investigating an application’s RAM usage, it is important to keep shared memory usage in mind since we should only be looking at the private dirty memory that is being used by our application. • This is reflected by USS (unique set size) and PSS (proportional set size) in ‘meminfo.’
  • 13. Memory Optimization, Best Practices For Android • So what can you do to keep your system from running out of memory?
  • 14. Memory Optimization, Best Practices For Android • So what can you do to keep your system from running out of memory? • I’ll discuss about 30 points, we have to keep in mind while developing mobile/handheld applications.
  • 15. Memory Optimization, Best Practices For Android 1. ScrollViews and ListViews are an easy win. 2. Use the folder structures 3. 160dp = 1 inch. 320 dp = 2 inches. dp == dip 4. Resource rules of thumb: 5. you don’t have to tailor all your layout files, you could instead tailor the dimens.xml files. 6. Let whitespace scale more than graphics. Let graphics scale more than buttons.
  • 16. Memory Optimization, Best Practices For Android 7. Use the GraphicalLayout tool for fast previews GraphicalLayout is the WYSIWG editor for XML files
  • 17. Memory Optimization, Best Practices For Android 8. Don’t scale all your images The conceptually simplest way of doing this is to produce a whole host of images and pop them into a matching plethora of drawable folders
  • 18. Memory Optimization, Best Practices For Android 9. Avoid bitmaps (jpg, png). Try to avoid .jpg or png images, this images are easy to implement, but you can save lot of space and achieve much sharper result by 9-patch image, even better to use xml
  • 19. Memory Optimization, Best Practices For Android 10.Use XML Drawables. Wherever you can use XML drawables instead of bitmaps. XML drawables won’t let you do everything, but improve your performance.
  • 20. Memory Optimization, Best Practices For Android 11. Use XML Drawables. Wherever you can use XML drawables instead of bitmaps. XML drawables won’t let you do everything, but improve your performance. <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <corners android:bottomRightRadius="14dp" android:bottomLeftRadius="14dp" android:topLeftRadius="14dp" android:topRightRadius="14dp"/> <gradient android:startColor="@color/off_white" android:endColor="@color/pale_yellow" android:angle="270" android:type="linear"/> <stroke android:width="4dp" android:color="@color/osm_darkerblue"/> </shape>
  • 21. Memory Optimization, Best Practices For Android 12. Why use 9-patch (when you can use XML drawables)
  • 22. Memory Optimization, Best Practices For Android 13. Create custom views by overriding onDraw() There are some things XML just isn’t so great at, we draw a lot of graphs in OpenSignal and WeatherSignal and there are libraries for this, but we coded our graphs custom. It’s kind of fun. You might never need to do it, but to make graphics that are highly dynamic and custom it is often the only way to go.
  • 23. Memory Optimization, Best Practices For Android 14. Use SVG where you can’t use XML Sometimes overriding onDraw() and painstakingly coding up all the lines and arcs you need to draw your custom view is overkill. After all, there is a language for vector graphics, it’s called … Scalable Vector Graphics
  • 24. Memory Optimization, Best Practices For Android 15. GZip your SVG files. Makes them smaller and they parse quicker.
  • 25. Memory Optimization, Best Practices For Android 16. Customise your UI widgets. To make sure your app looks the same on all devices, you’ll need to customise everything, it’s not as hard as you might think and in doing so you’ll get a lot more control over how your app looks.
  • 26. Memory Optimization, Best Practices For Android 17. Selectors are super for building buttons. what do you do to create a button that changes when clicked? Easy: define the background to be an XML file as below, which will receive the button state and serve up the appropriate drawable.
  • 27. Memory Optimization, Best Practices For Android 17. Selectors are super for building buttons. <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/btn_bg_selected" /> <item android:state_focused="true" android:drawable="@drawable/btn_bg" /> <item android:drawable="@drawable/btn_bg" /> <!-- default --> </selector>
  • 28. Memory Optimization, Best Practices For Android 18. The ActionBar and many animation styles didn’t exist pre Honeycomb, use ActionBarSherlock and NineOldAndroids instead.
  • 30. Memory Optimization, Best Practices For Android 19. Test on slow phones. You’ll not only see any problems with slowness, but they’ll drive you nuts, no-one likes a slow app.
  • 31. Memory Optimization, Best Practices For Android 20. Keep your XML layout hierarchy flat. More layers means the system does a lot more work parsing your code and it can take views longer to deploy.
  • 32. Memory Optimization, Best Practices For Android 21.Use Android Lint. Right click on project folder in Eclipse>Android Tools>Run Lint. This can catch a host of things that can improve speed, or just make your code cleaner.
  • 33. Memory Optimization, Best Practices For Android 22. Android Lint can get it wrong. It can suggest things that will break your code in subtle ways, so do understand what it suggests before you make changes
  • 34. Memory Optimization, Best Practices For Android 23. Using <merge> can help flatten your view hierarchy. Simple way of getting rid of superfluous layers. http://android-developers. blogspot.com.ar/2009/03/android-layout- tricks-3-optimize-by.html
  • 35. Memory Optimization, Best Practices For Android 24. Use HierarchyViewer to see your layout hierarchy. This is a brilliant tool which shows just how many layers of layouts you have and which of them are slowing things down.
  • 36. Memory Optimization, Best Practices For Android 25. Use RelativeLayout whenever you can.
  • 37. Memory Optimization, Best Practices For Android 26. Use external profilers as well as DDMS
  • 38. Memory Optimization, Best Practices For Android 27. Use AsyncTasks
  • 40. Memory Optimization, Best Practices For Android 28. Some Android devices have a 100mb limit
  • 41. Memory Optimization, Best Practices For Android 29. Use XML resources (last time I recommend this, I promise)
  • 42. Memory Optimization, Best Practices For Android 30. When you must use PNGs always optimize (with PNGCrush or ImageOptim)
  • 44. Memory Optimization, Best Practices For Android 31. On the Android developer console check for any bugs that have been sent automatically.
  • 45. Memory Optimization, Best Practices For Android 32. ProGuard is turned on by default now. Proguard is awesome (speeds up your app and reduces filesize) but it can make StackTraces very obscure.
  • 46. Memory Optimization, Best Practices For Android 33. Adjust ProGuard config to show line numbers in StackTraces. Make sure your proguard.cfg has a line: -keepattributes SourceFile,LineNumberTable
  • 48. Background Data and Data Transfer
  • 49. ConnectivityManager • Class that answers queries about the state of network connectivity. • It also notifies applications when network connectivity changes. Get an instance of this class by calling Context.getSystemService(Context.CON NECTIVITY_SERVICE).
  • 50. ConnectivityManager • The primary responsibilities of this class are to: • Monitor network connections (Wi-Fi, GPRS, UMTS, etc.) • Send broadcast intents when network connectivity changes • Attempt to "fail over" to another network when connectivity to a network is lost • Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks
  • 53. Checking Network Connection • Android lets your application connect to the internet or any other local network and allows you to perform network operations.
  • 54. Checking Network Connection • A device can have various types of network connections. • We will focuses on using either a Wi-Fi or a mobile network connection.
  • 55. Checking Network Connection • Before you perform any netowrk operations, you must first check that are you connected to that network or internet e.t.c. • For this android provides ConnectivityManager class. • You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below:
  • 56. Checking Network Connection ConnectivityManager check = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
  • 57. Checking Network Connection Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo. So you have to recieve it like this.
  • 58. Checking Network Connection NetworkInfo[] info = check.getAllNetworkInfo();
  • 59. Checking Network Connection The last thing you need to do is to check Connected State of the network. Its syntax is given below: for (int i = 0; i<info.length; i++){ if (info[i].getState() == NetworkInfo.State.CONNECTED){ Toast.makeText(context, "Internet is connected Toast.LENGTH_SHORT).show(); } }
  • 60. Checking Network Connection Apart from this connected states, there are other states a network can achieve. They are listed below: Sr.No State 1 Connecting 2 Disconnected 3 Disconnecting 4 Suspended 5 Unknown
  • 61. Performing Network Operations After checking that you are connected to the internet, you can perform any network operation. Here we are fetching the html of a website from a url.
  • 62. Performing Network Operations Android provides HttpURLConnection and URL class to handle these operations. You need to instantiate an object of URL class by providing the link of website. Its syntax is as follows:
  • 63. Performing Network Operations String link = "http://www.google.com"; URL url = new URL(link);
  • 64. Performing Network Operations After that you need to call openConnection method of url class and recieve it in a HttpURLConnection object. After that you need to call the connect method of HttpURLConnection class.
  • 65. Performing Network Operations HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect();
  • 66. Performing Network Operations And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below: InputStream is = conn.getInputStream(); BufferedReader reader =new BufferedReader(new InputStreamReader(is, "UTF-8")); String webPage = "",data=""; while ((data = reader.readLine()) != null){ webPage += data + "n"; }
  • 67. Performing Network Operations And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below: InputStream is = conn.getInputStream(); BufferedReader reader =new BufferedReader(new InputStreamReader(is, "UTF-8")); String webPage = "",data=""; while ((data = reader.readLine()) != null){ webPage += data + "n"; }
  • 69. • we are going to explain, how you can integrate PHP and MYSQL with your android application. • This is very useful in case you have a webserver, and you want to access its data on your android application.
  • 70. CREATING DATABASE <?php $con=mysqli_connect("example.com","username"," password"); $sql="CREATE DATABASE my_db"; if (mysqli_query($con,$sql)) { echo "Database my_db created successfully"; } ?>
  • 71. CREATING TABLES <?php $con=mysqli_connect("example.com","username"," password","my_db"); $sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role CHAR(30))"; if (mysqli_query($con,$sql)) { echo "Table have been created successfully"; } ?>
  • 72. INSERTING VALUES IN TABLES <?php $con=mysqli_connect("example.com","username"," password","my_db"); $sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin', 'admin','adminstrator')"; if (mysqli_query($con,$sql)) { echo "Values have been inserted successfully"; } ?>
  • 73. PHP - GET AND POST METHODS <?php $con=mysqli_connect("example.com","username","password","database name"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_GET['username']; $password = $_GET['password']; $result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and Password='$password'"); $row = mysqli_fetch_array($result); $data = $row[0]; if($data){ echo $data; } mysqli_close($con); ?>
  • 74. Android - Connecting MYSQL • There are two ways to connect to MYSQL via PHP page. • The first one is called Get method. We will useHttpGet and HttpClient class to connect. Their syntax is given below: URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link));
  • 75. Android - Connecting MYSQL • After that you need to call execute method of HttpClient class and recieve it in a HttpResponse object. • After that you need to open streams to recieve the data. HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
  • 76. CONNECTING VIA POST METHOD • In the Post method , the URLEncoder,URLConnection class will be used. • The urlencoder will encode the information of the passing variables. • It's syntax is given below: URL url = new URL(link); String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URLConnection conn = url.openConnection();
  • 77. CONNECTING VIA POST METHOD • The last thing you need to do is to write this data to the link. • After writing , you need to open stream to recieve the responded data. OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  • 78. Type of web services • Web service is a system that enables applications to communicate with an API. • Web service helps to expose business logic through an API interface where different systems communicate over network.
  • 79. Type of web services
  • 80. Type of web services • Application to application communication. • Interoperability between disparate systems. • Communication over network. • Exposed interface is platform independent and internal implementation is abstracted. • Enables loosely coupled design. • Open protocol is used for establishing communication. • Web services are self contained.
  • 81. Components of a Web Service wsdl
  • 82. Type of web services • Web Services Description Language (WSDL) is used to describe a web service in an XML file. • It covers all the aspects of a web service like what is the message format, communication protocol, endpoint, security etc. • This is a standard provided by W3C consortium and widely accepted for web services description.
  • 83. Type of web services • A wsdl xml file for a web service is generally expected to be published publicly so that parties seeking to utilize its services can understand the nature of service and consume it accordingly.
  • 84. Type of web services • Types is an important element in WSDL. It is used to describe the message attributes and respective types. • XSD is the preferred format to describe the types. • Type definition can be given in a separate XSD file and imported in WSDL.
  • 85. Type of web services <definitions .... > <types> <xsd:schema .... />* </types> </definitions>
  • 86. UDDI
  • 87. • Universal Description, Discovery and Integration (UDDI) is a directory service. • Web services can register with a UDDI and make themselves available through it for discovery.
  • 88. Stub and Skeleton • Stub and skeleton are counterparts in a web service setup. Skeleton belongs to service provider side and stub belongs to receiver side. • At lower level stub and skeleton communicate with each other.
  • 89. Endpoint • An endpoint is a particular network location with associated protocol which includes message format mapping using which we can access that instance of web service. • This is described in WSDL file. Consider this as a handle using which we will access the web service.
  • 90. Binding • Associating an interface with a protocol and message format is binding. • It is used in endpoint definition. Binding is described in WSDL.
  • 91. Operation • A single logical grouping of a meaningful action which comprises a request and response is an operation. Group of operations forms a web service.
  • 92. SOAP • Simple Object Access Protocol is a XML based specification for web services message format and communication over network. That is it helps to describe the transport method and message format in a web service.
  • 93. Web Service Design • As given in diagram a web service has logic and an interface. • Logic is the actual service provided and interface is used to communicate with the web service. Interface definition is given in WSDL. • There are two approaches in implementing a web service and they are bottom-up and top-down.
  • 94. Bottom Up Approach • Bottom up approach is where we first define the logic of a web service and then using that we will build the interface. • Service code is written first and then the WSDL is created using the service code. • There are tools available to generate the wsdl file automatically based on it.
  • 95. Top Down Approach • Top down is the reverse of bottom up approach. • First the service definition is written up. WSDL is created first. • The complete service definition, message format, transport protocol, security and everything is described in WSDL.
  • 96. REST web services • Top down is the reverse of bottom up approach. • First the service definition is written up. WSDL is created first. • The complete service definition, message format, transport protocol, security and everything is described in WSDL.
  • 97. How to create RESTFul webservice in Java? • RESTful webservice in Java and in the next post will be discussing how to consume RESTful webservice we are about to create in Android application.
  • 98. How to create RESTFul webservice in Java?
  • 99. How to create RESTFul webservice in Java? • RESTful webservice in Java and in the next post will be discussing how to consume RESTful webservice we are about to create in Android application.
  • 100. Jersey – RESTfulWebservice • use Jersey framework to design RESTful webservice. Reference: http://www.vogella.com/tutorials/RE ST/article.html#installation_jersey
  • 101. Jersey – RESTfulWebservice • Goto https://jersey.java.net/download.html a nd download Jersey 1.18 ZIP bundle as shown below:
  • 102. Jersey – RESTfulWebservice • Unzip the bundle, you can see list of Jars under lib folder as shown below:
  • 103. Jersey – RESTfulWebservice • Create Dynamic web project in Eclipse as shown below:Choose File>>New>>Dynamic Web Project
  • 104. Jersey – RESTfulWebservice • Enter project name as ‘useraccount’ and Click Finish
  • 105. Jersey – RESTfulWebservice • Add unzipped Jersey library JARs to WEB-INF/ lib folder
  • 106. Jersey – RESTfulWebservice • Register Jersey as Servlet dispatcher by adding below code into web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>useraccount</display-name> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.prgguru.jersey</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
  • 107. Jersey – RESTfulWebservice • Create a package called ‘com.prgguru.jersey’ under src folder
  • 108. Jersey – RESTfulWebservice • Create a class called ‘Constants.java’ under the package ‘com.example.jersey’ and add below code to it: //Change these parameters according to your DB public class Constants { public static String dbClass = "com.mysql.jdbc.Driver"; private static String dbName= "users"; public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName; public static String dbUser = "root"; public static String dbPwd = "password"; }
  • 109. Jersey – RESTfulWebservice • Create a class called ‘DBConnection.java’ under the package ‘com.prgguru.jersey’ and add below code to it:
  • 110. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBConnection { /** * Method to create DB Connection * * @return * @throws Exception */ @SuppressWarnings("finally") public static Connection createConnection() throws Exception { Connection con = null; try { Class.forName(Constants.dbClass); con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); } catch (Exception e) { throw e; } finally { return con; } }
  • 111. public static boolean checkLogin(String uname, String pwd) throws Exception { boolean isUserAvailable = false; Connection dbConn = null; try { try { dbConn = DBConnection.createConnection(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Statement stmt = dbConn.createStatement(); String query = "SELECT * FROM user WHERE username = '" + uname + "' AND password=" + "'" + pwd + "'"; //System.out.println(query); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { //System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3)); isUserAvailable = true; }
  • 112. } catch (SQLException sqle) { throw sqle; } catch (Exception e) { // TODO Auto-generated catch block if (dbConn != null) { dbConn.close(); } throw e; } finally { if (dbConn != null) { dbConn.close(); } } return isUserAvailable; }
  • 113. public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception { boolean insertStatus = false; Connection dbConn = null; try { try { dbConn = DBConnection.createConnection(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Statement stmt = dbConn.createStatement(); String query = "INSERT into user(name, username, password) values('"+name+ "',"+"'" + uname + "','" + pwd + "')"; //System.out.println(query); int records = stmt.executeUpdate(query); //System.out.println(records); //When record is successfully inserted if (records > 0) { insertStatus = true; }
  • 114. } catch (SQLException sqle) { //sqle.printStackTrace(); throw sqle; } catch (Exception e) { //e.printStackTrace(); // TODO Auto-generated catch block if (dbConn != null) { dbConn.close(); } throw e; } finally { if (dbConn != null) { dbConn.close(); } } return insertStatus; } }
  • 115. Create a class called ‘Utility.java’ under the package ‘com.prgguru.jersey’ and add below code to it: Utility.java import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; public class Utitlity { /** * Null check Method * * @param txt * @return */ public static boolean isNotNull(String txt) { // System.out.println("Inside isNotNull"); return txt != null && txt.trim().length() >= 0 ? true : false; } /** * Method to construct JSON * * @param tag * @param status * @return */
  • 116. public static String constructJSON(String tag, boolean status) { JSONObject obj = new JSONObject(); try { obj.put("tag", tag); obj.put("status", new Boolean(status)); } catch (JSONException e) { // TODO Auto-generated catch block } return obj.toString(); } /** * Method to construct JSON with Error Msg * * @param tag * @param status * @param err_msg * @return */
  • 117. public static String constructJSON(String tag, boolean status,String err_msg) { JSONObject obj = new JSONObject(); try { obj.put("tag", tag); obj.put("status", new Boolean(status)); obj.put("error_msg", err_msg); } catch (JSONException e) { // TODO Auto-generated catch block } return obj.toString(); } }
  • 118. Jersey – RESTfulWebservice • Create a class called Register.java under the package ‘com.example.jersey’ and add below code to it. Register.java
  • 119. Register.java import java.sql.SQLException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; //Path: http://localhost/<appln-folder-name>/register @Path("/register") public class Register { // HTTP Get Method @GET // Path: http://localhost/<appln-folder-name>/register/doregister @Path("/doregister") // Produces JSON as response @Produces(MediaType.APPLICATION_JSON) // Query parameters are parameters: http://localhost/<appln-folder-name>/ register/doregister?name=pqrs&username=abc&password=xyz
  • 120. public String doLogin(@QueryParam("name") String name, @QueryParam("username") String uname, @QueryParam("password") String pwd){ String response = ""; //System.out.println("Inside doLogin "+uname+" "+pwd); int retCode = registerUser(name, uname, pwd); if(retCode == 0){ response = Utitlity.constructJSON("register",true); }else if(retCode == 1){ response = Utitlity.constructJSON("register",false, "You are already registered"); }else if(retCode == 2){ response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password"); }else if(retCode == 3){ response = Utitlity.constructJSON("register",false, "Error occured"); } return response; }
  • 121. private int registerUser(String name, String uname, String pwd){ System.out.println("Inside checkCredentials"); int result = 3; if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){ try { if(DBConnection.insertUser(name, uname, pwd)){ System.out.println("RegisterUSer if"); result = 0; } } catch(SQLException sqle){ System.out.println("RegisterUSer catch sqle"); //When Primary key violation occurs that means user is already registered if(sqle.getErrorCode() == 1062){ result = 1; } //When special characters are used in name,username or password else if(sqle.getErrorCode() == 1064){ System.out.println(sqle.getErrorCode()); result = 2; } }
  • 122. catch (Exception e) { // TODO Auto-generated catch block System.out.println("Inside checkCredentials catch e "); result = 3; } }else{ System.out.println("Inside checkCredentials else"); result = 3; } return result; } }
  • 123. Create a class called ‘Login.java’ under the package ‘com.example.jersey’ and add below code to it. Login.java import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; //Path: http://localhost/<appln-folder-name>/login @Path("/login") public class Login { // HTTP Get Method @GET // Path: http://localhost/<appln-folder-name>/login/dologin @Path("/dologin") // Produces JSON as response @Produces(MediaType.APPLICATION_JSON) // Query parameters are parameters: http://localhost/<appln-folder-name>/ login/dologin?username=abc&password=xyz
  • 124. public String doLogin(@QueryParam("username") String uname, @QueryParam("password") String pwd){ String response = ""; if(checkCredentials(uname, pwd)){ response = Utitlity.constructJSON("login",true); }else{ response = Utitlity.constructJSON("login", false, "Incorrect Email or Password"); } return response; }
  • 125. private boolean checkCredentials(String uname, String pwd){ System.out.println("Inside checkCredentials"); boolean result = false; if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){ try { result = DBConnection.checkLogin(uname, pwd); //System.out.println("Inside checkCredentials try "+result); } catch (Exception e) { // TODO Auto-generated catch block //System.out.println("Inside checkCredentials catch"); result = false; } }else{ //System.out.println("Inside checkCredentials else"); result = false; } return result; } }
  • 126. • Deploy the web application:Right click on the project ‘useraccount’ >> Run As >> Run on Server
  • 127. • http://opensignal.com/blog/2013/07/30/40- developer-tips-for-android-optimization/ • http://blog.hsc.com/android/technology-trends/ android-memory-optimization/ • https://www.google.co.in/search?q=optimization +in+android&rlz=1C1CHMO_enIN570IN570&oq= optimization+in+android&aqs=chrome..69i57.80 19j0j7&sourceid=chrome&es_sm=122&ie=UTF- 8#q=what+is+optimization+