[go: up one dir, main page]

0% found this document useful (0 votes)
14 views24 pages

Android Code Note

The document provides a comprehensive overview of Android development, focusing on creating activities, services, and notifications. It includes code examples for setting up button clicks to launch new activities, implementing notification channels, and managing different types of services. Additionally, it discusses best practices for using services and broadcast receivers, as well as data storage and network communication in Android applications.

Uploaded by

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

Android Code Note

The document provides a comprehensive overview of Android development, focusing on creating activities, services, and notifications. It includes code examples for setting up button clicks to launch new activities, implementing notification channels, and managing different types of services. Additionally, it discusses best practices for using services and broadcast receivers, as well as data storage and network communication in Android applications.

Uploaded by

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

New Activity on click button in

Android

res/layout/activity_main.xml

<?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" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Next"
android:textSize="32dp"
android:textColor="@color/colorPrimary"
android:textStyle="bold"/>
</RelativeLayout>

src/MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openNewActivity();
}
});
}
public void openNewActivity(){
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
}
}
res/layout/activity_second.xml

<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="10dp"
android:text="Welcome to Next Activity"
android:textColor="@color/colorPrimaryDark"
android:textSize="32dp"/>
</RelativeLayout>

src/SecondActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class NewActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
}
}

androidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<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/AppTheme">
<activity android:name=".NewActivity"></activity>
<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>

Notifications in Android
//

package com.example.notificationapp;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RemoteViews;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {


private final String channelId = "i.apps.notifications"; // Unique channel
ID for notifications
private final String description = "Test notification"; // Description for the
notification channel
private final int notificationId = 1234; // Unique identifier for the
notification

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

Button btn = findViewById(R.id.btn);

// Create a notification channel (required for Android 8.0 and higher)


createNotificationChannel();

btn.setOnClickListener(v -> {
// Request runtime permission for notifications on Android 13 and
higher

sendNotification(); // Trigger the notification


});
}

/**
* Create a notification channel for devices running Android 8.0 or higher.
* A channel groups notifications with similar behavior.
*/
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
channelId,
description,
NotificationManager.IMPORTANCE_HIGH
);
notificationChannel.enableLights(true); // Turn on notification light
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.enableVibration(true); // Allow vibration for
notifications

NotificationManager notificationManager = (NotificationManager)


getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {

notificationManager.createNotificationChannel(notificationChannel);
}
}
}

/**
* Build and send a notification with a custom layout and action.
*/
@SuppressLint("MissingPermission")
private void sendNotification() {
// Intent that triggers when the notification is tapped
Intent intent = new Intent(this, Notif.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT |
PendingIntent.FLAG_IMMUTABLE
);

// Custom layout for the notification content


@SuppressLint("RemoteViewLayout") RemoteViews contentView = new
RemoteViews(getPackageName(), R.layout.activity_after_notification);

// Build the notification


NotificationCompat.Builder builder = new
NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_name) // Notification icon
.setContent(contentView) // Custom notification content
.setContentTitle("Hello") // Title displayed in the notification
.setContentText("Welcome to Notifacation!!") // Text displayed in
the notification
.setContentIntent(pendingIntent) // Pending intent triggered
when tapped
.setAutoCancel(true) // Dismiss notification when tapped
.setPriority(NotificationCompat.PRIORITY_HIGH); // Notification
priority for better visibility

// Display the notification


NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
}
}

Chapter - 3

Services and Notification

3.1. Background Service


3.2. Foreground Service
3.3. Broadcast Receiver

Services
A Service is an application component that can perform long-running
operations in the background. It does not provide a user interface. Once started, a
service might continue running, even after the user switches to another application.
Additionally, a component can bind to a service to interact with it and even perform
interprocess communication (IPC). For example, a service can handle network
transactions, play music, perform file I/O, or interact with a content provider, all from
the background.

Caution: A service runs in the main thread of its hosting process; the service does not create its
own thread and does not run in a separate process unless you specify otherwise. You should run
any blocking operations on a separate thread within the service to avoid Application Not
Responding (ANR) errors.
Types of Services
These are the three different types of services:

Foreground

Background

Bound

1. Foreground Services:

Services that notify the user about their ongoing operations are termed

as Foreground Services. Users can interact with the service through the

notifications provided about the ongoing task. Such as in downloading

a file, the user can keep track of the progress in downloading and can

also pause and resume the process.

2. Background Services:

Background services do not require any user intervention. These

services do not notify the user about ongoing background tasks and

users also cannot access them. The process, like schedule syncing of

data or storing of data, falls under this service.

3. Bound Services:

This type of Android service allows the components of the application,

like an activity, to bind themselves to it. Bound services perform their

task as long as any application component is bound to them. More than


one component is allowed to bind itself to a service at a time. In order

to bind an application component with a service bindService() method

is used.

