title: Google Maps doesn't work if device is restarted
body: <p>Hey guys so my problem is a little weird. I'm doing an application that requires the map to work as the first activity. I'll give you the context:</p>
  
  <p>The application is started, the main activity shows a welcome screen with an image (nothing special) and then is reedirected to th maps activity. And that's where all things go wrong. If i run the application from the Android Studio, it's all good. The map is shown, it zooms in in my location, i can click on the map and add a marker, i can drag the marker, etc. Even when i destroy the application and clear the cache and start the application (this time through the device without starting it from the Android Studio) it works just fine. The problem is when i <strong>restart the device</strong> and try to run the application. It shows the welcome image from the main activity but when the maps activity is shown, it simply doesn't do anything besides showing the map of the world. I can't mapclick, it doesn't zoom in like i programmed it to do. It doesn't do nothing.</p>
  
  <p>I've tried updating the Google APP Key, changed the app location provider and nothing did the trick. I tried cleaning the data and the cache in the system settings and it works just fine.</p>
  
  <p>MapaActivity.java</p>
  
  <pre><code>public class MapaActivity extends Activity implements LocationListener{
  
      private final String TAG = "MapaActivity";
      private ArrayList&lt;Bitmap&gt; FotoLista = new ArrayList&lt;&gt;();
      //private ArrayList&lt;String&gt; ScreenShot = new ArrayList&lt;&gt;();
      private ArrayList&lt;String&gt; fotos_caminho;
      private Uri imageUri;
      private String _Location;
      private Bitmap bitmap_screen;
  
      private boolean isMarkerChecked;
      // The minimum distance to change Updates in meters
      private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
  
      // The minimum time between updates in milliseconds
      private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
  
      //String caminho_screen;
      //Button botao;
  
      GoogleMap googleMap;
  
      // Get the  LocationManager object from the System Service LOCATION_SERVICE
      LocationManager locationManager;
  
      // Create a criteria object needed to retrieve the provider
      Criteria criteria;
  
      // Get the name of the best available provider
      String provider;
  
      LatLng ponto;
      LatLng currentPosition;
  
      private Custom_Dialog dialog;
  
      // We can use the provider immediately to get the last known location
      Location location;
  
      double latitude; // latitude
      double longitude; // longitude
  
      Marker m;
  
  // request that the provider send this activity GPS updates every 20 seconds
  
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.layout_mapa);
  
          isMarkerChecked = false;
  
          fotos_caminho = new ArrayList&lt;String&gt;();
  
          //botao = (Button) findViewById(R.id.confirmar_local);
  
          turnOnDataConnection(true,this);
          // Get the  LocationManager object from the System Service LOCATION_SERVICE
          LocationManager locationManager = (LocationManager)
                  getSystemService(LOCATION_SERVICE);
  
          // Create a criteria object needed to retrieve the provider
          criteria = new Criteria();
  
          // Get the name of the best available provider
          provider = locationManager.GPS_PROVIDER;
  
          // We can use the provider immediately to get the last known location
          //location = new Location(provider);
          location = locationManager.getLastKnownLocation(provider);
  //        Log.e(TAG, "location: " +location.getLatitude()+"lon:"+location.getLongitude());
  
          // request that the provider send this activity GPS updates every 20 seconds
          locationManager.requestLocationUpdates(provider, 20000, 0, this);
  
          createMapView(location);
  
  
  
      }
  
      public void tirafoto_func(View v){
  
          Intent intentFoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "foto_0.png");
          imageUri = Uri.fromFile(photo);
          intentFoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
          startActivityForResult(intentFoto, 0);
  
      }
  
      //Para tratar o output da camera
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
  
          if(resultCode == RESULT_OK) {
  
              if (requestCode == 0) {
                  File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                          .toString());
                  for (File temp : f.listFiles()) {
                      if (temp.getName().equals("foto_0.png")) {
                          f = temp;
                          break;
                      }
                  }
                  try {
                      String fname=new File(f.getPath()).getAbsolutePath();
                      fotos_caminho.add(fname);
  
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
  
              }
          }
  
  
          if (resultCode == RESULT_CANCELED)
          {
              return;
          }
  
          inicia_Form();
  
      }
  
  
      public static Bitmap scaleDownBitmap(Bitmap realImage, float maxImageSize,
                                           boolean filter) {
          float ratio = Math.min(
                  (float) maxImageSize / realImage.getWidth(),
                  (float) maxImageSize / realImage.getHeight());
          int width = Math.round((float) ratio * realImage.getWidth());
          int height = Math.round((float) ratio * realImage.getHeight());
  
          Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
                  height, filter);
          return newBitmap;
      }
  
      public void inicia_Form(){
  
              Intent intent = new Intent(MapaActivity.this, Form_ocorrencia.class);
              intent.putExtra("objecto", FotoLista);
              //intent.putExtra("screen", caminho_screen);
              intent.putStringArrayListExtra("caminho_1",fotos_caminho);
              intent.putExtra("long", currentPosition.longitude);
              intent.putExtra("lat", currentPosition.latitude);
  
              MapaActivity.this.startActivity(intent);
              finish();
  
      }
  
  
      private void createMapView(Location local) {
  
  
          try {
              if (null == googleMap) {
                  googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                          R.id.map)).getMap();
                  Toast.makeText(getApplicationContext(),
                          "Criei mapa", Toast.LENGTH_SHORT).show();
  
                  googleMap.setMyLocationEnabled(true);
                  System.err.println("Location Enabled");
  
                  googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                 // googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                  // myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                  // myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                  System.err.println("set map type");
                  location = local;
                  System.err.println("location"+location.getLongitude());
                      CameraUpdate center =
                              CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),
                                      location.getLongitude()));
  
                  System.err.println("Camera Update");
  
                      CameraUpdate zoom = CameraUpdateFactory.zoomTo(22);
                  System.err.println("Camera Zoom");
                      googleMap.moveCamera(center);
                  System.err.println("Camera Move");
                      googleMap.animateCamera(zoom);
                  System.err.println("Camera Animate");
  
  
  
                      CameraPosition cp = new CameraPosition.Builder()
                              .target(new LatLng(local.getLatitude(), local.getLongitude()))
                              .zoom(18)
                              .build();
                      googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
  
                  googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                      @Override
                      public void onMapClick(LatLng pont){
                          drawMarker(location, pont);
                      }
                  });
  
                  googleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
                      @Override
                      public void onMarkerDragStart(Marker marker) {
                              System.err.println("Tou a arrastar");
                      }
  
                      @Override
                      public void onMarkerDrag(Marker marker) {
  
                      }
  
                      @Override
                      public void onMarkerDragEnd(Marker marker) {
                          currentPosition = marker.getPosition();
                          drawMarker(location, currentPosition);
                      }
                  });
  
                  googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                      @Override
                      public boolean onMarkerClick(Marker marker) {
                          mostra_dialog(getApplicationContext());
                          return false;
                      }
                  });
                  /**
                   * If the map is still null after attempted initialisation,
                   * show an error to the user
                   */
                  if (null == googleMap) {
                      Toast.makeText(getApplicationContext(),
                              "Erro ao criar mapa", Toast.LENGTH_SHORT).show();
                  }
              }
          } catch (NullPointerException exception) {
              Log.e("mapApp", exception.toString());
          }
  
      }
  
      private void drawMarker(Location location, LatLng ponto){
  
  
          googleMap.clear();
          //  convert the location object to a LatLng object that can be used by the map API
          currentPosition = new LatLng(location.getLatitude(),
                  location.getLongitude());
  
          // zoom to the current location
          googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,
                  18));
  
          // add a marker to the map indicating our current position
          System.err.println("vou adicionar");
          if (googleMap !=null) {
  
              m = googleMap.addMarker(new MarkerOptions()
                      .position(currentPosition)
                      .snippet("Lat:" + location.getLatitude() + "Lng:" + location.getLongitude())
                      .draggable(true));
  
          m.setDraggable(true);
          m.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marker_v2_2));
  
          }
  
  
  
          isMarkerChecked = true;
  
          System.err.println("MarkerChecked");
  
          searches_location(ponto);
  
          mostra_dialog(getApplicationContext());
  
  
  
      }
  
  
      int bv = Build.VERSION.SDK_INT;
  
      boolean turnOnDataConnection(boolean ON,Context context)
      {
  
          try{
              if(bv == Build.VERSION_CODES.FROYO)
  
              {
                  Method dataConnSwitchmethod;
                  Class&lt;?&gt; telephonyManagerClass;
                  Object ITelephonyStub;
                  Class&lt;?&gt; ITelephonyClass;
  
                  TelephonyManager telephonyManager = (TelephonyManager) context
                          .getSystemService(Context.TELEPHONY_SERVICE);
  
                  telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
                  Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
                  getITelephonyMethod.setAccessible(true);
                  ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
                  ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
  
                  if (ON) {
                      dataConnSwitchmethod = ITelephonyClass
                              .getDeclaredMethod("enableDataConnectivity");
                  } else {
                      dataConnSwitchmethod = ITelephonyClass
                              .getDeclaredMethod("disableDataConnectivity");
                  }
                  dataConnSwitchmethod.setAccessible(true);
                  dataConnSwitchmethod.invoke(ITelephonyStub);
  
              }
              else
              {
                  //log.i("App running on Ginger bread+");
                  final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                  final Class&lt;?&gt; conmanClass = Class.forName(conman.getClass().getName());
                  final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
                  iConnectivityManagerField.setAccessible(true);
                  final Object iConnectivityManager = iConnectivityManagerField.get(conman);
                  final Class&lt;?&gt; iConnectivityManagerClass =  Class.forName(iConnectivityManager.getClass().getName());
                  final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
                  setMobileDataEnabledMethod.setAccessible(true);
                  setMobileDataEnabledMethod.invoke(iConnectivityManager, ON);
              }
  
  
              return true;
          }catch(Exception e){
              Log.e(TAG,"error turning on/off data");
  
              return false;
          }
  
      }
  
  
  
  
      @Override
      public void onLocationChanged(Location location_2) {
  
  
  
      }
  
      @Override
      public void onStatusChanged(String s, int i, Bundle bundle) {
  
      }
  
      @Override
      public void onProviderEnabled(String s) {
  
      }
  
      @Override
      public void onProviderDisabled(String s) {
  
      }
  
  
      private void mostra_dialog(Context c)
      {
          dialog = new Custom_Dialog(this, R.style.omeuestilo_dialog);
  
          dialog.setContentView(R.layout.custom_dialog);
          dialog.setTitle("Confirmar Local");
          Button ok = (Button) dialog.findViewById(R.id.ok);
          Button cancelar = (Button) dialog.findViewById(R.id.cancel);
  
          ok.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  dialog.dismiss();
                  tirafoto_func(v);
              }
          });
  
          cancelar.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                      dialog.dismiss();
              }
          });
  
          searches_location(ponto);
  
          TextView text = (TextView) dialog.findViewById(R.id.text);
          text.setText("Longitude: " + location.getLongitude() + "\n" + "Latitude: " + location.getLatitude() + "\n" + "Rua: " + _Location);
  
          WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
  
          wmlp.gravity = Gravity.TOP | Gravity.RIGHT;
          wmlp.x = 400;   //x position
          wmlp.y = 500;   //y position
  
          dialog.show();
      }
  
      public void searches_location(LatLng pont){
          ponto = pont;
          Log.e(TAG, "location_1: " +pont.latitude+"lon:"+pont.longitude);
          googleMap.animateCamera(CameraUpdateFactory.newLatLng(ponto));
  
          Toast.makeText(getApplicationContext(), "Marcado Local da Ocorrência!",
                  Toast.LENGTH_LONG).show();
  
          googleMap.clear();
          MarkerOptions m = new MarkerOptions().position(ponto).title(
                  ponto.toString());
  
  
  
         googleMap.addMarker(new MarkerOptions()
                 .draggable(true)
                 .position(ponto).title(ponto.toString())).setIcon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marker_v2_2));
  
  
  
          location.setLatitude(ponto.latitude);
          location.setLongitude(ponto.longitude);
  
  
          Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
  
          try {
              List&lt;Address&gt; listAddresses = geocoder.getFromLocation(ponto.latitude, ponto.longitude, 1);
              if(null!=listAddresses&amp;&amp;listAddresses.size()&gt;0){
                  _Location = listAddresses.get(0).getAddressLine(0);
                  // String Sub_Localidade = listAddresses.get(0).getSubLocality(); //Dá para ir buscar tipo Alto São João
                  //String Cidade = listAddresses.get(0).get
                  //DEPOIS TEM DE SE BOTAR NUMA EDIT TEXT
              }
  
              listAddresses.clear();
          } catch (IOException e) {
              e.printStackTrace();
              System.err.println("Nao consegui obter rua!");
          }
      }
  
  }
  </code></pre>
  
  <p>layout_mapa.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"&gt;
  
      &lt;LinearLayout
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"&gt;
  
          &lt;LinearLayout
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="110dp"
              android:id="@+id/linear_top"
              android:background="@color/gnr_verde_mais_claro"
              android:weightSum="1"
              android:paddingTop="5dp"
              android:paddingLeft="10dp"&gt;
  
              &lt;ImageView
                  android:layout_width="wrap_content"
                  android:layout_height="match_parent"
                  android:id="@+id/imageView2"
                  android:src="@drawable/logo_v2"
                  android:layout_weight="0.09"
                  android:paddingLeft="-21dp"
                  android:paddingRight="-15dp" /&gt;
  
              &lt;TextView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:id="@+id/textView10"
                  android:text="GNReport   |   Introduza o Local da Ocorrência"
                  android:textSize="25dp"
                  android:paddingTop="35dp"
                  android:paddingLeft="0dp"
                  android:textColor="@color/branco" /&gt;
  
          &lt;/LinearLayout&gt;
  
          &lt;LinearLayout
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="8dp"
              android:background="@color/gnr_verde_mais_escuro"&gt;&lt;/LinearLayout&gt;
  
          &lt;RelativeLayout
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"&gt;
  
          &lt;fragment xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:name="com.google.android.gms.maps.MapFragment"
              android:id="@+id/map"
              android:layout_alignParentTop="true"
              android:layout_alignParentBottom="true"
              android:layout_alignParentLeft="true"
              android:layout_alignParentRight="true" /&gt;
  
          &lt;/RelativeLayout&gt;
  
      &lt;/LinearLayout&gt;
  &lt;/RelativeLayout&gt;
  </code></pre>