Java Android App Development Course, Linear Layout – LinearLayout

Java Android App Development Course: Linear Layout – LinearLayout

In Android app development, there are various components that make up the user interface (UI), among which LinearLayout is one of the most basic and important layouts. LinearLayout provides the functionality to arrange child views in a linear fashion, either horizontally or vertically. In this course, we will explain the concept, usage, attributes, and examples of LinearLayout in detail.

1. Understanding LinearLayout

LinearLayout is a view group that allows you to arrange child views in a single row. By default, it allows aligning child views in two directions: horizontal and vertical. This allows for quick and easy configuration of simple layouts.

1.1. Direction of LinearLayout

  • Vertical Direction: Child views are arranged from top to bottom.
  • Horizontal Direction: Child views are arranged from left to right.

1.2. Components

LinearLayout has the following characteristics:

  • orientation: Sets the direction of the LinearLayout. (vertical/horizontal)
  • layout_width: Sets the width of the LinearLayout. (match_parent/wrap_content)
  • layout_height: Sets the height of the LinearLayout. (match_parent/wrap_content)
  • gravity: Controls the position of child views.
  • padding: Sets the space between the LinearLayout and the child views.
  • layout_margin: Sets the space between child views and other elements.

2. How to Use LinearLayout

To use LinearLayout, define it in the XML layout file and add other views inside it. The basic structure of a LinearLayout is as follows.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello!" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me!" />

</LinearLayout>

2.1. Example of LinearLayout Settings

Below is an example of a LinearLayout set in a vertical direction. In this example, we will create a simple app using basic UI elements, namely TextView and Button.

<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, LinearLayout example!" 
        android:textSize="24sp"
        android:layout_gravity="center"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click!"
        android:layout_gravity="center"/>

</LinearLayout>

2.2. Horizontal Example

LinearLayout can also be set in horizontal direction. The following code is an example of arranging a button and a text view horizontally.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button: " 
        android:textSize="18sp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"/>

</LinearLayout>

3. Key Attributes of LinearLayout

Now, let’s explain the key attributes you need to know when using LinearLayout.

3.1. orientation

The orientation attribute sets the direction of the LinearLayout. The default value is vertical direction.

android:orientation="vertical"
android:orientation="horizontal"

3.2. layout_gravity

The layout_gravity attribute sets the position of child views. By default, child views will take the full width or height of the LinearLayout.

android:layout_gravity="center"

3.3. weight

The weight attribute is very useful for setting the proportion of child views. This allows you to adjust the space that child views occupy within the LinearLayout.

Below is an example where two buttons are used, sharing an equal proportion.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="First Button"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Second Button"/>

</LinearLayout>

4. Example Application Using LinearLayout

Now, let’s create a simple app that uses LinearLayout. The following example shows an app where the user inputs their name, and upon clicking a button, a welcome message is displayed.

4.1. XML Layout File (activity_main.xml)

<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">

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name"/>

    <Button
        android:id="@+id/buttonGreet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Greet"/>

    <TextView
        android:id="@+id/textViewGreeting"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="24sp"/>

</LinearLayout>

4.2. Java Code (MainActivity.java)

package com.example.helloapp;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText editTextName;
    private Button buttonGreet;
    private TextView textViewGreeting;

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

        editTextName = findViewById(R.id.editTextName);
        buttonGreet = findViewById(R.id.buttonGreet);
        textViewGreeting = findViewById(R.id.textViewGreeting);

        buttonGreet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editTextName.getText().toString();
                String greeting = "Hello, " + name + "!";
                textViewGreeting.setText(greeting);
            }
        });
    }
}

5. Precautions When Using LinearLayout

  • Be cautious not to include too many child views in LinearLayout as it may impact performance. Instead, consider other layouts such as ConstraintLayout.
  • When using layout_weight, the width or height of child views should be set to ‘0dp’.
  • Ensure that the layout properties of views are set correctly to achieve the desired UI results.