Comparison of Service Types (Foreground, Background, and Bound)

Foreground​

Runs with a visible notification to the user.

Must call startForeground().​

Ongoing tasks the user is aware of (e.g., music playback, GPS tracking).

- Requires persistent notification.

- Strict permissions and declarations in newer Android versions.​

- API 28+: Requires FOREGROUND_SERVICE permission.

- API 31+: Restricted background starts.

- API 34+: Service type declarations in manifest.

Mandatory notification ensures user transparency.

Android 12+ (API 31): Apps cannot start foreground services from the

background unless exempt (e.g., user-initiated actions).

Android 14+ (API 34): Requires explicit foregroundServiceType in the

manifest (e.g., health, location).


Background​

Runs without a visible notification.

Started via startService().​

Short-lived tasks (e.g., syncing data, processing files).

- API 26+ (Android 8.0+): Cannot start from the background; app crashes.

- Resource-intensive if misused.​

- API 26+: Use WorkManager/JobScheduler instead.

- Background execution is blocked unless the app is in the foreground.

Effectively deprecated on API 26+. Use WorkManager or JobScheduler for

background tasks.

Started Services (startService()) are treated as "background" unless

promoted to Foreground

Bound

Allows components (e.g., Activities) to bind and interact directly with it.

Inter-component communication (e.g., feeding data to an Activity).

- Stops when all components unbind.


- No direct background execution; tied to bound component lifecycle.​ -

API 26+: The System may terminate if the app is in the background.

- Avoid long-running tasks.

Primarily for IPC (Inter-Process Communication) or intra-app component

interaction.

Not ideal for long tasks; use with startService() if the service needs to

outlive bound components.

Declaring a service in the manifest

<manifest ... >

...

<application ... >

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

...

</application>

</manifest>
The service lifecycle

Example of Android Services

Playing music in the background is a very common example of a service

in Android.

Creating the custom service class will extend the Service class. The

callback methods are used to initiate and destroy the services.

import android.app.Service;

import android.content.Intent;

import android.media.MediaPlayer;

import android.os.IBinder;
import android.provider.Settings;

import androidx.annotation.Nullable;

