1 /* 2 * Copyright (C) 2019 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.tests.stagedinstall; 18 19 import android.app.PendingIntent; 20 import android.content.BroadcastReceiver; 21 import android.content.Context; 22 import android.content.Intent; 23 import android.content.IntentSender; 24 import android.content.pm.PackageInstaller; 25 import android.util.Log; 26 27 import androidx.test.InstrumentationRegistry; 28 29 import java.util.concurrent.BlockingQueue; 30 import java.util.concurrent.LinkedBlockingQueue; 31 32 public class LocalIntentSender extends BroadcastReceiver { 33 private static final String TAG = "StagedInstallTest"; 34 private static final BlockingQueue<Intent> sIntentSenderResults = new LinkedBlockingQueue<>(); 35 36 @Override onReceive(Context context, Intent intent)37 public void onReceive(Context context, Intent intent) { 38 Log.i(TAG, "Received intent " + prettyPrint(intent)); 39 sIntentSenderResults.add(intent); 40 } 41 42 /** 43 * Get a LocalIntentSender. 44 */ getIntentSender()45 static IntentSender getIntentSender() { 46 Context context = InstrumentationRegistry.getContext(); 47 Intent intent = new Intent(context, LocalIntentSender.class); 48 PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent, 0); 49 return pending.getIntentSender(); 50 } 51 52 /** 53 * Returns the most recent Intent sent by a LocalIntentSender. 54 */ getIntentSenderResult()55 static Intent getIntentSenderResult() throws InterruptedException { 56 Intent intent = sIntentSenderResults.take(); 57 Log.i(TAG, "Taking intent " + prettyPrint(intent)); 58 return intent; 59 } 60 prettyPrint(Intent intent)61 private static String prettyPrint(Intent intent) { 62 int sessionId = intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1); 63 int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, 64 PackageInstaller.STATUS_FAILURE); 65 String message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE); 66 return String.format("%s: {\n" 67 + "sessionId = %d\n" 68 + "status = %d\n" 69 + "message = %s\n" 70 + "}", intent, sessionId, status, message); 71 } 72 } 73