@Override
public void onCreate (Bundle savedInstanceState) {
super. onCreate (savedInstanceState);
// Hide the window title.
requestWindowFeature (Window. FEATURE_NO_TITLE);
setContentView(R.layout.simple_camera);
mBeyondarFragment = (BeyondarFragmentSupport) getSupportFragmentManager () .findFragmentById(R.id.beyondarFragment);
// We also can see the Frames per seconds
mBeyondarFragment.showFPS (false);
// We create the world and fill it…
mWorld = CustomWorldHelper.generateObjects (this, mCurrentLocation);
// … and send it to the fragment
mBeyondarFragment.setWorld (mWorld);
LowPassFilter.ALPHA = 0.003f;
buildGoogleApiClient ();
}
/**
* Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient () {
mGoogleApiClient = new GoogleApiClient. Builder (this)
.addConnectionCallbacks (this)
.addOnConnectionFailedListener (this)
.addApi (LocationServices. API)
.build ();
createLocationRequest ();
}
protected void createLocationRequest () {
mLocationRequest = LocationRequest.create ();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval (10000);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval (5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
public void onStart () {
super. onStart ();
mGoogleApiClient.connect ();
}
@Override
public void onStop () {
super. onStop ();
mGoogleApiClient. disconnect ();
}
@Override
public void onResume () {
super. onResume ();
// Within {@code onPause ()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected ()) {
startLocationUpdates ();
}
}
@Override
protected void onPause () {
super. onPause ();
// Stop location updates to save battery, but don’t disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected ()) {
stopLocationUpdates ();
}
}
protected void startLocationUpdates () {
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) {
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»
}
}
В файл манифеста добавим:
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 Map добавим Google API Key в файл манифеста. Для того получим ключ в Google Developers Console и добавим в тег файла манифеста.
Читать дальше