Java 如果设备重新启动,谷歌地图将无法工作

Java 如果设备重新启动,谷歌地图将无法工作,java,android,google-maps,Java,Android,Google Maps,嘿,伙计们,我的问题有点奇怪。我正在做一个应用程序,它需要地图作为第一个活动。我将向您介绍以下内容: 应用程序启动后,主活动将显示一个欢迎屏幕,屏幕上显示一个图像“无特殊”,然后重新定向到“地图”活动。这就是所有事情出错的地方。如果我从Android Studio运行应用程序,一切都很好。地图显示,它在我的位置放大,我可以单击地图并添加标记,我可以拖动标记,等等。即使我销毁应用程序并清除缓存,这次通过设备启动应用程序,而无需从Android Studio启动应用程序,它也可以正常工作。问题是当我

嘿,伙计们,我的问题有点奇怪。我正在做一个应用程序,它需要地图作为第一个活动。我将向您介绍以下内容:

应用程序启动后,主活动将显示一个欢迎屏幕,屏幕上显示一个图像“无特殊”,然后重新定向到“地图”活动。这就是所有事情出错的地方。如果我从Android Studio运行应用程序,一切都很好。地图显示,它在我的位置放大,我可以单击地图并添加标记,我可以拖动标记,等等。即使我销毁应用程序并清除缓存,这次通过设备启动应用程序,而无需从Android Studio启动应用程序,它也可以正常工作。问题是当我重新启动设备并尝试运行应用程序时。它显示了主活动中的欢迎图像,但当显示“地图”活动时,它除了显示世界地图外,什么也不做。我不能映射单击,它不像我编程的那样放大。它什么也没做

我尝试过更新Google应用程序密钥,更改了应用程序位置提供商,但没有任何效果。我尝试在系统设置中清理数据和缓存,效果很好

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>

这是一个位置问题。有时getLastKnownLocation方法返回null,因为没有可供检索的位置。您需要使用requestLocationUpdates方法,这将起作用

你用过什么设备?那么版本号是多少?它是三星Galaxy Tab 2 10.1。但我尝试了其他设备,问题也是一样的。此外,三星是有线的,你可以试试我的代码,或者在非三星设备上试试。谢谢你,bijang,但是你的GPS提供商在哪里?我需要设置它以便放大到我的位置。