6. Conclusion

LinearLayout is one of the most basic yet very useful layouts among Android UI components. In this course, we explored the concept, usage, key attributes, and examples related to LinearLayout. You can effectively configure simple user interfaces using LinearLayout. Furthermore, you can use it alongside various layout options to create more complex and sophisticated UIs.

Now, try creating your own app using LinearLayout! It would be great to practice by combining various UI elements and layout properties.

Java Android App Development Course, Understanding Services

In Android app development, ‘services’ are often an overlooked but important component. Services are designed to perform tasks that need to run for a long time in the background, without a user interface (UI). In this course, we will explore the concept, types, usage, exceptions, and real examples of Android services to understand how they contribute to Android app development.

1. What is a Service?

A service is one of the components of an Android application that performs tasks in the background without user interaction. For example, tasks such as playing music, downloading files, and network communication can be handled by a service. Services can continue to perform tasks even when the user is not using the application.

2. Types of Services

Android services are classified into three types:

  • Started Service: A service that is started within the application and runs continuously until terminated by the system. For example, a music player application can utilize a service while music is playing.
  • Bound Service: A service that is bound to another component (e.g., an Activity) and shares tasks. A bound service is useful when interaction with clients is needed.
  • IntentService: A service that handles requested tasks in the background and automatically stops itself once the tasks are completed. This feature is designed to perform tasks on a single thread.

3. Creating a Service

To create a service, you need to define a class and implement methods to start and stop the service. Here is how to create a basic service:

public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        // Work to be done when the service is created
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Work to be done when the service starts
        return START_STICKY; // Allows the service to restart even after it has been stopped.
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Called when binding to the service. Usually returns null.
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Perform cleanup tasks when the service is destroyed
    }
}

4. Registering a Service

To use a service, you must register it in the Manifest file. Here is an example of service registration:

<service android:name=".MyService"></service>

5. Starting a Service

To start a service, you need to invoke it via an Intent. Here is an example of starting a service:

Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);

6. Stopping a Service

Here is how to stop a service:

stopService(serviceIntent);

7. Using a Bound Service

A bound service helps share specific tasks with an activity. Here is how to implement a bound service:

public class MyBoundService extends Service {
    private final IBinder binder = new LocalBinder();

    class LocalBinder extends Binder {
        MyBoundService getService() {
            return MyBoundService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public String getGreeting() {
        return "Hello from MyBoundService!";
    }
}

An example of an activity calling the bound service is as follows:

private MyBoundService boundService;
private boolean isBound = false;

private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        MyBoundService.LocalBinder binder = (MyBoundService.LocalBinder) service;
        boundService = binder.getService();
        isBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        isBound = false;
    }
};

// Binding the service
Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);

8. Using IntentService

IntentService is a useful component for handling long-running tasks in the background. IntentService processes tasks asynchronously and automatically shuts down when the tasks are complete. Here is an example of implementing IntentService:

public class MyIntentService extends IntentService {
    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        // Write task handling logic here
    }
}

Here is how to call the service:

Intent intent = new Intent(this, MyIntentService.class);
startService(intent);

9. Service Lifecycle

A service goes through the following states and follows a lifecycle:

  • onCreate(): Called when the service is created.
  • onStartCommand(): Called when the service is started.
  • onBind(): Called when the service is bound.
  • onDestroy(): Called when the service is destroyed.

Understanding the service lifecycle is crucial for providing a smooth user experience.

10. Service Optimization

When using services, consider the following optimization tips:

  • Avoid unnecessary use of services. Consider using threads where possible.
  • Regularly check the necessity of services.
  • Properly clean up resources after the service has been terminated.

11. Conclusion

In this course, we explored the concept, types, lifecycle, and implementation methods of services in Android app development using Java. Services are an important element that can enhance user experience and add functionality to applications. Make good use of the advantages of services in real applications to develop even more advanced apps.

If you have any questions or comments, please feel free to leave them in the comments. Thank you!

