2013-11-26 3 views
8

У меня очень странная проблема. Я разработал свое приложение, используя мой HTC One V под управлением 4.0.3 ОС. Теперь приложение работает превосходно на моих и нескольких других случайных устройствах 2.2 и 2.3 и 4+, но на некоторых устройствах, несмотря на то, что у них есть приложение GooglePlayStore, приложение запускается и загружается, но не отображает карту на другом, несмотря на то, что у них есть GPStore на них приложение сбои говорят, что GPStore/Service нет.AVD Невозможно протестировать любое приложение с помощью AVD

Я попытался протестировать приложение на AVD Devies, но ни один из них не установил GooglePlayStore. Я попробовал подход Google Play on Android 4.0 emulator, чтобы подтолкнуть GPStore к ним, но без успеха.

Мой дроид SDK полностью обновлен:
enter image description here

Я компилирую мое приложение с enter image description here

В моей основной деятельности я проверяю, если Google Play Service/магазин присутствует, чтобы определить, можно использовать GoogleMaps :

public class Map extends FragmentActivity implements Observer 
{ 
    private MapAgent agent; 
    private Locator locator; 
    private Spinner spinner; 
    private Button gps; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
    super.onCreate(savedInstanceState); 

    // Get a new instance of Locator agent 
    locator = new Locator(); 

    // Register as Observer to Locator agent 
    locator.addObserver(this); 

    // Check if Internet connection is available 
    if(Services.connectivityServiceState(this)) 
    { 
     // We have a working Internet connection 
     // Check if we have a GooglePS in operating mode 
     if(Services.playServiceState(this)) 
     { 
     // Load the map 
     setContentView(R.layout.activity_map); 

     // Fetch dropdown list & gps button reference 
     spinner = (Spinner) findViewById(R.id.bankslist); 
     gps  = (Button) findViewById(R.id.gpsbttn); 

     // Register event listener with gps button 
     gps.setOnClickListener(new GpsAction(this)); 

     // Register event listener with spinner 
     spinner.setOnItemSelectedListener(new SpinnerAction()); 

     // Fetch our map 
     agent = new MapAgent(this); 

     // Move map camera to initial position 
     agent.initialPosition(); 



     } else { 
     // GooglePS is not in operating mode 
     Messages.playNotificationMessage(this); 
     } 

    } else { 
     // No Internet connection 
     // Prompt user to turn on WiFi or Mobile 
     Messages.internetConnectionRequestMessage(this); 
    } 
    } 

метод, который проверяет состояние GooglePlay службы находится в моем Services.java ниже:

public class Services 
{ 
    /** 
    * OPERATING CODES 
    */ 
    private static final int GPS_ERR_REQUEST = 9000; 

    /** 
    * Test device for GooglePlayServices, required for 
    * GoogleMaps API V2. 
    * 
    * @param Activity 
    * @result boolean 
    */ 
    public static boolean playServiceState(Activity context) 
    { 
    // Fetch GooglePS operating code 
    int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context); 

    // Check if GooglePS is operating 
    if(code == ConnectionResult.SUCCESS) 
    { 
     // We have GooglePS in working condition 
     return true; 
    } 

    // We have an error, check if it can be resolved by user 
    /*if(GooglePlayServicesUtil.isUserRecoverableError(code)) 
    { 
     // We can solve this error pull up GooglePS guide dialog 
     Dialog guide = GooglePlayServicesUtil.getErrorDialog(code, context, GPS_ERR_REQUEST); 

     // Show the guide dialog 
     guide.show(); 

     // Dispose of our activity 
     context.finish(); 
    }*/ 

