Play Video in background for Android App
In this video it shows the code to keep playing the video (or audio) in background by creating a foreground process for your Android App. So, when the app is sent to background either by pressing back or home button on your Android device then this foreground process/ service will start playing the video in mediaplayer.
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Details:
Java Code:
MainActivity.java
package com.programmerworld.audiocontrol;
// How to keep playing video in background by creating a foreground process for your Android App?
import static android.Manifest.permission.POST_NOTIFICATIONS;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
private VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ActivityCompat.requestPermissions(
this,
new String[]{POST_NOTIFICATIONS},
PERMISSION_GRANTED);
}
// Find the VideoView by ID
videoView = findViewById(R.id.videoView);
// Set the video URI
Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videosample);
// Set up the MediaController
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
// Set up the VideoView
videoView.setVideoURI(videoUri);
videoView.setMediaController(mediaController);
// Restart the video when it finishes
videoView.setOnCompletionListener(mp -> videoView.start());
// Start the video
videoView.start();
// Start the background service for video playback
startService(new Intent(this, VideoPlaybackService.class));
return insets;
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// Stop the service when the activity is destroyed
stopService(new Intent(this, VideoPlaybackService.class));
}
}
VideoPlaybackService.java
package com.programmerworld.audiocontrol;
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.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
public class VideoPlaybackService extends Service {
private static final String CHANNEL_ID = "VideoPlaybackChannel";
private MediaPlayer mediaPlayer;
private static final String STOP_ACTION = "STOP_ACTION";
@Override
public void onCreate() {
super.onCreate();
// Create a notification channel for foreground service
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Video Playback Channel",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(channel);
}
// Build the stop action intent
Intent stopIntent = new Intent(this, VideoPlaybackService.class);
stopIntent.setAction(STOP_ACTION);
PendingIntent stopPendingIntent = PendingIntent.getService(
this, 0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
// Build the notification
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Video Playback")
.setContentText("Playing video in the background")
.setSmallIcon(android.R.drawable.ic_media_play)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Stop", stopPendingIntent) // Add Stop action
.setOngoing(true) // Keep the notification active
.build();
// Start the service in the foreground
startForeground(1, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Play the video file in the background
Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videosample);
// Initialize MediaPlayer
mediaPlayer = MediaPlayer.create(this, videoUri);
mediaPlayer.setLooping(true); // Loop the video
if (intent != null && STOP_ACTION.equals(intent.getAction())) {
// Stop the media player and the service
mediaPlayer.stop();
mediaPlayer.release();
stopSelf();
return START_NOT_STICKY;
}
mediaPlayer.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AudioControl"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".VideoPlaybackService"
android:exported="false"
android:foregroundServiceType="mediaPlayback" />
</application>
</manifest>
Gradle File:
plugins {
alias(libs.plugins.android.application)
}
android {
namespace = "com.programmerworld.audiocontrol"
compileSdk = 35
defaultConfig {
applicationId = "com.programmerworld.audiocontrol"
minSdk = 29
targetSdk = 35
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
dependencies {
implementation(libs.appcompat)
implementation(libs.material)
implementation(libs.activity)
implementation(libs.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)
}
XML File:
<?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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="425dp"
android:layout_marginTop="80dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Screenshots:

