Java Android App Development Course, Creating a Battery Information App

In this tutorial, we will learn how to create an app that displays battery information in an Android environment using Java.
Battery usage is a very important factor in modern smartphones, and users want to check their battery status in real-time.
This app will allow users to check battery status, charging status, battery level, and more.

1. Creating a Project

Open Android Studio and create a new project. Select the “Empty Activity” template and set up the project name, package name,
storage location, etc., and then click “Finish”. A basic Android project has been created.

2. Modifying AndroidManifest.xml

You need to add the necessary permissions to the manifest file to access battery information.
Open the project’s AndroidManifest.xml file and modify it as follows.

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

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

            <application
                android:allowBackup="true"
                android:icon="@mipmap/ic_launcher"
                android:label="@string/app_name"
                android:roundIcon="@mipmap/ic_launcher_round"
                android:supportsRtl="true"
                android:theme="@style/Theme.AppCompat.Light.NoActionBar">

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

3. Creating Layout File

Modify the activity_main.xml file to define the app’s UI.
Add TextViews to display battery information to the user.

        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            
            <TextView
                android:id="@+id/batteryLevel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Battery Level: 100%"
                android:textSize="24sp"
                android:layout_centerInParent="true"/>

            <TextView
                android:id="@+id/batteryStatus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Charging Status: Charging"
                android:textSize="18sp"
                android:layout_below="@id/batteryLevel"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>
    

4. Modifying MainActivity.java

Now it’s time to implement the logic to obtain battery information. Open the MainActivity.java file and
add the code to get battery status and level.

        package com.example.batteryinfo;

        import android.content.BroadcastReceiver;
        import android.content.Context;
        import android.content.Intent;
        import android.content.IntentFilter;
        import android.os.BatteryManager;
        import android.os.Bundle;
        import android.widget.TextView;

        import androidx.appcompat.app.AppCompatActivity;

        public class MainActivity extends AppCompatActivity {

            private TextView batteryLevelTextView;
            private TextView batteryStatusTextView;

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

                batteryLevelTextView = findViewById(R.id.batteryLevel);
                batteryStatusTextView = findViewById(R.id.batteryStatus);

                registerBatteryReceiver();
            }

            private void registerBatteryReceiver() {
                IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                registerReceiver(batteryReceiver, filter);
            }

            private final BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                    int batteryPct = (int) ((level / (float) scale) * 100);

                    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                    String statusString;
                    switch (status) {
                        case BatteryManager.BATTERY_STATUS_CHARGING:
                            statusString = "Charging";
                            break;
                        case BatteryManager.BATTERY_STATUS_DISCHARGING:
                            statusString = "Discharging";
                            break;
                        case BatteryManager.BATTERY_STATUS_FULL:
                            statusString = "Fully Charged";
                            break;
                        default:
                            statusString = "Unknown";
                            break;
                    }

                    batteryLevelTextView.setText("Battery Level: " + batteryPct + "%");
                    batteryStatusTextView.setText("Charging Status: " + statusString);
                }
            };

            @Override
            protected void onDestroy() {
                super.onDestroy();
                unregisterReceiver(batteryReceiver);
            }
        }
    

5. Running the App

Now all the code is ready. Click the run button in Android Studio to run the app on an emulator or a real device.
When the app is running, battery level and status information will be displayed in real-time. This will be very important during the development process.

6. Implementing Additional Features

In addition to displaying basic battery information, we will implement a few additional features. For example,
we can add a battery overcharge prevention notification feature. This would send a notification to the user when the battery level reaches a certain level.

7. Implementing Overcharge Prevention Notification

        // Code added to MainActivity.java
        private void checkBatteryLevel(int level) {
            if (level > 80) {
                showNotification("Battery Overcharge Warning", "Battery level has exceeded 80%.");
            }
        }

        private void showNotification(String title, String message) {
            // Implement notification related code
        }
    

8. Improving User Interface

Various design elements can be added to improve the app’s UI. For example, you can use ConstraintLayout to create more complex layouts,
or utilize Material Design elements to implement a more modern UI.

Conclusion

In this tutorial, we learned essential skills for Android app development using Java. Through the process of creating a battery information app,
we gained a deep understanding of the structure of Android apps, user interfaces, and data handling.
Building upon this foundation, you can add more features or explore other topics to enhance your Android app development skills.

Thank you! If you have any additional questions or feedback, please leave a comment.

Java Android App Development Course, Binding Service