    // We do not have GooglePS in operating mode 
    // solve error and retry 
    return false; 
    } 

    /** 
    * Tests devices Wi-Fi and Mobile network for a 
    * working Internet connection. 
    * 
    * @param Activity 
    * @return boolean 
    */ 
    public static boolean connectivityServiceState(Activity context) 
    { 
    // Fetch a CM instance 
    ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    // Test both carriers for a working Internet connection 
    NetworkInfo wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
    NetworkInfo mobi = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

    // Check for Internet connection 
    if(wifi.isConnected() || mobi.isConnected()) 
    { 
     // We have a working internet connection 
     return true; 
    } 

    // No internet connection 
    return false; 
    } 

    /** 
    * Test NETWORK service to determine if Google Location 
    * services are enabled or not. 
    */ 
    public static boolean networkServiceState(Activity context) 
    { 
    // Fetch a LM instance 
    LocationManager provider = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 

    // Return true for enabled GLS 
    return provider.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
    } 

    /** 
    * Tests GPS service to determine if GPS 
    * is enabled or not. 
    * 
    * @param Activity 
    * @result boolean 
    */ 
    public static boolean gpsServiceState(Activity context) 
    { 
    // Fetch a LM instance 
    LocationManager provider = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 

    // Return true for enabled GPS 
    return provider.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } 

    /** 
    * Checks if a GPS Radio is present 
    * within the device. 
    * 
    * @param Activity 
    * @return boolean 
    */ 
    public static boolean hasGPS(Activity context) 
    { 
    // Refere to devices package manager for GPS service 
    return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS); 
    } 
} 

И моя карта просто обрабатывается в моем классе MapAgent, ничего не впечатляющего, просто манипулируя маркерами.

public MapAgent(FragmentActivity context) 
    { 
    // Fetch the map support fragment 
    SupportMapFragment fragment = ((SupportMapFragment) context.getSupportFragmentManager().findFragmentById(R.id.map)); 

    // Fetch map and view 
    map = fragment.getMap(); 

    // Set initial zoom 
    zoom = 7; 

    // Check if this is the first run 
    final SharedPreferences prefs = context.getSharedPreferences("slo.bankomati.core", Context.MODE_PRIVATE); 

    if(prefs.getBoolean("firstrun", true)) 
    { 
     // Check if database exists and delete it 
     if(Database.exists(context)) 
     { 
     Database.delete(context); 
     } 
     prefs.edit().putBoolean("firstrun", false); 
    } 


    // Fetch all atms 
    try { 
     db = new Database(context); 
     atms = db.getAtms(); 
     db.close(); 
    } catch (Exception e) { 
     // TODO: Temporary solution 
    } 

    // Create an empty array for filtered results 
    filtered = new ArrayList<Atm>(); 
    markers = new HashMap<Marker, Atm>(); 

    // Reference the resources and context 
    this.resources = context.getResources(); 
    this.context = context; 

    // Register camera & info window listener with the map 
    map.setOnCameraChangeListener(this); 
    //map.setOnInfoWindowClickListener(new ShowDetails(context, resources)); 
    map.setOnMarkerClickListener(new ShowDetails(context)); 
    } 

Я из всех идей, которые я не могу получить GooglePlay Service работает на AVD 2.2+ Я попытался AVD 4,4 Google Play API он приходит GPService но ти обыкновение отображать карту. Поэтому, чтобы прямо указать мои подзаголовки:

1) Если все AVD от 2.2 до 4.4 все без работы с GooglePlay Services, то как мы можем протестировать приложение для нескольких телефонов и версий ОС без наличия нескольких телефонов.

2) Есть ли верный способ или более правильный способ отображения GoogleMap на более старых устройствах. Я говорю о Android 2.2+. Я использовал самый тривиальный способ отображения моей карты. У меня есть элемент Fragment SupportMap в моем макете Layout. Проблема, с которой я столкнулся, заключается в том, что некоторые телефоны 2.2 и 2.3, на которых есть GooglePlayStore, будут или не будут открывать приложение, те, которые открывают приложение, не отображают карту, но они отображают элементы управления масштабированием карты и логотип Google внизу.

3) Я добавил свой файл макета, но у меня больше нет моего телефона Android, и AVD не позволяет мне тестировать приложение, которое требует GooglePlayServices, возможно, что мой макет, показанный ниже, вызывает проблему из-за наложения макета.

