17. Common errors
- Polling chat/message from server every 5 seconds even when
app in the background
- Pulling photos/articles from server every time user opens the
Gallery even when nothing is changed
- Retrying failing networking requests till them will succeed.
- Service that never stops...
- A lot of bugs :)
32. ● Hypertext Transfer Protocol.
● This makes HTTP a stateless protocol. The communication
usually takes place over TCP/IP, but any reliable transport can be
used. The default port for TCP/IP is 80, but other ports can also
be used.
HTTP
33. URL
The protocol is typically http, but it can also be https for secure
communications.
34. HTTP Verb
Specifying the action we want to perform on host
● GET: fetch an existing resource. The URL contains all the necessary
information the server needs to locate and return the resource.
● POST: create a new resource. POST requests usually carry a payload that
specifies the data for the new resource.
● PUT: update an existing resource. The payload may contain the updated data
for the resource.
● DELETE: delete an existing resource.
35. Status Code
In return, the server responds with status codes and message payloads
1xx: Informational Messages - Expect: 100-continue
2xx: Successful - 200 OK, 204 No Content
3xx: Redirection - This requires the client to take additional action. The most
common use-case is to jump to a different URL in order to fetch the resource.
4xx: Client Error - 404 Not Found, 400 Bad Request,401 Unauthorized,
5xx: Server Error - 503 Service Unavailable
41. HTTP & HTTPS
A TCP stream is broken into IP packets, and it ensures that those
packets always arrive in the correct order without fail. HTTP is an
application layer protocol over TCP, which is over IP.
45. Parallel connections
If there are six assets that the client needs to download from a
website, the client makes six parallel connections to download those
assets, resulting in a faster turnaround.
47. Server side
● establishing a socket to start listening on port 80 (or some other port)
● receiving the request and parsing the message
● processing the response
● setting response headers
● sending the response to the client
● close the connection if a Connection: close request header was found
59. public interface UserService {
@POST("me")
Call<User>me();
}
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/v2/");
.build();
UserService service = retrofit.create(UserService.class);
// the request url for service.me() is:
// https://your.api.url/v2/me
60. OkHttp Integrated
Retrofit 2 relies on OkHttp as the HTTP client and has its own dependency to the
library as well
compile 'com.squareup.okhttp3:okhttp:3.3.1'
OkHttpClient client = httpClient.build();
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/v2/");
.client(client)
.build();
69. Multiple Convertors
First come - first server
First fail, pass to next ne
One that succeed - consume the response.
Add the esoteric first and more general like GSON last.
81. What is it and how i eat that
Android Framework
API >= 7 (Android 2.1)
Synchronizing data between an Android device and web servers
You specify what you should sync , how often - and it will do the rest
83. Let’s compare
Custom Sync Sync Adapter
Network Availability - manually Network Availability - Automatically
Pending Queue - manually Pending Queue - Automatically
Refresh on Network - manually Refresh on Network - Automatically
Periodic Update - manually Periodic Update - Automatically
Sync Setting - manually Sync Setting - Automatically
Network Bandwidth - manually Network Bandwidth - Automatically
Battery Efficient - ?? Depend on you Battery Efficient - Yes
Survive on Reboot - Depends on you Survive on Reboot - Yes
84.
85. How to?
Sqlite Database: I guess you all are master of Sqlite database, SyncAdapter will store data in
Sqlite using Content Provider. You may choose other options as well.
Content Provider: Act as bridge between your database and SyncAdapter. To expose your
data in Rest like URL pattern.
AbstractAccountAuthenticator: We need to extend this class and override methods, It is
primarily used to manage authentication and account management. To use SyncAdapter you
must have custom account. This class is responsible to create account, maintain auth token.
86. How to?
Authenticator Service: This is normal Service, which we are using daily. The only difference
is that this service create object of AbstractAccountAuthenticator class and bind.
AbstractThreadedSyncAdapter: As developer we need to extend this class and override
methods. This is the main piece of SyncAdapter puzzle. It has method onPerformSync, in
which we need to write our code.
Sync Service: This is normal Service. It use to create object of
AbstractThreadedSyncAdapter class and bind.
87. How to?
Authenticator.xml: You need to create this file under res/xml/ folder. This file is required to bind your
authenticator component into the sync adapter and account frameworks, you need to provide these framework
with metadata that describes the component. You can choose your own file name.
SyncAdapter.xml: You need to create this file under res/xml/ folder. The metadata specifies the account type
you've created for your sync adapter, declares a content provider authority associated with your app.
AndroidManifest.xml: You must register Sync Service, Authenticator service and few other things in
AndroidManifast file in order to work SyncAdapter, This is the final piece of puzzle.
90. What?
Schedule the task to execute it when certain conditions met.
(charging, idle, connected to a network or connected to an unmetered
network)
91. Why two?
JobScheduler was introduced in API >= 21 (Lollipop).
GCMNetworkManager - is part of GCM package. When using on
devices >= 21, use JobScheduler underneath.
95. BestTimeService.java
/**
* Task run by GcmNetworkManager when all the requirements of the scheduled
* task are met.
*/
public class BestTimeService extends GcmTaskService {
...
}
96. BestTimeService.java
@Override
public int onRunTask(TaskParams taskParams) {
Log.i(TAG, "onRunTask");
switch (taskParams.getTag()) {
case TAG_TASK_ONEOFF_LOG:
Log.i(TAG, TAG_TASK_ONEOFF_LOG);
// This is where useful work would go
return GcmNetworkManager.RESULT_SUCCESS;
case TAG_TASK_PERIODIC_LOG:
Log.i(TAG, TAG_TASK_PERIODIC_LOG);
// This is where useful work would go
return GcmNetworkManager.RESULT_SUCCESS;
default:
return GcmNetworkManager.RESULT_FAILURE;
}
}
98. Scheduling a task
Task task = new OneoffTask.Builder()
.setService(BestTimeService.class)
.setExecutionWindow(0, 30)
.setTag(BestTimeService.TAG_TASK_ONEOFF_LOG)
.setUpdateCurrent(false)
.setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
.setRequiresCharging(false)
.build();
mGcmNetworkManager.schedule(task);
99. What’s in it?
● Service: The specific GcmTaskService that will control the task.
This will allow us to cancel it later.
● Execution window: The time period in which the task will execute.
First param is the lower bound and the second is the upper bound
(both are in seconds). This one is mandatory.
● Tag: We’ll use the tag to identify in the onRunTask method which
task is currently being run. Each tag should be unique, and the
max length is 100.
100. What’s in it?
● Update Current: This determines whether this task should
override any pre-existing tasks with the same tag. By default, this
is false, so new tasks don’t override existing ones.
● Required Network: Sets a specific network state to run on. If that
network state is unavailable, then the task won’t be executed until
it becomes available.
● Requires Charging: Whether the task requires the device to be
connected to power in order to execute.
101. Scheduling a periodic task
Task task = new PeriodicTask.Builder()
.setService(BestTimeService.class)
.setPeriod(30)
.setFlex(10)
.setTag(BestTimeService.TAG_TASK_PERIODIC_LOG)
.setPersisted(true)
.build();
mGcmNetworkManager.schedule(task);
102. What’s in it?
● Period: Specifies that the task should recur once every interval at
most, where the interval is the input param in seconds. By
default, you have no control over where in that period the task will
execute. This setter is mandatory.
● Flex: Specifies how close to the end of the period (set above) the
task may execute. With a period of 30 seconds and a flex of 10,
the scheduler will execute the task between the 20-30 second
range.
103. What’s in it?
● Persisted: Determines whether the task should be persisted
across reboots. Defaults to true for periodic tasks, and is not
supported for one-off tasks. Requires “Receive Boot Completed”
permission, or the setter will be ignored.
107. Not all devices shipped with Play Services
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode == ConnectionResult.SUCCESS) {
mGcmNetworkManager.schedule(task);
} else {
// Deal with this networking task some other way
}
108. When Google Play updated it removes all scheduled periodic tasks
public class BestTimeService extends GcmTaskService {
@Override
public void onInitializeTasks() {
super.onInitializeTasks();
// Reschedule removed tasks here
}
}
126. Message strategy
● Notifications delivered when your app is in the background. In this case, the
notification is delivered to the device’s system tray. A user tap on a
notification opens the app launcher by default.
● Messages with both notification and data payload. In this case, the notification
is delivered to the device’s system tray, and the data payload is delivered in
the extras of the intent of your launcher Activity.
127. public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
sendNotification(remoteMessage.getNotification().getBody());
}
}
MyFirebaseMessagingService
144. WhiteList
● An app can fire the
ACTION_IGNORE_BATTERY_OPTIMIZATION_SE
TTINGS intent to take the user directly to the
Battery Optimization, where they can add the
app.
● An app holding the
REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
permission can trigger a system dialog to let
145. WhiteList
● An app holding the
REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
permission can trigger a system dialog to let
the user add the app to the whitelist directly,
without going to settings. The app fires a
ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZ
ATIONS Intent to trigger the dialog.
146. Note: Google Play policies prohibit apps from
requesting direct exemption from Power
Management features in Android 6.0+ (Doze
and App Standby) unless the core function of
the app is adversely affected.
154. Process
1. Create schema
2. Compile schema with flatc compiler
3. Import generated files into your project
4. Read from byte[]:
java.nio.ByteBuffer buf = builder.dataBuffer();
// Deserialize the data from the buffer.
StarWars starWars = StarWars.getRootAsStarWars(buf);