Tuesday, June 6, 2023

Learning Journey #6: Brief Exploration of Databases and its Management Systems

 Welcome to the "Learning Journey" series. This space is my personal archive where I share insights and discoveries from my explorations into new tech territories, particularly back-end development and cloud services. As I continue to broaden my tech understanding, I hope this series inspires and contributes to your own learning journey.

1. Understanding the Concept of a Database

A database is a structured repository of data stored electronically. This data, which could pertain to people, products, transactions, or any other entity significant to an individual or a business, is organized to facilitate ease of access, management, and update. Databases serve as the backbone of any data-driven business decision-making process, making them an indispensable part of today's businesses.

2. Database Management Systems (DBMS)

A Database Management System (DBMS) is a specialized software designed to interact with the user, applications, and the database itself to capture, analyze, and manage data. It serves as an interface between the database and end-users, or to other application programs, allowing users to organize, retrieve, and manage data in a systematic way.

3. Diving Deeper into Database Management Systems

DBMSs come in various forms, each with unique strengths, catering to different types of applications:

  • Relational DBMS (RDBMS): The RDBMS organizes data into a set of tables with rows and columns, establishing relationships between different records and tables. These are well-suited for applications needing structured data management and are the most popular type of DBMS. Examples include MySQL, Oracle, and PostgreSQL. However, RDBMS may struggle with unstructured data, making them less suited for handling large volumes of such data.
  • Object-Oriented DBMS (OODBMS): This type of DBMS organizes data into objects instead of tables. The objects and their relationships form the core data model, making this DBMS type useful for applications handling complex, often unstructured, data like multimedia content or scientific data.
  • NoSQL DBMS: NoSQL DBMS is designed with scalability and performance in mind. They do not require fixed table schemas and usually steer clear of join operations, allowing them to handle large volumes of structured, semi-structured, and unstructured data. They are commonly used in big data and real-time web applications. Examples include MongoDB, Cassandra, and Redis.

4. An Overview of Various Types of DBMS: Hierarchical, Network, Relational, Object-Oriented, Object-Relational

  • Hierarchical DBMS: Here, data is represented in a tree-like structure with a single root, and all other data is linked to it. Each child record has only one parent.
  • Network DBMS: This type of DBMS enhances the hierarchical DBMS by allowing each record to have multiple parent and child records, forming a web-like structure of networked records.
  • Relational DBMS (RDBMS): The most prevalent DBMS type, it stores data and their relationships in tables.
  • Object-Oriented DBMS (OODBMS): This DBMS allows creating objects, instances of classes, which can include both data and methods.
  • Object-Relational DBMS (ORDBMS): This type merges features of both relational DBMS and object-oriented DBMS, offering enhanced versatility.

5. SQL: Commanding the Realm of Data Manipulation

SQL, or Structured Query Language, is a standard language to interact with databases, predominantly those adhering to the relational model. It allows for a diverse range of

tasks such as creating, retrieving, updating, and deleting data.

  • Creating data: The CREATE command is used to construct a database or a table. The INSERT command is used to populate data into a table.
  • Reading data: The SELECT command retrieves data from a database. It allows fetching data from specific columns, multiple tables simultaneously using a JOIN operation, or with specific characteristics using a WHERE clause.
  • Updating data: The UPDATE command modifies data in a table. Typically, this command is used with a WHERE clause to specify the exact data to modify.
  • Deleting data: The DELETE command removes data from a table, typically used with a WHERE clause to specify the data to be removed.
  • Altering structure: The ALTER command modifies the structure of the database, allowing adaptations as per changing requirements.

Here's a quick illustration of how you might use SQL to create a table, add data to it, and then retrieve that data:

CREATE TABLE Employees (
    EmployeeID int,
    FirstName varchar(255),
    LastName varchar(255),
    Position varchar(255)
);

INSERT INTO Employees (EmployeeID, FirstName, LastName, Position)
VALUES (1, 'John', 'Doe', 'Software Engineer');

SELECT * FROM Employees WHERE Position = 'Software Engineer';

6. An Introduction to NoSQL

NoSQL is a broad category of database management systems that do not use SQL as their primary data access language. These databases, tailored for specific data models, exhibit flexible schemas for building modern applications.

NoSQL databases are renowned for their ability to manage large volumes of structured, semi-structured, and unstructured data. They excel in areas where traditional RDBMS might falter, offering performance, scalability, and flexibility

Friday, June 2, 2023

Learning Journey#5. From Foundation to Future: Cloud Computing as a Career Pathway

Welcome to the "Learning Journey" series. This space is my personal archive where I share insights and discoveries from my explorations into new tech territories, particularly back-end development and cloud services. As I continue to broaden my tech understanding, I hope this series inspires and contributes to your own learning journey.

Introduction

In the vast expanse of the digital universe, the concept of cloud computing has become an intrinsic part of our daily lives. Silently powering the technology we rely on, from our emails to the multitude of apps we use, cloud computing has become a cornerstone of modern technological advancements. This post aims to unpack the concept of the cloud, narrate its evolutionary journey, and shine a light on the emerging role of cloud engineers.


Grasping the Concept of Cloud

At its core, cloud computing is the delivery of computing services such as servers, storage, databases, networking, software, analytics, and intelligence over the internet, known as “the cloud.” It allows businesses to avoid the capital expenditure of owning their own infrastructure or data centers, instead renting these services as needed from a cloud service provider.

The three core types of cloud services include Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS). Below is a more detailed look at these models:

Service Type Description Example
IaaS (Infrastructure as a Service) IaaS provides the infrastructure such as virtual machines and other resources like virtual-machine disk image library, block and file-based storage, firewalls, load balancers, IP addresses, virtual local area networks etc. These resources are made available to the customer as service. Customers can avoid the capital outlay for hardware and purchase IaaS based on consumption, similar to electricity or other utility billing. Examples: AWS EC2, Rackspace, Google Compute Engine (GCE), Digital Ocean
PaaS (Platform as a Service) PaaS provides the runtime environment for applications, development and deployment tools, etc. The resources can be used to run applications designed in a specific programming language. This eliminates the need to manage underlying infrastructure (usually hardware and operating systems) and allows developers to focus on the deployment and management of their applications. Examples: AWS Elastic Beanstalk, Windows Azure, Heroku, Force.com, Google App Engine
SaaS (Software as a Service) In the SaaS model, cloud providers install and operate application software in the cloud and users access the software from cloud clients. The applications are made available over a network, typically the Internet. Cloud providers manage the infrastructure and platforms that run the applications. Examples: Google Apps, Salesforce, Dropbox, MailChimp, ZenDesk

The Evolution and Expansion of Cloud Computing

Over the past decade, cloud computing has evolved from a promising business concept to an essential business tool. Today, businesses are drawn to the cloud not just for cost savings and scalability, but also as a platform for innovation and business transformation. According to recent data, the worldwide public cloud services market is expected to reach $455.2 billion in 2022, a significant increase from $332.3 billion in 2021. This growth is mainly driven by the widespread adoption of cloud computing across businesses of all sizes, seeking the benefits of cost savings, scalability, and flexibility. The leading providers of public cloud services are Amazon Web Services (AWS) with a market share of over 33%, Microsoft Azure with over 18%, and Google Cloud Platform (GCP) with over 10%.

Year Event
1960 The concept of an "intergalactic computer network" was introduced by J.C.R. Licklider, who enabled the development of ARPANET.
1969 ARPANET, the predecessor to the internet, was developed.
1970 The concept of virtual machines became popular, effectively separating the hardware from the operating system.
1990 Telecommunication companies started offering virtualized private network connections.
1999 Salesforce.com started delivering applications to users using a simple website. This paved the way for software firms to deliver applications over the internet.
2002 Amazon launched Amazon Web Services (AWS), providing a suite of cloud-based services including storage, computation, and even human intelligence.
2006 Amazon launched its Elastic Compute cloud (EC2) as a commercial web service that allows small companies and individuals to run their own computer applications on a commercial web service.
2008 Google launched Google App Engine in Beta.
2009 Rackspace launched Cloud Servers with a pay-as-you-go pricing model.
2010 Microsoft launched Azure, its cloud computing platform. VMware launched vCloud Director, one of the first cloud management platforms.
2011 IBM launched the IBM SmartCloud framework to support Smarter Planet. Salesforce.com launched Heroku for developing and deploying web applications.
2012 Oracle announced the Oracle Cloud. Amazon launched AWS Elastic Beanstalk, making it easy to deploy and scale web applications on AWS.
2013 Google launched Google Compute Engine and App Engine Flex, allowing developers to run applications on Google App Engine using a variety of languages.
2014 Microsoft announced Azure Machine Learning on the Azure cloud platform and launched Azure App Service for developing applications in various languages.
2016 AWS Lambda was announced, allowing developers to run code for applications or backend services without having to provision or manage servers.
2017 Google announced Google Cloud Functions, which allows functions as a service for event-driven serverless computing.
2019 Microsoft announced the general availability of Azure Functions, their own function as a service platform.
2020 AWS, Azure, and Google Cloud continued to release new services and features, furthering the reach and capabilities of cloud computing.


