1 /* 2 * Copyright (C) 2016 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17 package com.googlecode.android_scripting.activity; 18 19 import android.app.Notification; 20 import android.app.NotificationManager; 21 import android.app.Service; 22 import android.content.Context; 23 24 import com.googlecode.android_scripting.Log; 25 26 import java.lang.reflect.InvocationTargetException; 27 import java.lang.reflect.Method; 28 29 /** 30 * A utility class supplying helper methods for {@link Service} objects. 31 * 32 * @author Felix Arends (felix.arends@gmail.com) 33 */ 34 public class ServiceUtils { ServiceUtils()35 private ServiceUtils() { 36 } 37 38 /** 39 * Marks the service as a foreground service. This uses reflection to figure out whether the new 40 * APIs for marking a service as a foreground service are available. If not, it falls back to the 41 * old {@link #setForeground(boolean)} call. 42 * 43 * @param service 44 * the service to put in foreground mode 45 * @param notificationId 46 * id of the notification to show 47 * @param notification 48 * the notification to show 49 */ setForeground(Service service, Integer notificationId, Notification notification)50 public static void setForeground(Service service, Integer notificationId, 51 Notification notification) { 52 final Class<?>[] startForegroundSignature = new Class[] { int.class, Notification.class }; 53 Method startForeground = null; 54 try { 55 startForeground = service.getClass().getMethod("startForeground", startForegroundSignature); 56 57 try { 58 startForeground.invoke(service, new Object[] { notificationId, notification }); 59 } catch (IllegalArgumentException e) { 60 // Should not happen! 61 Log.e("Could not set TriggerService to foreground mode.", e); 62 } catch (IllegalAccessException e) { 63 // Should not happen! 64 Log.e("Could not set TriggerService to foreground mode.", e); 65 } catch (InvocationTargetException e) { 66 // Should not happen! 67 Log.e("Could not set TriggerService to foreground mode.", e); 68 } 69 70 } catch (NoSuchMethodException e) { 71 // Fall back on old API. 72 // service.setForeground(true); //too old to be supported 73 74 NotificationManager manager = 75 (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE); 76 manager.notify(notificationId, notification); 77 } 78 } 79 } 80