In Android development, a service is a component that runs in the background, performing work independently of the user interface (UI). Services can handle long-running tasks, providing a better experience for users. Services are divided into started services and bound services, and this tutorial will focus primarily on bound services.

1. What is a Bound Service?

A bound service provides a way for clients (mainly activities) to interact with it. The client can bind to the service to call methods or send data. This allows for an effective way to perform complex tasks and reflect them directly in the UI.

2. Characteristics of a Bound Service

  • Interaction with Clients: A bound service facilitates communication between the client and the service by allowing the client to call methods in the service.
  • Lifecycle: The lifecycle of a bound service can vary depending on the lifecycle of the client. The service starts when the client binds to it, and it can stop when the client unbinds.
  • Multi-client Support: Multiple clients can bind to the same service simultaneously, allowing multiple activities or fragments to share the service.

3. Implementing a Bound Service

To create a bound service, you need to create a service class and provide a pair of methods to manage the connection with clients.

3.1 Creating the Service Class

First, create a service class that will be used as a bound service. This class should extend Service and implement the onBind() method. Here is a simple example:

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

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

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

    public String getRandomNumber() {
        Random random = new Random();
        return String.valueOf(random.nextInt(100));
    }
}

In the code above, the LocalBinder class serves to connect the service and the client. The getService() method allows the client to access the service instance.

3.2 Binding the Service in the Client Class

To bind to the service, the client (activity) must implement the ServiceConnection interface.

public class MainActivity extends AppCompatActivity {
    MyBoundService boundService;
    boolean isBound = false;

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

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

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, MyBoundService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
    }
}

The code above binds to the service in the onStart() method and unbinds in the onStop() method. The connection object, which implements the ServiceConnection interface, defines the code to execute when the service is connected.

3.3 Calling Service Methods

Now the client can call the service methods. Below is an example code snippet that calls a service method to retrieve a result on a button click event.

Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (isBound) {
            String randomNumber = boundService.getRandomNumber();
            Toast.makeText(MainActivity.this, "Random Number: " + randomNumber, Toast.LENGTH_SHORT).show();
        }
    }
});

4. Use Cases for Bound Services

Bound services can be used effectively in various scenarios. For example:

  • Interaction between a music playback service and the UI in a music player app
  • Data transfer between a service handling network requests and the UI
  • Data transmission between a service performing long-running tasks and clients

5. Precautions

There are several precautions when using bound services:

  • Avoid performing long tasks directly on the UI thread. Instead, use AsyncTask or Handler to perform tasks asynchronously.
  • Always ensure that the client is bound to the service to manage the lifecycle between the client and service.
  • Keep service methods as short as possible to facilitate smooth interaction with the client.

Conclusion

Bound services are a very useful feature in Android development. They provide a better experience for users through smooth data transfer and interaction between clients and services. I hope this tutorial has helped you understand the basic concepts and implementation methods of bound services.

This concludes the tutorial on bound services. If you have any additional questions or comments, feel free to leave them in the comments!

Java Android App Development Course, Creating an Intro Screen for a Messenger App

The messenger app is an essential element of modern communication. In this course, we will specifically explore how to create an intro screen that can be used in Android apps.

1. Importance of the Intro Screen

The intro screen is the first screen that users encounter when starting the app. It serves to briefly introduce the brand image, usage instructions, features, etc. It can leave a strong first impression on users and greatly help in building trust in the app. Additionally, the intro screen is a useful way to utilize the waiting time while the app is loading.

2. Preparing the Project

Create a new project using Android Studio. The following settings can be applied:

  • Project Name: MessengerApp
  • Package Name: com.example.messengerapp
  • Language: Java
  • Minimum API Level: API 21 (Lollipop)

When you create a new Android project with the above settings, the MainActivity.java and activity_main.xml files are generated by default.

3. Designing the Intro Screen

The design of the intro screen can enhance user experience. We will design the intro screen using a simple background image and logo.

3.1 Creating the Layout File

Create an intro_activity.xml file in the res/layout folder and write the following:

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

    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/logo" />

</RelativeLayout>

The above XML code will place the logo in the center of the screen. The logo image should be added to the res/drawable folder.

4. Creating the Intro Screen Activity

Now we will create the Activity that displays the intro screen. Create a new Java file named IntroActivity.java and write the following:

package com.example.messengerapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;

public class IntroActivity extends AppCompatActivity {
    private static final int SPLASH_TIME_OUT = 3000; // 3 seconds

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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent mainIntent = new Intent(IntroActivity.this, MainActivity.class);
                startActivity(mainIntent);
                finish(); // Exit the intro screen
            }
        }, SPLASH_TIME_OUT);
    }
}

