1 /* 2 * Copyright 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.mobileer.oboetester; 18 19 import android.app.Notification; 20 import android.app.NotificationChannel; 21 import android.app.NotificationManager; 22 import android.app.Service; 23 import android.content.Context; 24 import android.content.Intent; 25 import android.content.pm.ServiceInfo; 26 import android.os.Build; 27 import android.os.IBinder; 28 import android.util.Log; 29 30 public class AudioForegroundService extends Service { 31 private static final String TAG = "OboeTester"; 32 public static final String ACTION_START = "ACTION_START"; 33 public static final String ACTION_STOP = "ACTION_STOP"; 34 35 @Override onBind(Intent intent)36 public IBinder onBind(Intent intent) { 37 // We don't provide binding, so return null 38 return null; 39 } 40 buildNotification()41 private Notification buildNotification() { 42 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 43 44 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 45 manager.createNotificationChannel(new NotificationChannel( 46 "all", 47 "All Notifications", 48 NotificationManager.IMPORTANCE_NONE)); 49 50 return new Notification.Builder(this, "all") 51 .setContentTitle("Playing/recording audio") 52 .setContentText("playing/recording...") 53 .setSmallIcon(R.drawable.ic_notification) 54 .build(); 55 } 56 return null; 57 } 58 59 @Override onStartCommand(Intent intent, int flags, int startId)60 public int onStartCommand(Intent intent, int flags, int startId) { 61 Log.i(TAG, "Receive onStartCommand" + intent); 62 switch (intent.getAction()) { 63 case ACTION_START: 64 Log.i(TAG, "Receive ACTION_START " + intent.getExtras()); 65 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 66 int serviceTypes = intent.getIntExtra("service_types", 0); 67 Log.i(TAG, "ServiceTypes: " + serviceTypes); 68 startForeground(1, buildNotification(), serviceTypes); 69 } 70 break; 71 case ACTION_STOP: 72 Log.i(TAG, "Receive ACTION_STOP " + intent.getExtras()); 73 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 74 stopForeground(STOP_FOREGROUND_REMOVE); 75 } 76 break; 77 } 78 return START_NOT_STICKY; 79 } 80 } 81