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.
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
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:
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.
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:
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.
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.
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.
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>
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.
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
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;
}
}
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