The above code implements the functionality of transitioning to MainActivity after a 3-second wait on the intro screen.

5. Modifying AndroidManifest.xml

Open the AndroidManifest.xml file and register IntroActivity. Modify it as follows:

<application
        ... >

        <activity android:name=".IntroActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity"></activity>

        </application>

Here, IntroActivity should be set as the starting screen for the app, so we set the MAIN and LAUNCHER actions.

6. Running and Testing the App

Now everything is set up. When you run the app, you can see that the intro screen appears for 3 seconds before transitioning to MainActivity. Make sure the app is functioning correctly.

If any issues arise, you can check the error messages in Logcat in Android Studio to resolve the problem.

7. Implementing Additional Features

If you want to implement additional features on the intro screen, you can consider ideas such as:

  • Adding animation effects
  • Applying various transition effects to the app logo
  • Adding a simple slogan below the logo

For example, if you want to add an animation effect to the logo, you can use the Animation class to provide a simple fade-in effect.

ImageView logo = findViewById(R.id.logo);
Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo.startAnimation(fadeIn);

Conclusion

In this course, we learned how to implement the intro screen for a messenger app. This process lays the foundation for Android development and contributes to providing an attractive app to users. It’s important for the messenger app to not only have basic messaging functionality but also to evolve by adding various features. Keep striving to continuously improve by adding more functionalities and enhancements.

If you have any more questions about app development or need help with code, feel free to leave a comment anytime. We wish you success on your Android app development learning journey!

Java Android App Development Course, Building Interfaces with Material Library

The importance of user interface (UI) in Android app development cannot be overstated. All visual elements that the user experiences determine the overall satisfaction of the app, so an appropriate UI arrangement is essential. In this context, Google’s Material Design library helps provide a robust and consistent user experience.

1. What is Material Design?

Material Design is a design system proposed by Google in 2014, based on the manipulation and holistic feel of the physical world. It includes elements that provide a sense of physicality and facilitate interaction with the user.

Material Design has the following key principles:

  • Functionality: The user interface should be intuitive and easy for users to operate.
  • Flexibility: It must operate consistently across various devices and immediately adapt to changes in screen size.
  • Emotion: Users should have a positive experience when interacting with the device.

2. Setting Up Material Library

To develop an app using Material Design elements, you first need to add the Material library in the project’s build.gradle file. Add the following code:

dependencies {
    implementation 'com.google.android.material:material:1.4.0'
}

Now you are ready to use Material elements. You can create a new project through Android Studio and start by modifying the default layout file.

3. Using Material Design Components

3.1 Button

Buttons are one of the most commonly used UI elements. Material Design buttons come in default, emphasized, or outline styles. Typically, you declare a button using MaterialButton.

<com.google.android.material.button.MaterialButton
    android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me"
    app:cornerRadius="24dp"
    app:backgroundTint="@color/colorPrimary"/>

3.2 Card

Cards are used to highlight content blocks. In Material Design, you can easily configure cards using CardView.

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardElevation="4dp"
    app:cardCornerRadius="8dp">
    
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello Card!"
        android:padding="16dp"/>
    
</androidx.cardview.widget.CardView>

3.3 Dialog

Dialogs are very useful for providing information or receiving input from users. In Material Design, you can create dialogs using MaterialAlertDialogBuilder.

new MaterialAlertDialogBuilder(this)
    .setTitle("Title")
    .setMessage("Message content")
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Yes button clicked
        }
    })
    .setNegativeButton("Cancel", null)
    .show();

4. Layout Composition

Now let’s connect the elements used above. Here is an example of the main layout file for a simple Material Design app:

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"/>

    </androidx.appcompat.widget.AppBarLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Material Design App"
            android:textSize="24sp"
            android:layout_marginTop="16dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"/>

        <com.google.android.material.button.MaterialButton
            android:id="@+id/my_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click Me"
            app:layout_constraintTop_toBottomOf="@+id/textView"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginTop="20dp"/>

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

5. Development and Execution

Now that we have structured all the UI elements, let’s implement events such as button clicks while logging.

public class MainActivity extends AppCompatActivity {

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