The Rise of the Cloud Engineer

With the growing adoption of cloud technologies, the demand for skilled cloud engineers is on the rise. A cloud engineer is an IT professional responsible for any technological tasks associated with cloud computing, including design, planning, management, maintenance, and support.

There are several specialties within cloud engineering — cloud software engineers, cloud systems engineers, cloud

network engineers, and cloud security engineers. All these roles require a comprehensive understanding of cloud computing principles and modern software development practices.

Cloud engineers need a strong grasp of programming languages, web development, database management, and networking. Furthermore, they should have a deep understanding of top cloud service platforms, their services, architectural best practices, and how to design, deploy, and service workloads on these platforms.

Pathways in Cloud Engineering

There are a multitude of pathways available to cloud engineers. With the expanding roles and responsibilities, one can opt to specialize as a Cloud Architect, Cloud Software Engineer, Cloud Security Engineer, Cloud Systems Engineer, or Cloud Network Engineer, each role demanding a unique skill set and knowledge base.

Resources for Aspiring Cloud Engineers

For individuals interested in diving into the world of cloud engineering, there are a host of resources available. Online learning platforms like Coursera, Udacity, and edX offer a range of courses in cloud computing and related fields. Industry certifications such as AWS Certified Solutions Architect, Google Professional Cloud Architect, or Microsoft Certified: Azure Solutions Architect Expert are also beneficial in accelerating your cloud engineering career.

Conclusion

The journey of cloud computing from a fledgling idea to a robust platform for innovation has been extraordinary. The role of a cloud engineer, while challenging, offers a rewarding career in a field that continues to grow and evolve. The cloud is not just a technological revolution, it's an opportunity to redefine the digital landscape.

Join me in my next post where we delve deeper into the specifics of Amazon Web Services (AWS) and Microsoft Azure, their unique offerings, and the intricacies of their services. As the cloud continues to evolve, so will we. Until then, keep exploring and keep learning!

Wednesday, May 31, 2023

Learning Journey#4. Understanding REST APIs: for Beginners

Welcome to the "Learning Journey" series. This space is my personal archive where I share insights and discoveries from my explorations into new tech territories, particularly back-end development and cloud services. As I continue to broaden my tech understanding, I hope this series inspires and contributes to your own learning journey.

Introduction

https://uxwing.com/rest-api-icon

An API, or application programming interface, is a way for two pieces of software to communicate with each other. REST, or Representational State Transfer, is a set of architectural principles for designing APIs. REST APIs are the most common type of API and are employed in a wide array of applications, such as web browsers, mobile apps, and server-to-server communication.

What is a REST API?

A REST API is an API that adheres to the REST architectural principles. These principles dictate how an API should be designed, including how requests should be formulated, how responses should be formatted, and how errors should be managed.

The core principles of REST include:

REST API Principle Description
Stateless The server should not store any state about the client, meaning that each client request should be independent of previous ones.
Client-server The client and server should function independently of each other, implying that the client need not know anything about the server, and vice versa.
Cacheable The server should permit clients to cache responses to improve performance by decreasing the number of server requests.
Layered system The API should be designed as a layered system, meaning that it should be divided into different layers, each offering a specific set of functionalities.
Uniform interface The API should use a uniform interface, implying that all API requests should use the same methods and formats.


Why Use REST APIs?

