1 /* 2 * Copyright (C) 2023 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.android.test.binder; 18 19 import android.app.Service; 20 import android.content.Intent; 21 import android.os.IBinder; 22 import android.os.RemoteException; 23 24 import java.lang.ref.PhantomReference; 25 import java.lang.ref.ReferenceQueue; 26 27 public class MyService extends Service { 28 @Override onBind(Intent intent)29 public IBinder onBind(Intent intent) { 30 return new IFooProvider.Stub() { 31 ReferenceQueue<IFoo> mRefQueue = new ReferenceQueue<>(); 32 PhantomReference<IFoo> mRef; 33 34 @Override 35 public IFoo createFoo() throws RemoteException { 36 IFoo binder = new IFoo.Stub() {}; 37 mRef = new PhantomReference<>(binder, mRefQueue); 38 return binder; 39 } 40 41 @Override 42 public boolean isFooGarbageCollected() throws RemoteException { 43 forceGc(); 44 return mRefQueue.poll() == mRef; 45 } 46 47 @Override 48 public void killProcess() throws RemoteException { 49 android.os.Process.killProcess(android.os.Process.myPid()); 50 } 51 }; 52 } 53 forceGc()54 private static void forceGc() { 55 Object obj = new Object(); 56 ReferenceQueue<Object> refQueue = new ReferenceQueue<>(); 57 PhantomReference<Object> ref = new PhantomReference<>(obj, refQueue); 58 obj = null; // make it an orphan 59 while (refQueue.poll() != ref) { 60 System.gc(); 61 } 62 } 63 } 64