public class NewService extends Service {

// declaring object of MediaPlayer

private MediaPlayer player;

@Override

// execution of service will start

// on calling this method

public int onStartCommand(Intent intent, int flags, int startId) {

// creating a media player which

// will play the audio of Default

// ringtone in android device

player = MediaPlayer.create( this,


Settings.System.DEFAULT_RINGTONE_URI );

// providing the boolean

// value as true to play

// the audio on loop

player.setLooping( true );

// starting the process

player.start();
// returns the status

// of the program

return START_STICKY;

@Override

// execution of the service will

// stop on calling this method

public void onDestroy() {

super.onDestroy();

// stopping the process

player.stop();

@Nullable

@Override

public IBinder onBind(Intent intent) {

return null;

Java MainActivity file

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity implements


View.OnClickListener {

// declaring objects of Button class

private Button start, stop;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate( savedInstanceState );

setContentView( R.layout.activity_main );

// assigning ID of startButton

// to the object start

start = (Button) findViewById( R.id.startButton );

// assigning ID of stopButton

// to the object stop

stop = (Button) findViewById( R.id.stopButton );

// declaring listeners for the

// buttons to make them respond

// correctly according to the process


start.setOnClickListener( this );

stop.setOnClickListener( this );

public void onClick(View view) {

// process to be performed

// if start button is clicked

if(view == start){

// starting the service

startService(new Intent( this, NewService.class ) );

// process to be performed

// if stop button is clicked

else if (view == stop){

// stopping the service

stopService(new Intent( this, NewService.class ) );

}
Modify the AndroidManifest.xml file

It is necessary to mention the created service in the

AndroidManifest.xml file. It is not possible for a service to

perform its task if it is not mentioned in this file.

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

<manifest
xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.services_in_android">

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

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN"
/>

<category
android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>
<meta-data

android:name="preloaded_fonts"

android:resource="@array/preloaded_fonts" />

<!-- Mention the service name here -->

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

</application>

</manifest>

Best Practices:
•Use Background Services for short, non-urgent tasks.
•Use Foreground Services for critical, user-facing operations.
•Optimize for battery and resource usage (e.g., WorkManager for scheduled
tasks).

Broadcast Receivers
Broadcast Receivers allow us to register for the system and application events,
and when that event happens, then the register receivers get notified.
A Broadcast Receiver is a component that listens for system or app-generated
events (e.g., screen turned on, battery low, SMS received) and triggers actions in
response.

Types of Broadcast Receivers

Static Broadcast Receivers: Declared in the application's manifest file, these


receivers can respond to broadcasts even when the application is not running.
However, starting from Android API Level 26 (Oreo), many broadcasts can
only be received through dynamic receivers due to background execution
limitations.​
Dynamic Broadcast Receivers: Registered programmatically at runtime, these
receivers are active only while the application is running or minimized. They
offer greater flexibility and are suitable for events that are relevant during the
app's active lifecycle.

Static Receiver: Declared in AndroidManifest.xml (works even if the app is


closed).
Dynamic Receiver: Registered/unregistered at runtime via code (tied to
component lifecycle).
There are following two important steps to make BroadcastReceiver works for
the system broadcasted intents −

​ Creating the Broadcast Receiver.


​ Registering Broadcast Receiver

Creating the Broadcast Receiver:

class AirplaneModeChangeReceiver:BroadcastReceiver() {

override fun onReceive(context: Context?, intent: Intent?) {

// logic of the code needs to be written here

Registering a BroadcastReceiver:

IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {

// receiver is the broadcast receiver that we have registered

// and it is the intent filter that we have created

registerReceiver(receiver,it)
}

Chapter - 4

Storing and Retrieving Data

4.1. Local Storage


4.1.1. File Management
4.1.2. SQLite Database
4.2. Getting the Model Right
4.3. CRUD in Local Storage
4.4. Working with a Content Provider

Chaper - 5

Communication via network and the web


5.1. Networking and HTTP
5.2. Data Fetching using web API
5.3. JSON and Serialization
5.2. Telephony
​ Deciding the Scope of an App
​ Wireless Connectivity and Mobile Apps

5.3. Performance and Memory Management

Chapter - 6

Accessing Platform Services

6.1. Local and Remote Notification


6.2. Bluetooth
6.3. Location
6.4. Scheduler and Alarm

Accessing Platform Services

Notification on Android

A notification is a message you can display to the user outside of your


application's normal UI. When you tell the system to issue a notification, it
first appears as an icon in the notification area.

Or

Notification is a kind of message, alert, or status of an application


(probably running in the background) that is visible or available in the
Android’s UI elements

Local Notifications are generated by the app itself, while Remote


Notifications (push notifications) are sent from a server.

Permissions in AndroidManifest.xml
<uses-permission
android:name="android.permission.POST_NOTIFICATIONS" /> <!-- For
Android 13+ - - >

Four types of notifications:

1.​ Status Bar Notification (appears in the same layout as the current

time, and battery percentage)

2.​ Notification drawer Notification (appears in the drop-down menu)

3.​ Heads-Up Notification (appears on the overlay screen, ex:

WhatsApp notification, OTP messages)

4.​ Lock-Screen Notification


Note: Without configuring Notification Channels, you cannot build
notification for applications with Android API >=26. For them generating a
notification channel is mandatory. Apps with API<26 don’t need
notification channels they just need notification builder. Each channel is
supposed to have a particular behavior that will be applicable to all the
notifications which are a part of it. Every channel will, therefore, have a
Channel ID which basically will act as a unique identifier for this Channel
which will be useful if the user wants to differentiate a particular
notification channel. In contrast, the Notification builder provides a
convenient way to set the various fields of a Notification and generate
content views using the platform’s notification layout template but is not
able to target a particular notification channel.

Android - Bluetooth
Bluetooth is a way to send or receive data between two different devices.
Android platform includes support for the Bluetooth framework that allows a
device to wirelessly exchange data with other Bluetooth devices.

Using the Bluetooth APIs, an app can perform the following:

●​ Scan for other Bluetooth devices.


●​ Query the local Bluetooth adapter for paired Bluetooth devices.
●​ Connect to other devices through service discovery.
●​ Transfer data to and from other devices.
●​ Manage multiple connections.

Four major tasks are necessary to communicate using Bluetooth:

●​ Setting up Bluetooth.
●​ Finding devices that are either paired or available in the local area.
●​ Connecting devices.
●​ Transferring data between devices.

All of the Bluetooth APIs are available in the android.bluetooth package.


BluetoothAdapter is the entry-point for all Bluetooth interaction. Using this, you
can discover other Bluetooth devices

AndroidManifest.xml

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

Android - Location
Android location APIs make it easy for you to build location-aware
applications, without needing to focus on the details of the
underlying location technology.

Permissions in AndroidManifest.xml
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />

Android - Alarm

Permissions in AndroidManifest.xml
<uses-permission
android:name="android.permission.SCHEDULE_EXACT_ALARM" /> <!--
For Android 12+ -->

References
https://developer.android.com/develop/background-work/services
https://www.geeksforgeeks.org/services-in-android-with-example/
https://www.tutorialspoint.com/android/android_broadcast_receivers.htm

https://developer.android.com/develop/ui/views/notifications/build-notificatio
n#java
https://developer.android.com/develop/connectivity/bluetooth

https://medium.com/@sandeepkella23/exploring-data-storage-in-android-ty
pes-advantages-datastore-real-time-use-cases-and-best-8bb42fa6792e

You might also like