1 /* 2 * Copyright (C) 2022 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 package android.alarmmanager.alarmtestapp.cts.common; 17 18 import android.app.Notification; 19 import android.app.NotificationChannel; 20 import android.app.NotificationManager; 21 import android.app.Service; 22 import android.content.Context; 23 import android.content.Intent; 24 import android.os.Handler; 25 import android.os.IBinder; 26 import android.os.Looper; 27 28 /** 29 * An empty service, that makes itself as a foreground service, and stops itself. 30 */ 31 public class TestService extends Service { 32 private static final String CHANNEL_ID = "mychannel"; 33 34 private static final int FGS_NOTIFICATION_ID = 1; 35 36 /** Create a notification channel. */ getNotificationChannelId(Context context)37 private static String getNotificationChannelId(Context context) { 38 NotificationManager nm = context.getSystemService(NotificationManager.class); 39 40 CharSequence name = "my_channel"; 41 String description = "my channel"; 42 int importance = NotificationManager.IMPORTANCE_DEFAULT; 43 NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); 44 channel.setDescription(description); 45 // Register the channel with the system; you can't change the importance 46 // or other notification behaviors after this 47 nm.createNotificationChannel(channel); 48 49 return CHANNEL_ID; 50 } 51 52 @Override onBind(Intent intent)53 public IBinder onBind(Intent intent) { 54 return null; 55 } 56 57 @Override onStartCommand(Intent intent, int flags, int startId)58 public int onStartCommand(Intent intent, int flags, int startId) { 59 // When this service is started, make it a foreground service, and stop itself. 60 Notification.Builder builder = 61 new Notification.Builder(this, getNotificationChannelId(this)) 62 .setSmallIcon(android.R.drawable.btn_star) 63 .setContentTitle("My FGS") 64 .setContentText("My FGS"); 65 startForeground(FGS_NOTIFICATION_ID, builder.build()); 66 67 new Handler(Looper.getMainLooper()).post(() -> { 68 stopSelf(); 69 }); 70 71 return Service.START_NOT_STICKY; 72 } 73 } 74