1 /* 2 * Copyright (C) 2015 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.compatibility.common.util; 18 19 import android.app.Instrumentation; 20 import android.location.Location; 21 import android.os.SystemClock; 22 23 import java.io.IOException; 24 import java.util.Random; 25 26 public class LocationUtils { 27 28 private static final double MIN_LATITUDE = -90D; 29 private static final double MAX_LATITUDE = 90D; 30 private static final double MIN_LONGITUDE = -180D; 31 private static final double MAX_LONGITUDE = 180D; 32 33 private static final float MIN_ACCURACY = 1; 34 private static final float MAX_ACCURACY = 100; 35 registerMockLocationProvider(Instrumentation instrumentation, boolean enable)36 public static void registerMockLocationProvider(Instrumentation instrumentation, 37 boolean enable) throws IOException { 38 SystemUtil.runShellCommand(instrumentation, 39 String.format("appops set --user %d %s android:mock_location %s", 40 instrumentation.getContext().getUserId(), 41 instrumentation.getContext().getPackageName(), 42 enable ? "allow" : "deny")); 43 } 44 createLocation(String provider, Random random)45 public static Location createLocation(String provider, Random random) { 46 return createLocation(provider, 47 MIN_LATITUDE + random.nextDouble() * (MAX_LATITUDE - MIN_LATITUDE), 48 MIN_LONGITUDE + random.nextDouble() * (MAX_LONGITUDE - MIN_LONGITUDE), 49 MIN_ACCURACY + random.nextFloat() * (MAX_ACCURACY - MIN_ACCURACY)); 50 } 51 createLocation(String provider, double latitude, double longitude, float accuracy)52 public static Location createLocation(String provider, double latitude, double longitude, float accuracy) { 53 return createLocation(provider, latitude, longitude, accuracy, SystemClock.elapsedRealtimeNanos()); 54 } 55 createLocation(String provider, double latitude, double longitude, float accuracy, long elapsedRealTimeNanos)56 public static Location createLocation(String provider, double latitude, double longitude, float accuracy, long elapsedRealTimeNanos) { 57 Location location = new Location(provider); 58 location.setLatitude(latitude); 59 location.setLongitude(longitude); 60 location.setAccuracy(accuracy); 61 location.setTime(System.currentTimeMillis()); 62 location.setElapsedRealtimeNanos(elapsedRealTimeNanos); 63 return location; 64 } 65 } 66