REST APIs offer several advantages:

  • Scalability: Due to their stateless nature and layered system, REST APIs can effectively support an increasing number of requests, making them suitable for large, growing applications.
  • Simplicity: The ease of use of REST APIs makes them a preferred choice for developers, especially those new to APIs.
  • Performance: REST APIs can enhance efficiency by using techniques like caching to reduce server requests.
  • Modifiability: REST APIs are adaptable and can be easily changed to accommodate the evolving needs of your application.

Components of a REST API

A REST API is composed of several elements:

  • Base URL: The base URL is the starting point for all API requests.
  • Path: The path in the URL identifies the specific resource that you are trying to access.
  • HTTP method: The HTTP method denotes the type of request you're making. The most common HTTP methods are GET, POST, PUT, and DELETE.
  • Headers: Headers supply additional information about the request, such as the content type of the request or the authorization credentials.
  • Query parameters: Query parameters are utilized to filter or sort the results of a request.

Detailed explanations for these components can be found in resources like the Mozilla Developer Network.

REST APIs vs. Other API Styles

API styles like SOAP and GraphQL also exist. SOAP is a more intricate API style than REST and uses XML to format requests and responses, potentially increasing its complexity. GraphQL is a newer API style designed to offer more flexibility than REST. It enables you to request specific data from the server, which can enhance performance. A comprehensive comparison between these styles, however, would be a topic for a separate, more in-depth post.


Common HTTP Methods in REST APIs

REST APIs typically use four basic HTTP methods for interaction with resources:

  • GET: Retrieves a representation of a resource without modifying it. GET requests can be cached and bookmarked.

  • POST: Sends data to the server to create a new resource. The server generates the unique identifier for the new resource.

  • PUT: Updates a known resource. It replaces the entire resource with the new content.

  • DELETE: Deletes a specified resource.

In practice, these methods are used to construct a complete API that can create, read, update, and delete resources – commonly referred to as a CRUD interface.

REST API - Author: Seobility - License: CC BY-SA 4.0
https://www.seobility.net/en/wiki/REST_API

JSON in REST APIs

JSON (JavaScript Object Notation) is a common format for sending and receiving data in a REST API. JSON provides a simple, text-based way to represent structured data. It is human-readable, and easy for both machines and humans to write and parse. Here's a simple example of what a JSON response might look like:

{
  "name": "John Doe",
  "email": "john@example.com",
  "id": 123
}

In this example, the server is responding with a JSON object that represents a user, including their name, email, and id.


Building Your First REST API

If you're new to REST APIs, start by building a simple one. Many frameworks, such as Express.js, can assist in creating REST APIs. After building a basic API, you can delve deeper into REST architectural principles and design more complex APIs.

Common Tools for Interacting with REST APIs

Numerous tools can be used to interact with REST APIs. Some popular ones include:

  • Postman: This popular tool is used for testing and interacting with REST APIs. It allows you to send requests to the API, view the responses, and debug errors.
  • curl: curl is a command-line tool that can be used to send requests to REST APIs. It is a suitable choice for developers who wish to automate REST API testing.

Conclusion

REST APIs are powerful tools that facilitate the interaction between different applications and services. Understanding the basics of REST APIs enables you to build more robust and flexible applications. The journey of learning and implementing REST APIs may seem challenging at first, but with the right resources and consistent practice, you can become proficient and leverage their power in your projects.

Friday, May 26, 2023

Learning Journey #3. Spring Framework

Welcome to the "Learning Journey" series. This space is my personal archive where I share insights and discoveries from my explorations into new tech territories. we're going to dive into a game-changer in the world of Java-based enterprise applications: the Spring Framework.


1. Background: The Evolution of Spring

At the beginning of enterprise Java, EJB (Enterprise JavaBeans) was the dominant choice for building robust enterprise applications. However, the complexities of EJB did not blend well with modern architectural trends, which required a simpler, more lightweight solution. This need led to the birth of the Spring Framework.

Over time, Spring has evolved from a remedial framework to combat the complexities of EJB to a comprehensive suite of projects addressing a wide array of enterprise Java needs. It now includes everything from a security framework to a full-fledged MVC web application framework.

2. Understanding the Spring Framework

