Тимур Машнин - Разработка Android-приложений с Augmented Reality стр 13.

Шрифт
Фон

return;

}

LocationServices.FusedLocationApi.requestLocationUpdates (

mGoogleApiClient, mLocationRequest, this);

}


/**

* Removes location updates from the FusedLocationApi.

*/

protected void stopLocationUpdates () {

// It is a good practice to remove location requests when the activity is in a paused or

// stopped state. Doing so helps battery performance and is especially

// recommended in applications that request frequent location updates.


// The final argument to {@code requestLocationUpdates ()} is a LocationListener

// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).

LocationServices.FusedLocationApi.removeLocationUpdates (mGoogleApiClient, this);

}


@Override

public void onConnected (@Nullable Bundle bundle) {


if (ActivityCompat.checkSelfPermission (this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission (this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED) {

// TODO: Consider calling

// ActivityCompat#requestPermissions

// here to request the missing permissions, and then overriding

// public void onRequestPermissionsResult (int requestCode, String [] permissions,

// int [] grantResults)

// to handle the case where the user grants the permission. See the documentation

// for ActivityCompat#requestPermissions for more details.

return;

}

Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation (mGoogleApiClient);

if (mLastLocation!= null) {

mCurrentLocation = mLastLocation;

String lat = String.valueOf(mCurrentLocation.getLatitude ());

String lon = String.valueOf(mCurrentLocation.getLongitude ());

Toast toast = Toast.makeText (this, «Last location» + lat + " " + lon, Toast. LENGTH_LONG);

toast.show ();

mWorld.clearWorld ();

mWorld = CustomWorldHelper.generateObjects (this, mCurrentLocation);

mBeyondarFragment.setWorld (mWorld);

} else {

startLocationUpdates ();

}

}


@Override

public void onConnectionSuspended (int i) {

mGoogleApiClient.connect ();

}


@Override

public void onConnectionFailed (@NonNull ConnectionResult connectionResult) {


}


@Override

public void onLocationChanged (Location location) {

mCurrentLocation = location;

String lat = String.valueOf(mCurrentLocation.getLatitude ());

String lon = String.valueOf(mCurrentLocation.getLongitude ());

Toast toast = Toast.makeText (this,«Current location " + lat+" "+lon, Toast. LENGTH_LONG);

toast.show ();

mWorld.clearWorld ();

mWorld = CustomWorldHelper.generateObjects (this, mCurrentLocation);

mBeyondarFragment.setWorld (mWorld);

}

}

Теперь дополненная реальность будет привязана к текущему местоположению пользователя.

В качестве примера использования фреймворка BeyondAR создадим игровое приложение Creatures in Camera, в котором пользователь сможет расставлять 2D объекты в реальном мире, а потом наблюдать их через камеру.

Создадим новый проект в Android Studio, используя шаблон Navigation Drawer Activity.

Для сборки APK файла с большим количеством методов в коде, в Gradle файл добавим:

defaultConfig {


multiDexEnabled true

}

dependencies {


compile 'com.android.support: multidex:1.0.0»

}

android {


dexOptions {

javaMaxHeapSize «4g»

}

}

В файл манифеста добавим:

<application


android:name="android.support.multidex.MultiDexApplication»>

Добавим зависимость от библиотек beyondar-googlemap-plugin-v0.9.0.jar, beyondar-radar-plugin-v0.9.1.jar и beyondar-v0.9.3.jar, скопировав соответствующие файлы в папку libs проекта.

Добавим зависимость от библиотеки Google Play Services.

compile 'com.google.android.gms: play-services:9.6.1»

Добавим необходимые разрешения в файл манифеста.

<!  Google maps stuff  >

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE» />

<uses-permission android:name="android.permission. WRITE_EXTERNAL_STORAGE» />

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES» />


<!  Minimum permissions for BeyondAR  >

<uses-permission android:name="android.permission.CAMERA» />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION» />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION» />


<!  For BeyondAR this is not mandatory unless you want to load something from the network  >

<uses-permission android:name="android.permission.INTERNET» />


<!  BeyondAR needs the following features  >

<uses-feature android:name="android.hardware.camera» />

<uses-feature android:name="android.hardware.sensor.accelerometer» />

<uses-feature android:name="android.hardware.sensor.compass» />

Для использования Google Map добавим Google API Key в файл манифеста. Для того получим ключ в Google Developers Console и добавим в тег <application> файла манифеста.

<meta-data

android:name="com.google.android.geo. API_KEY»

android: value=«AIzaSyBcRu9Vvb7» />

Изменим файл компоновки content_main. xml.

<?xml version=«1.0» encoding=«utf-8»? >

<android.support.v4.widget.NestedScrollView

xmlns: android="http://schemas.android.com/apk/res/android"

xmlns: app="http://schemas.android.com/apk/res-auto"

xmlns: tools="http://schemas.android.com/tools"

android: layout_width=«match_parent»

android: layout_height=«match_parent»

android: paddingLeft="@dimen/activity_horizontal_margin»

android: paddingRight="@dimen/activity_horizontal_margin»

android: paddingTop="@dimen/activity_vertical_margin»

android: paddingBottom="@dimen/activity_vertical_margin»

android: fillViewport=«true»

android: layout_gravity=«fill_vertical»

app: layout_behavior="@string/appbar_scrolling_view_behavior»

tools:context=".MainActivity»

tools: showIn="@layout/app_bar_main»

android: id="@+id/content_main»

>


<RelativeLayout

android: layout_width=«match_parent»

android: layout_height=«match_parent»>


<fragment

android: id="@+id/beyondarFragment»

android:name="com.beyondar.android.fragment.BeyondarFragmentSupport»

android: layout_width=«match_parent»

android: layout_height=«match_parent» />


</RelativeLayout>


</android.support.v4.widget.NestedScrollView>

Ваша оценка очень важна

0
Шрифт
Фон

Помогите Вашим друзьям узнать о библиотеке

Скачать книгу

Если нет возможности читать онлайн, скачайте книгу файлом для электронной книжки и читайте офлайн.

fb2.zip txt txt.zip rtf.zip a4.pdf a6.pdf mobi.prc epub ios.epub fb3