Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

MULTITHREADING

Multithreading
Multithreading in Android allows you to run multiple threads concurrently, enabling
you to perform tasks in parallel and keep your application responsive.

In Android, you often use multithreading to offload time-consuming operations from
the main UI thread to keep your app responsive

Examples for multithreading in Android:


a) Downloading an Image in the Background:

b) Using AsyncTask for Background Processing

c) Performing Database Operations

d) Loading Data from a REST API:


CREATE A NEW THREAD
To create a new thread, you can use the Thread class and provide it with a
Runnable that contains the code you want to run in the new thread.

new Thread(new Runnable() {


@Override
public void run() {
// Code to be executed in the new thread
}
}).start();
UPDATE UI FROM THE MAIN
THREAD (UI THREAD)
If you need to update UI elements based on the results of the background
work, you should use a Handler to post a Runnable to the main (UI) thread.
This is because UI updates must be performed on the main thread.

HANDLER
A Handler is an Android class that allows you to send and process Message
and Runnable objects associated with the main (UI) thread. It's commonly
used to update UI elements from background threads.
UPDATE UI FROM THE MAIN
THREAD (UI THREAD)
Handler handler = new Handler(Looper.getMainLooper());
new Thread(new Runnable() {
@Override
public void run() {
// Background work
final String result = performBackgroundTask();
// Update UI from the main thread using a Handler
handler.post(new Runnable() {
@Override
public void run() {
textView.setText(result); // Update UI element
}
});
}
}).start();
ASYNCTASK
AsyncTask is a class in Android that simplifies the process of
performing background tasks and updating the UI thread with the
results.
It's a commonly used component for handling asynchronous
operations in Android applications.
AsyncTask is particularly useful when you need to perform
operations like network requests, database queries, or any other
time-consuming tasks off the main UI thread to ensure your app
remains responsive
KEY COMPONENTS OF
ASYNCTASK:
doInBackground: This method runs in the background thread. You
should place the time-consuming task you want to perform here. It
takes an input parameter, processes it, and returns a result.
onPreExecute: This method runs on the UI thread before
doInBackground is executed. It's typically used to set up any UI
elements or show progress indicators before starting the background
task.
onPostExecute: This method runs on the UI thread after
doInBackground completes. You can use it to update UI elements
with the result of the background task.
KEY COMPONENTS OF
ASYNCTASK:
onProgressUpdate: This method runs on the UI thread whenever
you call publishProgress from within doInBackground. It's useful
for updating progress bars or other UI elements during the
background task's execution.
ASYNCTASK PARAMETERS:
AsyncTask is defined with three generic types:
i. Params: The type of input parameters you pass to
doInBackground.
ii. Progress: The type of progress units you send during the task's
execution (used with publishProgress and onProgressUpdate).
iii. Result: The type of result returned by doInBackground and
passed to onPostExecute.
ASYNCTASK WORKFLOW:
Creation: Create an instance of your AsyncTask class and set up
any necessary parameters, such as input data.
Execution: Call execute on the AsyncTask instance. This starts the
background task by invoking onPreExecute, followed by
doInBackground in a separate background thread.
Background Work: doInBackground performs the time-consuming
task. It can access input parameters passed to the AsyncTask and
uses publishProgress to send progress updates to
onProgressUpdate.
ASYNCTASK WORKFLOW:
Progress Updates: If needed, you can call publishProgress from within
doInBackground to trigger onProgressUpdate on the UI thread.

Post-Execution: Once doInBackground completes, it returns a result,


which is passed to onPostExecute. Here, you can update the UI with
the result.

Cancellation: AsyncTask can be cancelled by calling cancel. You can


