How to create foreground services and notification in your Android App?

The below video shows the steps to create and start your service as a foreground service in your Android App. It also shows the steps to create a notification for your App in the Android phone notification bar.

In this video, it uses the service class created in the previous video: “How to create Service class to run a custom alarm clock in your Android?”
The link for the same is: https://youtu.be/RgOqmQcyeuk

It is recommended to watch this previous video to understand how to create an alarm clock using a service class.

Also, for video on step counter App, please watch the tutorial at: https://youtu.be/o-qpVefrfVA or refer to the below webpage:

We will be glad to hear from you regarding any query, suggestions or appreciations at: programmerworld1990@gmail.com

Source Code:

package com.example.myserviceclass;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {

private Integer alarmHour;
private Integer alarmMinute;
private Ringtone ringtone;
private Timer t = new Timer();

private static final String CHANNEL_ID = “MyNotificationChannelID”;

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

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

alarmHour = intent.getIntExtra(“alarmHour”, 0);
alarmMinute = intent.getIntExtra(“alarmMinute”, 0);

ringtone = RingtoneManager.getRingtone(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));

try {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID )
.setContentTitle(“My Alarm clock”)
.setContentText(“Alarm time – ” + alarmHour.toString() + ” : ” + alarmMinute.toString())
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();

startForeground(1, notification);

NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, “My Alarm clock Service”, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);

}
catch (Exception e){
e.printStackTrace();
}

t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (Calendar.getInstance().getTime().getHours() == alarmHour &&
Calendar.getInstance().getTime().getMinutes() == alarmMinute){
ringtone.play();
}
else {
ringtone.stop();
}

}
}, 0, 2000);

return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
ringtone.stop();
t.cancel();
super.onDestroy();
}
}

package com.example.myserviceclass;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TimePicker;

public class MainActivity extends AppCompatActivity {

private TimePicker timePicker;

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

ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.FOREGROUND_SERVICE}, PackageManager.PERMISSION_GRANTED);

timePicker = findViewById(R.id.timPicker);

final Intent intent = new Intent(this, MyService.class);
ServiceCaller(intent);

timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int i, int i1) {
ServiceCaller(intent);
}
});

}

private void ServiceCaller(Intent intent){

stopService(intent);

Integer alarmHour = timePicker.getCurrentHour();
Integer alarmMinute = timePicker.getCurrentMinute();

intent.putExtra(“alarmHour”, alarmHour);
intent.putExtra(“alarmMinute”, alarmMinute);

startService(intent);
}
}

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
package=”com.example.myserviceclass”>

<uses-permission android:name=”android.permission.FOREGROUND_SERVICE”/>

<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”>
<service android:name=”.MyService”/>
<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>

Top comments from YouTube:

Benjamin Ishaia
Thanks for your amazing videos
I learned now how to make an Alarm
But can you next teach us how to make a foreground service that run a countdown timer ?

Programmer World
Sure, I will try to make the video to show how to create stop watch running in foreground service. Will let you know once I post it. Thanks.

Leave a Reply

%d bloggers like this: