У меня очень странная проблема. Я разработал свое приложение, используя мой 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 полностью обновлен:
Я компилирую мое приложение с
В моей основной деятельности я проверяю, если 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 намного проще.
Я поехал в Генни и никогда не оглядывался назад.
Будьте осторожны, чтобы не путать Google Play Маркете с Google Play. Все двое действительно разделяют имя; Я думаю, вы в основном имеете в виду Google Play Services в своем вопросе. –
Есть ли исключения в LogCat? Я подозреваю, что GooglePlayServicesUtil.isGooglePlayServicesAvailable (контекст) 'throws ClassNotFoundException, потому что на этом устройстве нет класса под названием« GooglePlayServicesUtil ». В этом случае вы должны поймать исключение и вернуть 'false'. – ADTC