NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

- Background Services
- Android Work Manager
- Retrofit


Broadcasts
Broadcasts are messages that the Android system and Android apps send when events occur that might affect the functionality of other apps. For example, the Android system sends an event when the system boots up, when power is connected or disconnected, and when headphones are connected or disconnected. Your Android app can also broadcast events, for example when new data is downloaded.
In general, broadcasts are messaging components used for communicating across apps when events of interest occur.
There are two types of broadcasts:
● System broadcasts are delivered by the system.
● Custom broadcasts are delivered by your app.



System broadcasts
A system broadcast is a message that the Android system sends when a system event occurs. System broadcasts are wrapped in Intent objects.
Examples:
● When the device boots, the system broadcasts a system Intent with the action ACTION_BOOT_COMPLETED.
● When the device is disconnected from external power, the system sends a system Intent with the action field ACTION_POWER_DISCONNECTED.



Custom broadcasts

Custom broadcasts are broadcasts that your app sends out. Use a custom broadcast when you want your app to take an action without launching an activity.
More than one broadcast receiver can be registered to receive your broadcast.
To create a custom broadcast, define a custom Intent action.



Type of Custom Broadcast
There are three ways to deliver a custom broadcast:
● For a normal broadcast, pass the intent to sendBroadcast().
● For an ordered broadcast, pass the intent to sendOrderedBroadcast().
● For a local broadcast, pass the intent to LocalBroadcastManager.sendBroadcast().



Normal broadcasts
The sendBroadcast() method sends broadcasts to all the registered receivers at the same time, in an undefined order. This is called a normal broadcast. A normal broadcast is the most efficient way to send a broadcast. With normal broadcasts, receivers can't propagate the results among themselves, and they can't cancel the broadcast.

Ordered broadcasts