Java Android App Development Course, Receive Notifications from Server

In Android app development, communication with the server is a very important element, and the ability to deliver information from the server to the client can greatly enhance user experience. In this course, we will explain in detail how to receive notifications sent from the server in an Android app using Java. In this process, we will implement the push notification feature using FCM (Firebase Cloud Messaging).

1. Introduction to FCM (Firebase Cloud Messaging)

FCM is a service provided by Google that is used to deliver push notifications to Android, iOS, and web applications. Through this service, developers can send information even when the user is not running the app. FCM is easy to use and provides a variety of features, which is why it is used in many apps.

2. Setting up FCM

2.1. Creating a Firebase Project

To use FCM, you first need to create a Firebase project.

  1. Log in to the Firebase console (https://console.firebase.google.com/).
  2. Create a new project and enter the project name.
  3. After setting up additional options such as Google Analytics, create the project.

2.2. Registering the Android App

Once the project is created, register the Android app in the Firebase project.

  1. Go to Project Settings in the Firebase console.
  2. Click on the Android icon to register the app.
  3. Enter the package name of the app and also add the SHA-1 certificate fingerprint. (Both debug and release certificates)
  4. Download the google-services.json file and place it in the app folder of the Android project.

2.3. Configuring Gradle

Edit the build.gradle file for basic dependency settings.

dependencies {
    implementation 'com.google.firebase:firebase-messaging:23.0.0'
}

Add the Google services plugin to the project-level build.gradle file.

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

2.4. Configuring AndroidManifest.xml

Add the necessary permissions for Firebase in the AndroidManifest.xml file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pushnotification">
    
    <application 
        ... >
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="default_channel">
        </meta-data>

        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

3. Implementing Server Code

To send notifications using FCM from the server, we will introduce an example of a Node.js server using the Firebase Admin SDK.

3.1. Setting up Node.js Environment

After installing Node.js, install the Firebase Admin SDK.

npm install firebase-admin

3.2. Writing Server Code

const admin = require("firebase-admin");

// Path to Firebase service account key JSON file
const serviceAccount = require("./path/to/serviceAccountKey.json");

// Firebase initialization
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

// Function to send notifications
function sendNotification(token, message) {
    const payload = {
        notification: {
            title: message.title,
            body: message.body,
        },
    };

    admin
        .messaging()
        .sendToDevice(token, payload)
        .then((response) => {
            console.log("Successfully sent message:", response);
        })
        .catch((error) => {
            console.log("Error sending message:", error);
        });
}

// Client device's token and message content
const registrationToken = "Device's registration token";
const message = {
    title: "Push Notification Title",
    body: "This is the body of the push notification.",
};

// Sending notification
sendNotification(registrationToken, message);

4. Implementing Android Client

4.1. Extending FirebaseMessagingService

To receive push notifications, create a class that extends FirebaseMessagingService.

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import android.util.Log;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Handle received notification
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            // Call method to display notification
            showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    private void showNotification(String title, String messageBody) {
        // Implement code to display notification using NotificationCompat.Builder
    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        // Implement code to send the new token to the server
    }
}

4.2. Displaying Notifications

To display notifications, implement a method to create and show notifications using NotificationCompat.Builder.

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

private void showNotification(String title, String messageBody) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    String channelId = "default_channel";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setSmallIcon(R.drawable.ic_stat_ic_notification);

    notificationManager.notify(0, notificationBuilder.build());
}

5. Testing and Debugging

If you have completed all configurations and code, it is now time to conduct a real test. Run the server and try sending a notification using the registration token. Check if the notification is properly received on the client app.

5.1. Checking Receipt of Notifications

If a notification is received, verify that a push notification appears at the top of the app and that a specific activity is executed when the notification is clicked.

5.2. Troubleshooting

If notifications are not being received, check the following:

  • Check if the FCM registration token is valid.
  • Check if the Firebase project settings are correct.
  • Ensure that the necessary permissions and services are added in AndroidManifest.xml.

