0% found this document useful (0 votes)
12 views10 pages

Lab-stateMachine NetworkCommunication Telephon

The document provides a comprehensive guide on implementing a state machine, network communication, and telephony functionalities in an Android application using Java. It includes steps to create a login flow state machine, perform network operations using HttpURLConnection, and fetch telephony information using TelephonyManager. Each section details the necessary code, layout, and permissions required for successful implementation.

Uploaded by

Keto Tg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Lab-stateMachine NetworkCommunication Telephon

The document provides a comprehensive guide on implementing a state machine, network communication, and telephony functionalities in an Android application using Java. It includes steps to create a login flow state machine, perform network operations using HttpURLConnection, and fetch telephony information using TelephonyManager. Each section details the necessary code, layout, and permissions required for successful implementation.

Uploaded by

Keto Tg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

State Machine

Below is a complete demo that demonstrates how to implement and display the activity of a state
machine in an Android application using Java. We'll use a basic state machine to represent a
login flow (Idle, Logging In, Login Successful, Login Failed) and visualize the transitions
in the UI.

1. Create a New Android Project

 Ensure the Minimum SDK is API 28 (as per your setup).


 Use Empty Activity for simplicity.

2. Define the State Machine

Create a new Java class called LoginStateMachine:

public class LoginStateMachine {


public enum State {
IDLE,
LOGGING_IN,
LOGIN_SUCCESS,
LOGIN_FAILED
}

private State currentState;

public LoginStateMachine() {
currentState = State.IDLE;
}

public State getCurrentState() {


return currentState;
}

public void startLogin() {


if (currentState == State.IDLE) {
currentState = State.LOGGING_IN;
}
}

public void loginSuccess() {


if (currentState == State.LOGGING_IN) {
currentState = State.LOGIN_SUCCESS;
}
}

public void loginFailed() {


if (currentState == State.LOGGING_IN) {
currentState = State.LOGIN_FAILED;
}
}

public void reset() {


currentState = State.IDLE;
}

3. Update the UI to Display State Transitions

In the activity_main.xml file, define the layout:

xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/stateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current State: IDLE"
android:textSize="18sp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"/>

<Button
android:id="@+id/startLoginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Login"/>

<Button
android:id="@+id/loginSuccessButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login Success"
android:layout_marginBottom="8dp" />

<Button
android:id="@+id/loginFailedButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login Failed"
android:layout_marginTop="8dp" />

<Button
android:id="@+id/resetButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Reset"
android:layout_marginTop="8dp" />
</LinearLayout>
4. Implement State Transitions in MainActivity

In the MainActivity.java file, implement the logic:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private LoginStateMachine stateMachine;


private TextView stateTextView;
private Button startLoginButton, loginSuccessButton, loginFailedButton,
resetButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

stateMachine = new LoginStateMachine();


stateTextView = findViewById(R.id.stateTextView);
startLoginButton = findViewById(R.id.startLoginButton);
loginSuccessButton = findViewById(R.id.loginSuccessButton);
loginFailedButton = findViewById(R.id.loginFailedButton);
resetButton = findViewById(R.id.resetButton);

updateUI();

startLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stateMachine.startLogin();
updateUI();
}
});

loginSuccessButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stateMachine.loginSuccess();
updateUI();
}
});

loginFailedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stateMachine.loginFailed();
updateUI();
}
});

resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stateMachine.reset();
updateUI();
}
});
}

private void updateUI() {


stateTextView.setText("Current State: " + stateMachine.getCurrentState());
}

5. Run the App

 Build and run the app on an emulator or physical device.


 Interact with the buttons to see state transitions displayed on the screen.

6. Explanation

1. State Machine Logic: Encapsulates the state transitions in LoginStateMachine.


2. UI Interaction: Each button triggers a specific action, transitioning the state machine and
updating the UI.
3. Dynamic Feedback: The TextView displays the current state, reflecting changes in real
time.

Network Communication

Here's a simple demo to demonstrate network communication in an Android application using


Java. We'll use the HttpURLConnection class to fetch data from a REST API and display it in a
TextView.

1. Create a New Android Project

 Minimum SDK: API 26 (your setup).


 Use an Empty Activity template.
2. Add Internet Permission

Add the following permission to your app's AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

3. Define the Layout

Update the activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<Button
android:id="@+id/fetchButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetch Data" />

<TextView
android:id="@+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Result will appear here..."
android:textSize="16sp"
android:padding="16dp"
android:gravity="start|top"
android:scrollbars="vertical" />
</LinearLayout>

