# Share snapshot image

> **Note (legacy): A newer version of the Maps SDK is available**
> 
> This page uses v9.7.1 of the Mapbox Maps SDK. A newer version of the SDK is available. Learn about the latest version, v11.29.0, in the [Maps SDK documentation](https://docs.mapbox.com/android/maps/guides/).

Your browser doesn't support HTML5 video. Open [link to the video](https://docs.mapbox.com/android/android/assets/medias/maps-example-snapshot-share-activity-84e6d16f0824dc0e8030e6afa5fe3f65.mp4).

> **Note**
> 
> This example is a part of the [Mapbox Android Demo app](https://github.com/mapbox/mapbox-android-demo). You can find the values for all referenced resources in the [`res`](https://github.com/mapbox/mapbox-android-demo/tree/master/MapboxAndroidDemo/src/main/res) directory. For example, see [`res/values/activity_strings.xml`](https://github.com/mapbox/mapbox-android-demo/tree/master/MapboxAndroidDemo/src/main/res/values/activity_strings.xml) for `R.string.*` references used in this example. The dependencies can be found [here.](https://github.com/mapbox/mapbox-navigation-android-examples/blob/main/app/build.gradle) The examples use View binding. [See setup documention if necessary.](https://developer.android.com/topic/libraries/view-binding)

Title: `activity_snapshot_share`

[View on GitHub](https://github.com/mapbox/mapbox-android-demo/tree/master/MapboxAndroidDemo/src/main/res/layout/activity_snapshot_share.xml)

```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        mapbox:mapbox_cameraTargetLat="37.536172"
        mapbox:mapbox_cameraTargetLng="126.916954"
        mapbox:mapbox_cameraTilt="60"
        mapbox:mapbox_cameraZoom="9"
         />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/camera_share_snapshot_image_fab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"
        fab:fab_size="normal" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

**Java**

Title: `SnapshotShareActivity.java`

[View on GitHub](https://github.com/mapbox/mapbox-android-demo/tree/master/MapboxAndroidDemo/src/main/java/com/mapbox/mapboxandroiddemo/examples/snapshot/SnapshotShareActivity.java)

```java
package com.mapbox.mapboxandroiddemo.examples.snapshot;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.mapbox.mapboxandroiddemo.R;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.snapshotter.MapSnapshot;
import com.mapbox.mapboxsdk.snapshotter.MapSnapshotter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class SnapshotShareActivity extends AppCompatActivity {

  private MapView mapView;
  private MapboxMap mapboxMap;
  private MapSnapshotter mapSnapshotter;
  private FloatingActionButton cameraFab;
  private boolean hasStartedSnapshotGeneration;

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

    // Mapbox access token is configured here. This needs to be called either in your application
    // object or in the same activity which contains the mapview.
    Mapbox.getInstance(this, getString(R.string.access_token));

    // This contains the MapView in XML and needs to be called after the access token is configured.
    setContentView(R.layout.activity_snapshot_share);

    cameraFab = findViewById(R.id.camera_share_snapshot_image_fab);
    cameraFab.setImageResource(R.drawable.ic_camera);

    hasStartedSnapshotGeneration = false;

    mapView = findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);

    // Set a callback for when MapboxMap is ready to be used
    mapView.getMapAsync(new OnMapReadyCallback() {
      @Override
      public void onMapReady(@NonNull final MapboxMap mapboxMap) {
        SnapshotShareActivity.this.mapboxMap = mapboxMap;
        mapboxMap.setStyle(Style.SATELLITE_STREETS, new Style.OnStyleLoaded() {
          @Override
          public void onStyleLoaded(@NonNull Style style) {
            // When user clicks the map, start the snapshotting process with the given parameters
            cameraFab.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                if (!hasStartedSnapshotGeneration) {
                  hasStartedSnapshotGeneration = true;
                  Toast.makeText(SnapshotShareActivity.this, R.string.loading_snapshot_image, Toast.LENGTH_LONG).show();
                  startSnapShot(
                    mapboxMap.getProjection().getVisibleRegion().latLngBounds,
                    mapView.getMeasuredHeight(),
                    mapView.getMeasuredWidth());
                }
              }
            });
          }
        });

        // To account for new security measures regarding file management that were released with Android Nougat.
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
      }
    });
  }

  /**
   * Creates bitmap from given parameters, and creates a notification with that bitmap
   *
   * @param latLngBounds of map
   * @param height       of map
   * @param width        of map
   */
  private void startSnapShot(LatLngBounds latLngBounds, int height, int width) {
    mapboxMap.getStyle(new Style.OnStyleLoaded() {
      @Override
      public void onStyleLoaded(@NonNull Style style) {
        if (mapSnapshotter == null) {
          // Initialize snapshotter with map dimensions and given bounds
          MapSnapshotter.Options options =
            new MapSnapshotter.Options(width, height)
              .withRegion(latLngBounds)
              .withCameraPosition(mapboxMap.getCameraPosition())
              .withStyle(style.getUri());

          mapSnapshotter = new MapSnapshotter(SnapshotShareActivity.this, options);
        } else {
          // Reuse pre-existing MapSnapshotter instance
          mapSnapshotter.setSize(width, height);
          mapSnapshotter.setRegion(latLngBounds);
          mapSnapshotter.setCameraPosition(mapboxMap.getCameraPosition());
        }

        mapSnapshotter.start(new MapSnapshotter.SnapshotReadyCallback() {
          @Override
          public void onSnapshotReady(MapSnapshot snapshot) {

            Bitmap bitmapOfMapSnapshotImage = snapshot.getBitmap();

            Uri bmpUri = getLocalBitmapUri(bitmapOfMapSnapshotImage);

            Intent shareIntent = new Intent();
            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            shareIntent.setType("image/png");
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(shareIntent, "Share map image"));

            hasStartedSnapshotGeneration = false;
          }
        });
      }
    });
  }

  private Uri getLocalBitmapUri(Bitmap bmp) {
    Uri bmpUri = null;
    File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
      "share_image_" + System.currentTimeMillis() + ".png");
    FileOutputStream out = null;
    try {
      out = new FileOutputStream(file);
      bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
      try {
        out.close();
      } catch (IOException exception) {
        exception.printStackTrace();
      }
      bmpUri = Uri.fromFile(file);
    } catch (FileNotFoundException exception) {
      exception.printStackTrace();
    }
    return bmpUri;
  }

  @Override
  public void onResume() {
    super.onResume();
    mapView.onResume();
  }

  @Override
  protected void onStart() {
    super.onStart();
    mapView.onStart();
  }

  @Override
  protected void onStop() {
    super.onStop();
    mapView.onStop();
  }

  @Override
  public void onPause() {
    super.onPause();
    mapView.onPause();
    // Make sure to stop the snapshotter on pause if it exists
    if (mapSnapshotter != null) {
      mapSnapshotter.cancel();
    }
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
  }
}
```