The Spring Framework is a comprehensive, yet lightweight solution for building enterprise applications in Java. It emerged as a response to the intricate nature of enterprise application development, providing a simpler, more flexible, and modular approach.

3. The Pillars of the Spring Framework

The Spring Framework is built upon several key principles:

  • Inversion of Control (IoC): Also known as Dependency Injection (DI) and Dependency Lookup (DL), IoC shifts the responsibility of managing dependencies from the programmer to the framework itself. This results in more modular and testable code.
  • Plain Old Java Object (POJO): Spring advocates for the use of POJOs, which are straightforward, reusable, and testable Java objects that aren't bound to a specific framework.
  • Aspect-Oriented Programming (AOP): AOP is a programming paradigm that aims to increase modularity by separating cross-cutting concerns. It does this by breaking down the program logic into distinct parts (called "aspects"). For example, logging is a concern that cuts across multiple methods, classes, and layers in an application. Using Spring AOP, you can separate this logging concern from the core business logic, making the code cleaner and easier to maintain.
  • Model-View-Controller (MVC): The Spring MVC web application framework provides a clear separation of concerns among the roles in the application, and is a highly flexible, robust alternative to traditional heavyweight frameworks.
  • Modularity: The modularity of Spring allows developers to use only the components they require, instead of being forced to adopt the entire framework.

4. Inside the Spring Framework Architecture

https://docs.spring.io/spring-framework/docs/3.0.x/spring-framework-reference/html/overview.html

The Spring Framework has a layered architecture comprising various well-structured modules like Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, and Test. A detailed diagram of the Spring Framework architecture can help visualize how different modules work together and allow developers to keep their applications lightweight and optimized.

5. Introducing Spring Boot

Spring Boot is an extension of the Spring Framework, designed to simplify the initial setup and configuration of a new Spring project. With its opinionated approach to the Spring platform and third-party libraries, Spring Boot allows developers to start projects quickly, making it an ideal choice for developing microservices.

6. Java EE vs. Spring Boot: A Comparative Look

Feature Java EE Spring Boot
Startup Time Can be lengthy due to application server startup Extremely fast, ideal for microservices
Configuration XML based, can be verbose Convention over configuration, minimal setup
Dependency Injection Uses CDI Uses Spring's Dependency Injection
Data Access Uses JPA Supports JPA and Spring Data
Flexibility Bound to the specifications Highly customizable
Learning Curve Steeper, requires understanding of various specifications Easier to start with due to auto-configuration and embedded server
Community and Support Supported by various vendors, larger community Robust community support, primarily driven by Pivotal
Packaging and Deployment Usually requires an application server for deployment Standalone applications with embedded servers, easy to deploy
Microservices Support Can be more complex to setup Built with microservices in mind

Java EE (Enterprise Edition) provides a standardized API and runtime environment for building and running large-scale, multi-tiered, scalable, reliable, and secure network applications. Despite the comprehensive solution offered by Java EE, Spring Boot brings a more

lightweight, flexible approach, and has managed to simplify many of the complexities that exist in Java EE. Thus, Spring Boot has gained significant popularity among developers looking for a streamlined and efficient development process.

In the next part of my Learning Journey, I will delve into more interesting features. Stay tuned!

Thursday, May 25, 2023

Daily#14. Understanding JVM, Dalvik, and ART: The Engines Behind Java and Android Applications

Introduction

Developing applications in Java or for the Android platform requires an understanding of the runtime environments where these applications run. A runtime environment refers to the state of the system when a program is executed. It includes the settings, libraries, and other supporting infrastructure that the system provides to the program. Understanding runtime environments is crucial as they dictate how a program will behave when executed. Java Virtual Machine (JVM) is the original runtime environment for Java, but is not used on Android. Dalvik and ART, on the other hand, are newer runtime environments that were specifically designed for Android. This post will guide you through the functionality of JVM, Dalvik, and ART.

What is JVM?

The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to run a Java program. Here are the key characteristics of JVM:

https://en.wikipedia.org/wiki/Java_virtual_machine






  • Platform Independence: Java's "write once, run anywhere" principle is enabled by JVM's ability to interpret Java bytecode into the machine code of the host device.
  • Memory Management: JVM handles object allocation and de-allocation in memory through a process called garbage collection. Garbage collection is an automatic memory management scheme that reclaims the heap space occupied by objects that are no longer in use by the program.
  • Execution of Bytecode: JVM interprets and executes the compiled Java bytecode line by line, translating it into the machine code that the host device can understand.