4. Implement the Network Communication

In the MainActivity.java file, use a background thread to perform the network operation.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private TextView resultTextView;


private Button fetchButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

resultTextView = findViewById(R.id.resultTextView);
fetchButton = findViewById(R.id.fetchButton);

fetchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fetchData();
}
});
}

private void fetchData() {


// URL of a public API for demonstration
final String apiUrl = "https://jsonplaceholder.typicode.com/posts/1";

// Perform the network request in a background thread


new Thread(new Runnable() {
@Override
public void run() {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("GET");

// Read the response


BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
reader.close();
} catch (Exception e) {
result.append("Error: ").append(e.getMessage());
}

// Update the UI on the main thread


new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
resultTextView.setText(result.toString());
}
});
}
}).start();
}
}
5. Run the App

1. Launch the app on an emulator or device with internet access.


2. Click "Fetch Data" to trigger the network call.
3. The response from the API will be displayed in the TextView.

6. Explanation

 Internet Permission: Required to make network requests.


 Background Thread: Network operations are not allowed on the main thread; hence we
use Thread.
 Handler: Updates the UI after the network request completes.
 API: The demo fetches a sample post from
https://jsonplaceholder.typicode.com/posts/1, a free testing API.

Telephony

Below is a complete demo of how to use the TelephonyManager in Android to showcase


telephony functionalities. The app demonstrates how to fetch basic telephony information, such
as device IMEI, SIM operator name, and network type.

Steps to Implement the Demo

1. Add Required Permissions

You need to declare the necessary permissions in the AndroidManifest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.telephonydemo">

<uses-permission android:name="android.permission.READ_PHONE_STATE" />


<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
android:allowBackup="true"
android:label="Telephony Demo"
android:theme="@style/Theme.AppCompat">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

2. Create the Layout File

Create a layout file (res/layout/activity_main.xml) to display telephony details.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvTelephonyInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Telephony Information"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginBottom="16dp" />

<Button
android:id="@+id/btnFetchInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fetch Telephony Info" />

</LinearLayout>

3. Implement the Logic in MainActivity

Create a Java file (MainActivity.java) and add the following code to fetch telephony details.

import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private static final int PERMISSION_REQUEST_CODE = 100;
private TelephonyManager telephonyManager;
private TextView tvTelephonyInfo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tvTelephonyInfo = findViewById(R.id.tvTelephonyInfo);
Button btnFetchInfo = findViewById(R.id.btnFetchInfo);

// Initialize TelephonyManager
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

btnFetchInfo.setOnClickListener(v -> {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// Request necessary permissions
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);
} else {
fetchTelephonyInfo();
}
});
}

private void fetchTelephonyInfo() {


try {
StringBuilder info = new StringBuilder();

// Fetch telephony details


/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
info.append("IMEI: ").append(telephonyManager.getImei()).append("\n");
}*/
info.append("Network Operator:
").append(telephonyManager.getNetworkOperatorName()).append("\n");
info.append("SIM Operator:
").append(telephonyManager.getSimOperatorName()).append("\n");
info.append("Network Type:
").append(getNetworkType(telephonyManager.getNetworkType())).append("\n");

// Display details
tvTelephonyInfo.setText(info.toString());
} catch (SecurityException e) {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}

private String getNetworkType(int type) {


switch (type) {
case TelephonyManager.NETWORK_TYPE_LTE:
return "LTE (4G)";
case TelephonyManager.NETWORK_TYPE_HSPAP:
return "HSPA+ (3G)";
case TelephonyManager.NETWORK_TYPE_EDGE:
return "EDGE (2G)";
default:
return "Unknown";
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
fetchTelephonyInfo();
} else {
Toast.makeText(this, "Permission is required to fetch telephony
information", Toast.LENGTH_SHORT).show();
}
}
}

4. Run the App

1. Build and run the app on a physical device (not an emulator, as telephony features often require
actual hardware).
2. Click the "Fetch Telephony Info" button.
3. Grant the necessary permissions when prompted.

Output

 The app will display telephony information such as:


o IMEI number
o Network operator name
o SIM operator name
o Network type (e.g., 2G, 3G, 4G)

Notes

1. IMEI Access Restrictions: From Android 10 (API level 29) onward, apps cannot access the IMEI
unless they are system apps or default dialers.
2. Testing: Use a physical device with SIM card inserted, as the emulator may not provide
telephony data.
3. Permissions: Make sure to handle runtime permissions gracefully for a smooth user experience

You might also like