        MaterialButton myButton = findViewById(R.id.my_button);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Button Clicked!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

5.1 Running the App

To run the app, click the “Run” button in Android Studio. Verify that the layout and button you set up appear correctly. A message saying “Button Clicked!” should be displayed when the button is clicked.

6. Conclusion

In this tutorial, we explored how to develop an Android app using Java and how to structure the screen with the Material Design library. Material Design helps enhance user experience and allows easy use of various components. Actively incorporate Material Design into your app development!

Java Android App Development Course, Types and Features of Resources

Android app development can range from simple apps to complex applications with various functionalities. One of the most essential parts of creating such diverse applications is ‘resources’. Resources consist of various components such as the app’s UI, images, string data, colors, etc., and contribute to enriching the visual elements and user experience of the app. In this article, we will discuss the types of resources used in Android app development and their characteristics in detail.

1. Overview of Android Resources

Android resources are various files created to manage the app’s visual elements or content separately. These files are bundled with the code when the app is executed and provided to the user. Resources can be divided into several types, and effectively managing these resources can improve the readability and maintainability of the code.

2. Types of Resources

The main types of resources used in Android are as follows:

  • String Resources
  • Image Resources
  • Layout Resources
  • Color Resources
  • Style Resources
  • Value Resources
  • Icons

2.1 String Resources

String resources are used to store all the text used within the app. They are defined in the strings.xml file, and each string must have a unique name. These strings can be easily referenced later in the code.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My Application</string>
    <string name="welcome_message">Hello!</string>
</resources>

The strings defined this way can be easily referenced through the code.

String appName = getString(R.string.app_name);

2.2 Image Resources

Image resources include all image files used in the app. You can store image files in PNG, JPG format in the drawable folder. These images are displayed in bitmap format and can provide resources adjusted for various screen densities.

ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.my_image);

2.3 Layout Resources

Layout resources define the structure of the UI. They are written in XML format and can include various UI elements. They are stored in the res/layout folder, allowing you to create layout files corresponding to each screen.

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome_message"/>

</LinearLayout>

2.4 Color Resources

Color resources define the colors used in the app. They are defined in the res/values/colors.xml file, and each color can be referenced by a unique name.

<resources>
    <color name="primary_color">#FF5722</color>
    <color name="secondary_color">#03A9F4</color>
</resources>

2.5 Style Resources

Style resources define a group of attributes that can be applied commonly to multiple views. They are defined in the res/values/styles.xml file and help maintain consistency across UI elements.

<resources>
    <style name="AppTheme">
        <item name="colorPrimary">@color/primary_color</item>
        <item name="colorAccent">@color/secondary_color</item>
    </style>
</resources>

2.6 Value Resources

Value resources can include arrays or other basic data. They are defined in the res/values/arrays.xml file and are useful for storing data in a list format.

<resources>
    <string-array name="example_array">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
    </string-array>
</resources>

2.7 Icons

Icons are various small image files used in the app. Icons are typically used for app launchers, button icons in the toolbar, etc. You can store icons that match the respective densities in folders like drawable-mdpi, drawable-hdpi, thus optimizing the app for various screen resolutions.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon">
</ImageView>

3. Accessing Resources

When accessing resources in Android, resource IDs are used. These IDs are automatically generated when the app is built and defined in the R.java file. This allows easy access to strings, images, layouts, etc.

String welcomeMessage = getResources().getString(R.string.welcome_message);
Drawable icon = getResources().getDrawable(R.drawable.icon);
setContentView(R.layout.activity_main);

4. Multilingual Support for Resources

One of Android’s powerful features is multilingual support. You can create and manage the strings.xml file for the app to be used in several languages. For example, the resources for English and Korean are structured as follows:

res/values/strings.xml (English)
<resources>
    <string name="app_name">My Application</string>
    <string name="welcome_message">Hello!</string>
</resources>
res/values-kr/strings.xml (Korean)
<resources>
    <string name="app_name">내 애플리케이션</string>
    <string name="welcome_message">안녕하세요!</string>
</resources>

This way, the appropriate resources are automatically selected based on the device’s language settings.

5. Tips for Resource Optimization

Resource management greatly impacts the performance and size of the app. Here are some tips for necessary resource optimization.

  • Avoid duplicate resources. Storing the same resource in multiple forms is inefficient.
  • Delete unnecessary resources. Managing resources not used in the project is important.
  • When supporting resources for various resolutions, it is advisable to provide images that match each resolution.
  • Compress unnecessary images to reduce the app’s size.
  • Utilize styles and themes to enhance code reusability and solidify UI consistency.

6. Conclusion

Efficiently managing resources in Android app development plays a significant role in enhancing the quality of the app and improving the user experience. By understanding the characteristics and access methods of each resource, you can build a better app development environment. In future lectures, we will cover actual implementation examples utilizing resources, so please stay tuned!