What is Dalvik?

Dalvik is a virtual machine designed specifically for Android and was the default Android runtime until Android 5.0 (Lollipop), after which it was replaced by Android Runtime (ART). Here are the key characteristics of Dalvik:

  • Designed for Devices with Limited Resources: Dalvik was built keeping in mind the constraints of device resources like memory and battery. It does so by converting .class files, which are relatively heavy, into .dex (Dalvik Executable) format. The .dex files are much lighter and optimized for minimal memory footprint.
  • Executes .dex Files: Java code in Android applications is converted into .dex files, which are more memory efficient than traditional .class files used by JVM.
  • Register-Based: Unlike the JVM, which is stack-based, Dalvik is a register-based machine, typically leading to fewer instructions, but more complex ones.

What is ART?

https://source.android.com/docs/core/architecture


The Android Runtime (ART) is the current runtime used by Android applications, introduced as a replacement for Dalvik in Android 5.0 (Lollipop). ART is still under development, and new features and optimizations are being added all the time. Here are the key characteristics of ART:

  • Ahead-of-Time (AOT) Compilation: Unlike Dalvik, which used Just-In-Time (JIT) compilation, ART performs AOT compilation. This means that the bytecode is compiled into machine code upon app installation, leading to improved performance.
  • Garbage Collection: ART implements improved garbage collection over Dalvik, reducing pauses and overhead during application runtime.
  • Backwards Compatibility: ART can execute apps targeted for the Dalvik runtime by translating the Dalvik bytecode. This ensures older applications can still run on newer versions of Android, preserving the vast library of Android apps across updates.

JVM vs. Dalvik vs. ART: Key Differences

Here's a table that shows the key differences between JVM, Dalvik, and ART:

Feature JVM Dalvik ART
Execution Runs .class files Runs .dex files Compiles .dex files
Garbage Collection Generational GC Concurrent GC Improved GC
Performance Optimization Just-In-Time (JIT) Initially interpreted, later included JIT Ahead-Of-Time (AOT) compilation
Application Isolation Each app runs on separate JVM Multiple apps run concurrently within separate Dalvik instances Each app runs on separate ART instance


All three—JVM, Dalvik, and ART—have been designed with very different goals and optimizations in mind. Understanding the workings of these VMs can provide valuable insights into optimizing your Java and Android application's performance. I hope you found this comparison informative! Feel free to leave comments or ask questions below. Stay tuned for more informative posts!

Tuesday, May 23, 2023

Daily #13: Diving Deeper Into Android Events: Location Tracking, Screen On/Off, Orientation Changes, Battery Status, Incoming Calls/SMS, and Pedometer

Welcome back to our daily tech series! Today, we're delving deeper into some essential Android events and features that you can implement in your apps to enhance user experience. Let's get started.

Location Tracking

Android provides the LocationManager for accessing system location services. This lets your app request location updates from GPS or network providers. Here's an example:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = locationManager.getBestProvider(criteria, true);

LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        // Do something with the location.
    }
    // Override other methods as needed
};

// Request location updates
locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);

For more information, visit the Android developer's guide on location.

Screen On/Off

Android sends broadcast intents (Intent.ACTION_SCREEN_ON and Intent.ACTION_SCREEN_OFF) when the device's screen turns on and off. You can create a BroadcastReceiver to listen for these changes:

BroadcastReceiver screenStateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
            Log.i(TAG, "Screen turned on");
        } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
            Log.i(TAG, "Screen turned off");
        }
    }
};

More details are available in the official Android developer guide on Broadcasts.

Orientation Changes

When a device's orientation changes, the system destroys and recreates the visible activity. You can handle such changes in your activity's lifecycle methods, particularly onConfigurationChanged:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Log.i(TAG, "Landscape");
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Log.i(TAG, "Portrait");
    }
}

See the Android developer's guide on handling runtime changes for more information.

Battery Level and Charging Status