6. Conclusion

In this course, we learned how to receive notifications sent from the server in an Android app using Java. We confirmed that we can easily implement push notifications using Firebase Cloud Messaging. Consider the potential to expand by adding various features needed for actual applications.

In the future, we will cover various FCM features such as customizing notifications, grouping, and delayed delivery, so please stay tuned. Thank you!

Java Android App Development Course, Positioning with Relative Position – RelativeLayout

In Android app development, various layouts can be used, one of which is RelativeLayout.
RelativeLayout is a layout that allows child views to be positioned relative to each other.
Using this layout, each view can be arranged relative to other views on the screen, making it advantageous for composing complex UIs.

What is RelativeLayout?

RelativeLayout allows child views to be positioned in relation to the specified parent view.
In other words, users can define the position of each view in respect to the direction on the screen.
For example, it is possible to place one view to the right of another view or to align it in the center of the parent layout.

Main Attributes of RelativeLayout

When using RelativeLayout, the main attributes that can be applied to child views are as follows:

  • android:layout_alignParentTop: Aligns to the top of the parent
  • android:layout_alignParentBottom: Aligns to the bottom of the parent
  • android:layout_alignParentLeft: Aligns to the left of the parent
  • android:layout_alignParentRight: Aligns to the right of the parent
  • android:layout_centerInParent: Aligns in the center of the parent
  • android:layout_toLeftOf: Aligns to the left of the specified view
  • android:layout_toRightOf: Aligns to the right of the specified view
  • android:layout_above: Aligns above the specified view
  • android:layout_below: Aligns below the specified view

Advantages of RelativeLayout

Several advantages of using RelativeLayout include:

  • Flexible Layout Modification: It is easy to change the relative positions of existing views, making UI modifications convenient.
  • Ability to Compose Complex Layouts: You can easily create complex UIs compared to other layouts.
  • Performance Improvement: It can improve performance by reducing nested layouts.

Example of Using RelativeLayout

Now let’s learn how to use RelativeLayout through an example that includes views positioned relative to each other.
The example below shows how to arrange a TextView, Button, and ImageView using RelativeLayout.

Step 1: Project Setup

Create a new project in Android Studio,
and modify the provided activity_main.xml file.

Step 2: XML Layout Code

        
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello, World!"
                android:textSize="24sp"
                android:layout_centerInParent="true"/>

            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Click Me"
                android:layout_below="@id/text_view"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="16dp"/>

            <ImageView
                android:id="@+id/image_view"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:src="@drawable/ic_launcher_foreground"
                android:layout_above="@id/button"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="16dp"/>

        </RelativeLayout>
        
    

Step 3: Adding Actions to the Views

After setting up the XML layout, let’s implement actions for those views.
Open the MainActivity.java file and add the code below.

        
        package com.example.myapp;

        import androidx.appcompat.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.TextView;

        public class MainActivity extends AppCompatActivity {

            private TextView textView;
            private Button button;

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

                textView = findViewById(R.id.text_view);
                button = findViewById(R.id.button);

                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        textView.setText("The button has been clicked!");
                    }
                });
            }
        }
        
    

Disadvantages of RelativeLayout

While RelativeLayout is very useful, it has some disadvantages.
Firstly, complex layouts can lead to performance degradation.
Additionally, there is a risk that multiple views may overlap or collide, which can make it visually difficult to see the order of views.

Comparing RelativeLayout with Other Layouts

RelativeLayout has its own strengths and weaknesses compared to other layouts such as LinearLayout and ConstraintLayout.
LinearLayout is suitable for arranging child views vertically or horizontally,
whereas ConstraintLayout offers more complex yet flexible layouts.
It is important to choose the appropriate layout according to the requirements of the user interface.

Conclusion

In this tutorial, we learned how to use RelativeLayout in Android to position views relatively.
RelativeLayout is characterized by its ability to easily set relationships with other views while constructing a UI,
making it suitable for various UI requirements.
Further, unleash your creativity in making your own app!

Java Android App Development Course, Obtaining User Location

User location information is a very important element in Android app development. To provide personalized services to users and enhance the functionality of our app, we need to understand the user’s current location. In this article, we will explain in detail how to obtain user location in Android apps using Java and provide related example code.

1. The Necessity of Acquiring User Location

Let’s explore why obtaining user location is important and what functionalities can be implemented through it. For example:

  • Location-Based Services: You can recommend nearby restaurants, cafes, etc., based on the user’s current location.
  • Navigation Feature: If the user inputs a starting point and a destination, the app can guide them along the optimal route.
  • Location History: You can record places the user has visited and analyze them based on this information.

2. Overview of Android Location Services

In Android, you can use the Location API of Google Play Services to easily obtain user location. This API helps determine the user’s location through information from GPS, Wi-Fi, cellular towers, and more.

3. Project Setup

First, you need to create a new project in Android Studio and add the necessary libraries.

3.1. Gradle File Setup

build.gradle (Module: app)
dependencies {
    implementation 'com.google.android.gms:play-services-location:21.0.1'
}

By adding the above Gradle dependency, you can use the location API through Google Play Services.

3.2. Update AndroidManifest.xml

You need to specify the permissions required to use location information in the AndroidManifest.xml file.

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

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

    <application ...>
        ...
    </application>
</manifest>

4. Requesting Location Permissions

To access the user’s location, you need to request location permissions. On Android 6.0 (API Level 23) and above, permissions must be requested at runtime. Here’s how to request permissions.

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        LOCATION_PERMISSION_REQUEST_CODE);
}

5. Acquiring Location Data

Now that we have obtained permissions, we will write a class to fetch the user’s location. Below is the code to get the user’s location.

public class MainActivity extends AppCompatActivity {

    private FusedLocationProviderClient fusedLocationClient;

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

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // Get latitude and longitude
        getLocation();
    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        
        fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener() {
                @Override
                public void onSuccess(Location location) {
                    // Successfully obtained location
                    if (location != null) {
                        double latitude = location.getLatitude();
                        double longitude = location.getLongitude();
                        Toast.makeText(MainActivity.this, "Latitude: " + latitude + ", Longitude: " + longitude, Toast.LENGTH_LONG).show();
                    }
                }
            });
    }
}

6. Receiving Location Updates

To receive real-time location updates as the user moves, you need to use the LocationRequest object to request location updates. Here’s how to set up location updates.

private void startLocationUpdates() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000); // Update every 10 seconds
    locationRequest.setFastestInterval(5000); // Fastest update interval 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                // Called whenever the location changes
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    Toast.makeText(MainActivity.this, "Latitude: " + latitude + ", Longitude: " + longitude, Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}

7. Stop Location Updates When App is Closed

Continuously tracking a user’s location can drain battery. Therefore, you must stop location updates when a user exits the app.

@Override
protected void onPause() {
    super.onPause();
    fusedLocationClient.removeLocationUpdates(locationCallback);
}

8. Additional Feature: Display Location on Map

Let’s add a feature to display the user’s location on a map. This can be implemented using the Google Maps API.

8.1. Integrating the Map

To use the Google Maps API, you need to generate an API key from Google Cloud Platform and add it to the AndroidManifest.xml.

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="YOUR_API_KEY"/>

8.2. Adding Location Marker to the Map

private GoogleMap mMap;

@Override
protected void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Code to display current location
    LatLng currentLocation = new LatLng(latitude, longitude);
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
}

9. Conclusion and References

In this tutorial, we explored how to obtain user location in Android apps using Java. We covered requesting location permissions, acquiring location data, and methods for location updates. This will allow you to effectively utilize location information, an important component of Android app development.

9.1. References

Important: When handling location information, you must consider user privacy and provide clear explanations to users regarding the use of their location.