How to start a Service from a BroadcastReceiver in Android

In this android programming source code example, we are going to start a Service from a BroadcastReceiver in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to start a Service from a BroadcastReceiver in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapAndService.MapAndServiceActivity18">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/time"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Time"
                android:inputType="number"
                android:textColorHint="@color/colorPrimary"
                android:textColor="@color/colorPrimary"/>

            <Button
                android:id="@+id/schedule"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorAccent"
                android:text="Start Alarm"
                android:textAllCaps="false"
                android:textColor="#ffffff"
                android:textSize="19sp" />
        </com.google.android.material.textfield.TextInputLayout>
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.material.textfield.TextInputEditText;

public class MapAndServiceActivity18 extends AppCompatActivity {
    private TextInputEditText time;
    private Button schedule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_and_service18);
        time = (TextInputEditText) findViewById(R.id.time);
        schedule = (Button) findViewById(R.id.schedule);
        schedule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startBroadcast();
            }
        });
    }

    private void startBroadcast(){
        int timeinput = Integer.parseInt(time.getText().toString());
        Intent intent = new Intent(this, BrService4.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+(timeinput * 1000), pendingIntent);
    }
}

BrService4.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BrService4 extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, Service18.class));
    }
}

Service18.java

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

public class Service18 extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        showNotification("Inducesmile", "Service started by user.");
        return START_STICKY;
    }

    private void showNotification(String title, String task){
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
            NotificationChannel notificationChannel = new NotificationChannel("inducesmile", "inducesmile", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(),"inducesmile")
                .setContentTitle(title)
                .setContentText(task)
                .setSmallIcon(R.mipmap.ic_launcher);
        notificationManager.notify(1, notification.build());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
    }
}

AndroidManifest.xml

<service android:name=".MapAndService.Service18" />

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

50% Discounts On Projects

Do you have a custom project with a clear requirements, we are currently giving a 50% discount on all projects.

We will work with you to ensure we deliver what you need.

If you have questions or want to chat with us, you can reach us on Skype (henry.tochi)

Languages and technologies we use - Java, Kotlin, Laravel, Vue, React, Flutter, Swift and more.