By monitoring the battery level and charging status, your app can adapt its behavior to maintain a good user experience even under low battery conditions. Android broadcasts Intent.ACTION_BATTERY_CHANGED when the battery level or charging state changes:

BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                             status == BatteryManager.BATTERY_STATUS_FULL;
        // Do something with this info
    }
};

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(batteryReceiver, ifilter);

More details can be found in the [Android developer's guide on monitoring the battery level and charging state](https://developer.android

.com/training/monitoring-device-state/battery-monitoring).

Incoming Calls/SMS

If your app needs to be aware of incoming calls or SMS messages, Android provides TelephonyManager and PhoneStateListener:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
    public void onCallStateChanged(int state, String incomingNumber) {
        if (state == TelephonyManager.CALL_STATE_RINGING) {
            Log.i(TAG, "Incoming call: " + incomingNumber);
        }
    }
};
telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

See the Android developer's guide on intercepting phone calls and receiving SMS messages for more information.

Pedometer

The Android platform provides a Step Counter sensor to track the number of steps the user has taken since the last device reboot. Here's a basic example:

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
    sensorManager.registerListener(new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            int steps = (int)event.values[0];
            // Do something with this info
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // Handle accuracy changes
        }
    }, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
    Log.e(TAG, "Step Counter sensor not available!");
}

For more details, refer to the official Android Sensor documentation.

Network Changes

Keeping track of the network state is crucial for apps with online functionalities. You can use the ConnectivityManager to listen to network changes and adapt your app accordingly. For more details on handling network changes, refer to this post: "Daily#6 Understanding and Using ConnectivityManager".

Understanding and implementing these features can significantly enhance your app's functionality and user experience. Happy coding!

Monday, May 22, 2023

Daily#12: Networking in Android - Understanding ConnectivityManager and Network APIs

Hello everyone! Today, let's delve into Android's networking capabilities. We'll concentrate on the ConnectivityManager class and the Network API, both of which provide applications the means to specify a network interface for communication with external networks.

ConnectivityManager and bindProcessToNetwork

Let's start with ConnectivityManager, a class that provides network connectivity status and updates applications when this connectivity changes. One crucial method in this class is bindProcessToNetwork.

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = ... // Your desired network
cm.bindProcessToNetwork(network);

Using bindProcessToNetwork, an application can dedicate a Network object for its network traffic. Therefore, all traffic from the application will be routed over this specified network.

Acquiring a Network Object

You may be wondering how to get a Network object to use with bindProcessToNetwork. There are several ways to do so:

  1. NetworkCallback (refer : previous post)
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
   @Override
   public void onAvailable(Network network) {
      // Use network object here
   }
};
  1. getActiveNetwork
Network activeNetwork = cm.getActiveNetwork();

With a Network object at hand, we can utilize the Network class's methods to control network traffic.

Network and its methods: bindSocket, getSocketFactory, openConnection

The Network class represents a network interface. It has several key methods:

  1. bindSocket(Socket socket): Binds the specified Socket to this Network, ensuring that all data traffic from the Socket will be sent over this Network.
Network network = ... // Your Network
Socket socket = new Socket();
network.bindSocket(socket);
OutputStream os = socket.getOutputStream();
os.write("Hello, world!".getBytes());
os.close();
socket.close();
  1. getSocketFactory(): Returns a SocketFactory that creates Sockets bound to this Network.
SocketFactory sf = network.getSocketFactory();
Socket socket = sf.createSocket("example.com", 80);
OutputStream os = socket.getOutputStream();
os.write("Hello, world!".getBytes());
os.close();
socket.close();
  1. openConnection(URL url): Opens a URLConnection over this network. It can be used to create an InputStream or OutputStream.
URL url = new URL("http://example.com");
URLConnection connection = network.openConnection(url);
InputStream is = connection.getInputStream();
// Use InputStream here
is.close();

By utilizing these methods, an application can explicitly send network traffic over a particular network interface, ensuring that data is routed correctly.

Remember, this is just a brief dive into Android's vast networking capabilities. There are many more classes and methods to explore. As always, refer to the official Android documentation for more details and don't stop experimenting!

Learning Journey #6: Brief Exploration of Databases and its Management Systems

  Welcome to the "Learning Journey" series. This space is my personal archive where I share insights and discoveries from my explo...