To send a broadcast to one receiver at a time, use the sendOrderedBroadcast():
● The android:priority attribute that's specified in the intent filter determines the order in which the broadcast is sent.
● If more than one receiver with same priority is present, the sending order is random.
● The Intent is propagated from one receiver to the next.
● During its turn, a receiver can update the Intent, or it can cancel the broadcast. (If the receiver cancels the broadcast, the Intent can't be propagated further.)

Local broadcasts

If you don't need to send broadcasts to a different app, use the LocalBroadcastManager.sendBroadcast() method, which sends broadcasts to receivers within your app. This method is efficient, because it doesn't involve interprocess communication. Also, using local broadcasts protects your app against some security issues.
To send a local broadcast:
1. To get an instance of LocalBroadcastManager, call getInstance() and pass in the application context.
2. Call sendBroadcast() on the instance. Pass in the intent that you want to broadcast.


Broadcast receivers

Broadcast receivers are app components that can register for system events or app events. When an event occurs, registered broadcast receivers are notified via an Intent.
Use broadcast receivers to respond to messages that have been broadcast from apps or from the Android system.
To create a broadcast receiver:
1. Define a subclass of the BroadcastReceiver class and implement the onReceive() method.
2. Register the broadcast receiver, either statically or dynamically.

Static receivers

Static receivers are also called manifest-declared receivers. To register a static receiver, include the following attributes inside the <receiver> element in your AndroidManifest.xml file:
android:name
The value for this attribute is the fully classified name of the BroadcastReceiver subclass, including the package name. To use the package name that's specified in the manifest, prefix the subclass name with a period, for example .AlarmReceiver.
android:exported (optional)
If this boolean value is set to false, other apps cannot send broadcasts to your receiver. This attribute is important for security.
<intent-filter>
Include this nested element to specify the broadcast Intent actions that your broadcast receiver component is listening for.


Dynamic receivers

Dynamic receivers are also called context-registered receivers. You register a dynamic receiver using an application context or an Activity context. A dynamic receiver receives broadcasts as long as the registering context is valid:
If you use the application context to register your receiver, your app receives relevant broadcasts as long as your app is running in either the foreground or the background.
If you use an Activity context to register your receiver, your app receives relevant broadcasts until that Activity is destroyed.


Local broadcasts

You must register local receivers dynamically, because static registration in the manifest is not possible for a local broadcasts.
To register a receiver for local broadcasts:
● Get an instance of LocalBroadcastManager by calling the local broadcast() method.
● Call registerReceiver(), passing in the receiver and an IntentFilter object.


What is a service?

A service is an app component that performs long-running operations, usually in the background. Services are defined by the Service class or one of its subclasses.
A service can be started, bound, or both:
Started service is a service that an app component starts by calling startService().
Use started services for tasks that run in the background to perform long-running operations. Also use started services for tasks that perform work for remote processes.
Bound service is a service that an app component binds to itself by calling bindService().
Use bound services for tasks that another app component interacts with to perform interprocess communication (IPC). For example, a bound service might handle network transactions, perform file I/O, play music, or interact with a database.



Implement Service

To implement any kind of service in your app, do the following steps:
1. Declare the service in the manifest.
2. Extend a Service class such as IntentService and create implementation code.
3. Manage the service lifecycle.



Started services

● An app component such as an Activity calls startService() and passes in an Intent. The Intent specifies the service and includes any data for the service to use.
● The system calls the service's onCreate() method and any other appropriate callbacks on the main thread. It's up to the service to implement these callbacks with the appropriate behavior, such as creating a secondary thread in which to work.
● The system calls the service's onStartCommand() method, passing in the Intent supplied by the client.
For example: it might download or upload a file over the network. When the operation is done, the service should stop itself by calling stopSelf(), or another component can stop it by calling stopService().

IntentService

Most started services don't need to handle multiple requests simultaneously, and if they did, it could be a complex and error-prone multi-threading scenario. For these reasons, the IntentService class is a useful subclass of Service on which to base your service:
● IntentService automatically provides a worker thread to handle your Intent.
● IntentService handles some of the boilerplate code that regular services need (such as starting and stopping the service).
● IntentService can create a work queue that passes one intent at a time to your onHandleIntent() implementation, so you don't have to worry about multi-threading.



Bound services

A service is "bound" when an app component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, and get results, sometimes using interprocess communication (IPC) to send and receive information across processes. A bound service runs only as long as another app component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
A bound service generally does not allow components to start it by calling startService().

Foreground services

A foreground service is a service that the user is aware is running. Although both Activities and Services can be killed if the system is low on memory, a foreground service has priority over other resources.
For example, a music player that plays music from a service should be set to run in the foreground, because the user is aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an Activity to interact with the music player.
To request that a service run in the foreground, call startForeground() instead of startService(). This method takes two parameters: an integer that uniquely identifies the notification and the Notification object for the status bar notification. This notification is ongoing, meaning that it can't be dismissed. It stays in the status bar until the service is stopped or removed from the foreground.



Background services

Services running in the background can consume device resources, potentially using device battery and resulting in a worse user experience. To mitigate this problem, the system now applies limitations on started services running in the background, beginning with Android version 8.0 (Oreo, API 26) or higher. These limitations don't affect foreground services or bound services.
While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has several minutes in which it is still allowed to create and use services. At the end of that time, the app is considered to be idle. The system stops the app's background services, just as if the app had called the services' Service.stopSelf() methods

WorkManager

WorkManager is a library for managing deferrable and guaranteed background work.
● Deferrable work : the task can run later and it is still useful (uploading logs vs send a message)
● Guaranteed: the task will run even the app will be closed or the device restarts (backup images to a server)

Why to use WorkManager?

● Backward compatibility with different OS versions (API level 14+)
● Follows system health best practices
● Supports one-off and periodic tasks
● Supports chained tasks with input/output
● Defines constraints on when the task runs
● Guarantees task execution, even if the app or device restarts


When to use WorkManager?

● Fetching data periodically
● Uploading images/files to a server
● Syncing data between app and server
● Sending logs to a server
● Executing expensive operations on data


Retrofit

For Android developers this library is one of the most important to handle network calls. It helps you create a meaningful and easy to understand ‘interface’ between your app and some web-service.


JSON to Kotlin Class (Android Studio Plugin)
Generating Kotlin class from any legal JSON string/JSONSchema or any URLs that returns a JSON string/JSONSchema as response Generating Kotlin class from any legal JSON text when right click on directory and select New -> Kotlin class File from JSON


Retrofit
● Data Classes: Data class which will map json data types with services.
● Service Interface: Define service interface with operational functions with retrofit Response of Data Type. Define annotation with functions like: @GET, @UPDATE, @DELETE, @POST
● Retrofit Instance Class: Create Retrofit instance class which has base url for rest api and return retrofit instance with GSON as converter factory.
● LiveData Response: make LiveData Response and emit the response.
● LiveData Observer: apply observer on LiveData and show records on UI.
● Query Parameters: use @Query() to attach query string to interface function.
● Query Path: add query path in @GET() with curly brace.
● HttpLoggingInterceptor: Build intercepter with level and attach intercept with OkHttpClient. And define client with Retrofit instance.
● Set Time Outs: to override default timeout, we can manage to add connectionTimeout, ReadTimeout, WriteTimeout on OkHttpClient.
● Post Request: use @POST to post body to rest api.

     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.