2015-02-25 3 views
0

Эй, ребята, моя проблема немного странная. Я делаю приложение, которое требует, чтобы карта работала как первое действие. Я дам вам контекст:Карты Google не работают, если устройство перезагружено.

Приложение запущено, основное действие показывает экран приветствия с изображением (ничего особенного), а затем перенаправляется на активность карт. И здесь все идет не так. Если я запустил приложение из Android Studio, все хорошо. Отображается карта, она масштабируется в моем местоположении, я могу щелкнуть по карте и добавить маркер, я могу перетащить маркер и т. Д. Даже когда я уничтожаю приложение и очищаю кеш и запускаю приложение (на этот раз через устройство, не запускающее его из Android Studio), он работает отлично. Проблема в том, когда i перезапустите устройство и попробуйте запустить приложение. Он показывает приветственное изображение из основного вида деятельности, но когда отображается активность карт, он просто ничего не делает, кроме отображения карты мира. Я не могу сопоставить клик, он не приближается, как я его запрограммировал. Он ничего не делает.

Я пробовал обновлять ключ AP APP, менял провайдера местоположения приложения и ничего не делал. Я попытался очистить данные и кеш в системных настройках, и он работает нормально.

MapaActivity.java

public class MapaActivity extends Activity implements LocationListener{ 

    private final String TAG = "MapaActivity"; 
    private ArrayList<Bitmap> FotoLista = new ArrayList<>(); 
    //private ArrayList<String> ScreenShot = new ArrayList<>(); 
    private ArrayList<String> 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<String>(); 

     //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<?> telephonyManagerClass; 
       Object ITelephonyStub; 
       Class<?> 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<?> conmanClass = Class.forName(conman.getClass().getName()); 
       final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService"); 
       iConnectivityManagerField.setAccessible(true); 
       final Object iConnectivityManager = iConnectivityManagerField.get(conman); 
       final Class<?> 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<Address> listAddresses = geocoder.getFromLocation(ponto.latitude, ponto.longitude, 1); 
      if(null!=listAddresses&&listAddresses.size()>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!"); 
     } 
    } 

} 

layout_mapa.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 

     <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"> 

      <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" /> 

      <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" /> 

     </LinearLayout> 

     <LinearLayout 
      android:orientation="vertical" 
      android:layout_width="fill_parent" 
      android:layout_height="8dp" 
      android:background="@color/gnr_verde_mais_escuro"></LinearLayout> 

     <RelativeLayout 
      xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 

     <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" /> 

     </RelativeLayout> 

    </LinearLayout> 
</RelativeLayout> 
+0

Какое устройство вы используете? и Какой номер сборки? – bjiang

+0

Это Samsung Galaxy Tab 2 10.1. Но я пробовал в других устройствах, и проблема такая же. (Также samsung) –

+0

Это проводной, вы можете попробовать мой код [здесь] (https://github.com/jbj88817/GoogleMapExample-android) или попробовать не samsung-устройства. – bjiang

ответ

0

Это была проблема расположения. Иногда метод getLastKnownLocation возвращает значение null, потому что нет места для его поиска. Вам нужно использовать метод requestLocationUpdates, и это сработает!

Смежные вопросы