У меня в основном есть рама в фоновом режиме У меня есть GoogleMap, а поверх этого в верхнем углу у меня есть прядильщик и кнопка. Когда я последний раз тестировал это приложение, он работал на моем телефоне HTC One V Android 4.0.3.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:map="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/root_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <fragment 
     android:id="@+id/map" 
     android:name="com.google.android.gms.maps.SupportMapFragment" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
    /> 

    <Button 
     android:id="@+id/gpsbttn" 
     android:layout_width="28dp" 
     android:layout_height="28dp" 
     android:layout_marginLeft="10dp" 
     android:layout_marginTop="10dp" 
     android:background="@drawable/gps" 
     android:minHeight="28dip" 
     android:minWidth="28dip" 
     android:text="" /> 

    <Spinner 
     android:id="@+id/bankslist" 
     android:layout_width="match_parent" 
     android:layout_height="36dp" 
     android:layout_marginLeft="48dp" 
     android:layout_marginRight="10dp" 
     android:layout_marginTop="10dp" 
     android:entries="@array/banks_list" 
     android:prompt="@string/banks_prompt" /> 

</FrameLayout> 

ПРОСТОЕ РЕШЕНИЕ:
Для всех друзей, которые приходят по этому вопросу, чтобы не быть в состоянии полностью проверить свои приложения через AVD сделать переход к Genymotion Emulator это жизнь заставка. Это быстрее, он менее глючит и поддерживает каждую отдельную функцию, которую делает настоящий телефон, и делает тестирование приложений для Android с 2,2 намного проще.

Я поехал в Генни и никогда не оглядывался назад.

+1

Будьте осторожны, чтобы не путать Google Play Маркете с Google Play. Все двое действительно разделяют имя; Я думаю, вы в основном имеете в виду Google Play Services в своем вопросе. –

+0

Есть ли исключения в LogCat? Я подозреваю, что GooglePlayServicesUtil.isGooglePlayServicesAvailable (контекст) 'throws ClassNotFoundException, потому что на этом устройстве нет класса под названием« GooglePlayServicesUtil ». В этом случае вы должны поймать исключение и вернуть 'false'. – ADTC

ответ

7

В соответствии с ответом на этот вопрос: Google Maps - "App won't run unless you update Google Play services", который ссылается на эту запись в Google+: https://plus.google.com/+AndroidDevelopers/posts/Tyz491d96Ci, использование Карт в вашем приложении не поддерживается в эмуляторе; в этом посте есть много горьких ответов.

Один из ответов ссылается на этот вопрос: This app won't run unless you update Google Play Services (via Bazaar), в котором описывается хакерство эмулятора, которое вы можете попробовать, если ничего не работает.

+0

Спасибо за ответ, я совсем забыл о вопросе. Главным образом благодаря моему открытию эмулятора Genymotion, который позволяет тестировать приложения, зависящие от служб GP, от Android 2.2 до последней версии. –

5

В дополнении к обходному Скотту упоминает, в соответствии с документацией Play Services, все AVDS ориентации 4.2.2 или выше будет поддерживать Play Services .: http://developer.android.com/google/play-services/setup.html

Есть также несколько людей, которые были в состоянии установить Play услуги на старых AVDS, но законность, которая может оказаться под вопросом:

3

В настоящее время Android-эмулятор не позволяет Google Maps, поскольку он не поддерживает приложение Google Play Services (на устройствах < 4.2.2), которое требуется для работы API Карт. Я предполагаю, что вы используете карты Google. Похож, http://www.genymotion.com/ предлагает эмулятор, который поддерживает функции Службы Google Play. Попробуйте, если это не сработает, попробуйте получить реальное устройство. Для меня нет смысла проверять приложение карты на эмуляторе. Я бы предложил инвестировать немного денег в устройство разработки. Он будет платить за себя и уменьшать свои головные боли при работе с этими типами ситуаций.

UPDATE

Попробуйте переключить свой Android Target (тому же номер адресата) Google API,

Я также вытащил Google Play services.apk от корневого устройства и установки, что с помощью командной строки на эмуляторе , Это не рекомендуется, и это может быть немного неприятным.

В документации, что Скотт предоставил ссылку, он говорит вам, что требования Google Play Store и Google Play Services.

+0

Имеются системные образы, в которых есть APK Play Services и поддерживают его. Ни один из них не имеет самого магазина Google Play. Я считаю, что проблема в том, что последнее обновление для Maps не позволяет сторонним приложениям отображать карты через API при работе в эмуляции. –

Смежные вопросы