check for cancellation within doInBackground using isCancelled.
ASYNCTASK WORKFLOW:
class MyAsyncTask extends AsyncTask<Void, Integer, String> {
@Override
protected void onPreExecute() {
// Set up UI elements, show progress indicator
}
ASYNCTASK WORKFLOW:
@Override
protected String doInBackground(Void... params) {
// Background work, e.g., fetching data from a web service
for (int i = 0; i < 100; i++) {
// Simulate progress
publishProgress(i);
}
return "Data fetched successfully!";
}
ASYNCTASK WORKFLOW:
@Override
protected void onProgressUpdate(Integer... values) {
// Update progress bar or other UI elements
int progress = values[0];
// Update UI with progress
}
ASYNCTASK WORKFLOW:
@Override
protected void onPostExecute(String result) {
// Update UI with the result
// Hide progress indicator
}
}
ANDROID NETWORK
PROGRAMMING
a) Android network programming is an essential part of many
Android applications, especially those that interact with web
services or fetch data from the internet. Android provides
various APIs for network communication.
b) one of the commonly used methods for making HTTP requests
is through the HttpURLConnection class.
USING
HTTPURLCONNECTION FOR
HTTP REQUESTS:
HttpURLConnection is a class provided by Android that allows
you to establish and manage HTTP connections. Here's a step-by-
step guide on how to use it:
Import the necessary packages:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
CREATE AN
HTTPURLCONNECTION
OBJECT:
URL url = new URL("https://example.com/api/data");
// Replace with your API endpoint
HttpURLConnection conn =
(HttpURLConnection)url.openConnection();
SET THE HTTP REQUEST
METHOD (GET, POST, ETC.):
conn.setRequestMethod("GET");
SET REQUEST HEADERS (IF
NEEDED):
conn.setRequestProperty("Content-Type", "application/json"); //
Set the content type
conn.setRequestProperty("Authorization", "Bearer
YourAuthToken"); // Set authorization header if required
SEND THE HTTP REQUEST:
int responseCode = conn.getResponseCode();
READ THE RESPONSE:
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {


response.append(inputLine);
}
in.close();

String jsonResponse = response.toString();


// Handle the response data here
} else {
// Handle the error response
CLOSING THE
CONNECTION:
conn.disconnect();
CONNECTING TO REST-
BASED WEB SERVICES:
REST (Representational State Transfer) is an architectural style for
designing networked applications. RESTful web services use
HTTP methods (GET, POST, PUT, DELETE) to perform CRUD
(Create, Read, Update, Delete) operations on resources.

Here's how you can connect to a RESTful web service using


HttpURLConnection:
CONNECTING TO REST-
BASED WEB SERVICES:GET
URL url = new URL("https://api.example.com/users");
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// Set headers and other properties if needed

int responseCode = conn.getResponseCode();


// Read and process the response as shown above
CONNECTING TO REST-
BASED WEB SERVICES:POST
URL url = new URL("https://api.example.com/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json"); // Set content type
// Set other headers and properties if needed
String postData = "{\"name\":\"John\",\"email\":\"john@example.com\"}"; // Your JSON
data
conn.setDoOutput(true); // Enable output (POST) mode
conn.getOutputStream().write(postData.getBytes("UTF-8"));

int responseCode = conn.getResponseCode();


// Read and process the response as shown above
CONNECTING TO SOAP-
BASED WEB SERVICES:
SOAP (Simple Object Access Protocol) is a protocol for
exchanging structured information in the implementation of web
services. Android has built-in libraries like ksoap2-android that
simplify working with SOAP-based services.
Here's a high-level overview of connecting to SOAP-based web
services:
 Add the ksoap2-android library to your project's dependencies.
 Create a SOAP request envelope and specify the SOAP action:
CONNECTING TO SOAP-
BASED WEB SERVICES:
SoapObject request = new SoapObject(NAMESPACE,
METHOD_NAME);
// Add parameters if required

Create a SoapSerializationEnvelope and set the request:


SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
CONNECTING TO SOAP-
BASED WEB SERVICES:
Create a HttpTransportSE object and make the SOAP request:
HttpTransportSE httpTransport = new HttpTransportSE(URL);
httpTransport.call(SOAP_ACTION, envelope);

// Handle the response


if (envelope.bodyIn instanceof SoapObject) {
SoapObject response = (SoapObject) envelope.bodyIn;
// Process the SOAP response
}

You might also like