Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/199.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 主服务器出现致命错误_Android_Fatal Error - Fatal编程技术网

Android 主服务器出现致命错误

Android 主服务器出现致命错误,android,fatal-error,Android,Fatal Error,它在主屏幕上显示致命错误。 现在我在这里发布日志和该来源。回答我哪里有错误以及如何清除错误。提前谢谢 11-10 11:31:50.927: V/Shravan(25876): Police 11-10 11:31:50.947: V/(25876): MainActivity's onPause Method !!! 11-10 11:31:50.977: W/dalvikvm(25876): VFY: unable to resolve static field 863 (MapAttrs)

它在主屏幕上显示致命错误。 现在我在这里发布日志和该来源。回答我哪里有错误以及如何清除错误。提前谢谢

11-10 11:31:50.927: V/Shravan(25876): Police
11-10 11:31:50.947: V/(25876): MainActivity's onPause Method !!!
11-10 11:31:50.977: W/dalvikvm(25876): VFY: unable to resolve static field 863 (MapAttrs) in Lcom/google/android/gms/R$styleable;
11-10 11:31:50.987: W/dalvikvm(25876): threadid=1: thread exiting with uncaught exception (group=0x40aeb9f0)
11-10 11:31:51.007: E/AndroidRuntime(25876): FATAL EXCEPTION: main
11-10 11:31:51.007: E/AndroidRuntime(25876): java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable
11-10 11:31:51.007: E/AndroidRuntime(25876):    at com.google.android.gms.maps.GoogleMapOptions.createFromAttributes(Unknown Source)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:279)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:268)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.Activity.setContentView(Activity.java:1837)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at shravan.nyshadh.balaji.Maps.onCreate(Maps.java:86)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.Activity.performCreate(Activity.java:4470)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.os.Looper.loop(Looper.java:137)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at android.app.ActivityThread.main(ActivityThread.java:4424)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at java.lang.reflect.Method.invokeNative(Native Method)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at java.lang.reflect.Method.invoke(Method.java:511)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
11-10 11:31:51.007: E/AndroidRuntime(25876):    at dalvik.system.NativeStart.main(Native Method)
这是主要活动。

public class MainActivity extends Activity {

    /*
     * HOSPITAL, POLICE, FIRESTATION, and AMBULANCE are constant variables that are assigned
     * to their respective emergency itent. It helps us to draw icons and perform web services
     * related activities.
     */
    private static final int HOSPITAL = 1;
    private static final int POLICE = 2;
    private static final int FIRESTATION = 3;
    private static final int AMBULANCE = 4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(Preferences.readString(this, Preferences.NAME) == null){
            startActivity(new Intent(this, Registration.class));
            if(Preferences.readString(this, Preferences.NAME) == null){
                this.finish();
            }
        } else {
            setContentView(R.layout.activity_main);
        }       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    /**
     * This is the main screen of our application. This is the first screen shown after a user has registered.
     * The registration screen only shows if it is the users first time using the application.
     * @param v
     */
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.sos_button) {
            startActivity(new Intent(this, Sos.class));
        } else if (id == R.id.firestation_button) {
            Intent firestation = new Intent(this, Maps.class);
            firestation.putExtra("key", FIRESTATION);
            startActivity(firestation);
        } else if (id == R.id.hospital_button) {
            Intent hospital = new Intent(this, Maps.class);
            hospital.putExtra("key", HOSPITAL);
            startActivity(hospital);
        } else if (id == R.id.ambulance_button) {
            Intent ambulance = new Intent(this, Maps.class);
            ambulance.putExtra("key", AMBULANCE);
            startActivity(ambulance);
        } else if (id == R.id.police_button) {
            Log.v("Shravan", "Police");
            Intent police = new Intent(this, Maps.class);
            police.putExtra("key", POLICE);
            startActivity(police);
        } else if (id == R.id.bloodbank_button) {
            Log.v("Shravan", "BloodBank");
            startActivity(new Intent(this,BloodBank.class));
        } else if (id == R.id.emergencycontact_button) {
            try{
              StringBuilder number = new StringBuilder();
              number.append("tel:");
              number.append(Preferences.readString(this, Preferences.EM_NUMBER));
              Intent callIntent = new Intent (Intent.ACTION_CALL);
              callIntent.setData(Uri.parse(number.toString()));
              startActivity(callIntent);
            }catch (ActivityNotFoundException activityException) {
                Log.e("First Response", "Call failed");
            }
        } else if (id == R.id.home_button) {
            try{
              StringBuilder number = new StringBuilder();
              number.append("tel:");
              number.append(Preferences.readString(this, Preferences.PHONE_NUMBER));
              Intent callIntent = new Intent (Intent.ACTION_CALL);
              //callIntent.setData(Uri.parse("tel:5136523144"));
              callIntent.setData(Uri.parse(number.toString()));
              startActivity(callIntent);
            }catch (ActivityNotFoundException activityException) {
                Log.e("First Response", "Call failed");
            }
        } else if (id == R.id.settings_button) {
            startActivity(new Intent(this,Settings.class));
        }
    }

    /** used upon resuming the application. 
     *
     */
    public void onResume(){
        super.onResume();
        Log.v(null, "MainActivity's onResume Method !!!");
    }

    /**
     * an empty onPause method
     */
    public void onPause(){
        super.onPause();
        Log.v(null, "MainActivity's onPause Method !!!");
    }
    /**
     * Called before interrupt to save data.
     */
    protected void onSaveInstanceState (Bundle outState){
        super.onSaveInstanceState(outState);
        // nothing needs to be saved here since nothing is changed or being used. 
    }
    /**
     * Called during onResume() to restore data.
     */
    protected void onRestoreInstanceState (Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        // Restore session score
        // nothing needs to be restored here since nothing is used previously. 
    }
}
/**
 * In this activity, emergency icons are drawn according to the view that was clicked
 * from MainActivity. Icons are numbered in order of increasing distance 
 * from user's current location.
 *
 */
public class Maps extends FragmentActivity {
    private GoogleMap myMap;
    LocationManager lm;
    LocationListener locationListener;
    Location mLoc;
    int code;
    boolean zoomb = true;
    ArrayList<String> ambulances = new ArrayList<String>();
    boolean directioncheck = false;

    // LIST VIEW
    ListView listview;
    ArrayList<String> itemlist = new ArrayList<String>();
    ArrayAdapter<String> adapter;
    ArrayList<Marker> markerlist;

    Direction direction = new Direction();
    ArrayList<LatLng> pline = new ArrayList<LatLng>();
    LatLng currentmarker;
    Integer cid;

    String provider = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);


        /*
         * Check if any of the radios (Mobile Data or Wi-Fi) are on. 
         */
        final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if(telephonyManager.getDataState() == 0 && wifiManager.isWifiEnabled() == false && manager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) {
            AlertDialog.Builder ad = new AlertDialog.Builder(Maps.this);
            ad.setTitle("First-Responder");
            ad.setMessage("Your network and gps providers are off. Please enable one of them.");
            ad.setPositiveButton("Network", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    AlertDialog.Builder network = new AlertDialog.Builder(Maps.this);
                    network.setTitle("First-Responder");
                    network.setMessage("Please choose between Wi-Fi and Mobile Data");
                    network.setPositiveButton("Wi-Fi", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
                            startActivity(intent);
                            provider = "network";
                        }
                    });
                    network.setNegativeButton("Mobile Data", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent (android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
                            startActivity(intent);
                            provider = "network";
                        }
                    });
                    network.show();
                }
            });
            ad.setNegativeButton("GPS", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                    provider = "gps";
                }
            });
            ad.show();
        }

        if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED) {
            provider = "network";
        } else if (wifiManager.isWifiEnabled()) {
            provider = "network";
        } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = "gps";
        }

        listview = (ListView)findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,itemlist);
        listview.setAdapter(adapter);
        markerlist = new ArrayList<Marker>();

        FragmentManager myFragmentManager = getSupportFragmentManager();
        SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
        myMap = mySupportMapFragment.getMap();
        myMap.setMyLocationEnabled(true);
        myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener();
        Intent intent = getIntent();
        code = intent.getIntExtra("key", 0);

        if (provider != null) {
            mLoc = lm.getLastKnownLocation(provider);
        }

        if (mLoc != null) {
            query(mLoc);
        }

        listview.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                //Toast.makeText(getApplicationContext(), Integer.toString(markerlist.size()), Toast.LENGTH_LONG).show();
                LatLng point = markerlist.get(position).getPosition();
                CameraUpdate center = CameraUpdateFactory.newLatLng(point);
                myMap.animateCamera(center, 2000, null);
            }
        });
        myMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(final Marker marker) {
                // TODO Auto-generated method stub
                AlertDialog.Builder ad = new AlertDialog.Builder(Maps.this);
                ad.setTitle("First-Responder");
                ad.setMessage("Would you like directions?");
                ad.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick( DialogInterface dialog, int arg1) {
                        myMap.clear();
                        query(mLoc);
                        currentmarker = marker.getPosition();
                        LatLng pt = marker.getPosition();
                        direction.getmapsinfo(myMap, pt, mLoc, itemlist, adapter);
                        listview.setClickable(false);
                    }
                });
                ad.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        //ok, do nothing
                        dialog.cancel();
                    }
                });
                ad.show();
            }
        });
    }

    /**
     * This method takes in a parameter loc, which is the user's current location. Then, according to the view
     * pressed from MainActivity the according case is executed. The method performs a Google nearby search and
     * returns a JSON String for parsing.
     * @param loc
     */
    public void query(Location loc) {
        switch (code) {
        case 1:
            new GetHospitals()
                    .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                            + Double.toString(mLoc.getLatitude())
                            + ","
                            + Double.toString(mLoc.getLongitude())
                            + "&rankby=distance&types=hospital&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ");
            break;
        case 2:
            new GetHospitals()
                    .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                            + Double.toString(mLoc.getLatitude())
                            + ","
                            + Double.toString(mLoc.getLongitude())
                            + "&rankby=distance&types=police&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ");
            break;
        case 3:
            new GetHospitals()
                    .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                            + Double.toString(mLoc.getLatitude())
                            + ","
                            + Double.toString(mLoc.getLongitude())
                            + "&rankby=distance&types=fire_station&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ");
            break;
        case 4:
            Database db = new Database(Maps.this);
            LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude());
            ambulances = db.sort(point);
            placemarkers(ambulances);
            db.close();
            break;
        }
    }


    /**
     * Assigns a number according to distance the nearest ambulance.
     * @param ambulances
     */
    private void placemarkers(ArrayList<String> ambulances){
        Bitmap myWrittenBitmap;     
        for(int i = 0; i < ambulances.size(); i++){
            String item = ambulances.get(i);
            Marker m;
            myWrittenBitmap = customImage(i+1, R.drawable.ambulance_launcher);

            String[] values = item.split(",");
            String name = values[0];
            String number = values[1];
            String itemlat = values[2];
            String itemlong = values[3];

            LatLng point = new LatLng(Double.parseDouble(itemlat), Double.parseDouble(itemlong));
            m = myMap.addMarker(new MarkerOptions().position(point).title(name).snippet(number).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
            markerlist.add(m);
            if(!directioncheck){
                itemlist.add(Integer.toString(i+1)+"  "+ name);
                adapter.notifyDataSetChanged();
            }
        }
        LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude());
        CameraUpdate center = CameraUpdateFactory.newLatLng(point);
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
        myMap.moveCamera(center);
        myMap.animateCamera(zoom);
    }


    /**
     * This method takes in an index and a picture (represented as an int) 
     * and creates a canvas on which to paint and write the number on.
     * @param index
     * @param resource
     * @return bitmap
     */
    // adding custom images to markers.
    private Bitmap customImage(int index, int resource ){
        Bitmap bm;
        Bitmap myWrittenBitmap;
        Canvas canvas;
        Paint txtPaint;

        bm = BitmapFactory.decodeResource(getResources(), resource);
        myWrittenBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_4444);
        // create a Canvas on which to draw and a Paint to write text.
        canvas = new Canvas(myWrittenBitmap);
        txtPaint = new Paint();
        txtPaint.setColor(Color.RED);
        txtPaint.setTextSize(12);
        txtPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        txtPaint.setTypeface(Typeface.DEFAULT_BOLD);
        //draw ref bitmap then text on our canvas
        canvas.drawBitmap(bm, 0, 0, null);
        canvas.drawText(Integer.toString(index), 10,10 , txtPaint);
        return myWrittenBitmap;

    }

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null) {
                mLoc = new Location(loc);
                //query(mLoc);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            Context context = Maps.this;
            AlertDialog.Builder ad = new AlertDialog.Builder(context);
            ad.setTitle("Warning!");
            ad.setMessage("Provider: " + provider + " disabled");
            if(provider.equals("network")) {
                String button1String = "Enable network";
                ad.setPositiveButton(button1String, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                });
            }
            ad.show();
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.maps, menu);
        return true;
    }

    public String readConnectionString(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("ConnectionString", "Failed to connect");
            }
        } catch (Exception e) {
            Log.d("ConnectionString", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

    private class GetHospitals extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return readConnectionString(urls[0]);
        }

        protected void onPostExecute(String JSONString) {
            try {
                JSONObject jsonObject = new JSONObject(JSONString);
                JSONArray EmergencyItems = new JSONArray(
                        jsonObject.getString("results"));
                for (int i = 0; i < EmergencyItems.length(); i++) {
                    JSONObject EmergencyItem = EmergencyItems.getJSONObject(i);
                    Double lat = Double.parseDouble(EmergencyItem
                            .getJSONObject("geometry")
                            .getJSONObject("location").getString("lat"));
                    Double lng = Double.parseDouble(EmergencyItem
                            .getJSONObject("geometry")
                            .getJSONObject("location").getString("lng"));
                    LatLng point = new LatLng(lat,lng);
                    Bitmap myWrittenBitmap;
                    Marker m;
                    switch (code) {
                    case 1:
                        myWrittenBitmap = customImage(i+1, R.drawable.hsp_launcher);
                         m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
                        if(directioncheck == false){
                            itemlist.add(Integer.toString(i+1)+"  "+ EmergencyItem.getString("name"));
                            adapter.notifyDataSetChanged();
                        }
                        markerlist.add(m);
                        break;
                    case 2:
                        myWrittenBitmap = customImage(i+1, R.drawable.pol_launcher);
                        m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
                        if(directioncheck == false){
                            itemlist.add(Integer.toString(i+1)+"  "+ EmergencyItem.getString("name"));
                            adapter.notifyDataSetChanged();
                        }
                        markerlist.add(m);
                        break;
                    case 3:                     
                        myWrittenBitmap = customImage(i+1, R.drawable.fire_launcher);
                        m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
                        if(directioncheck == false){
                            itemlist.add(Integer.toString(i+1)+"  "+ EmergencyItem.getString("name"));
                            adapter.notifyDataSetChanged();
                        }
                        markerlist.add(m);
                        break;
                    }
                }
                if(zoomb) {
                    LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude());
                    CameraUpdate center = CameraUpdateFactory.newLatLng(point);
                    CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
                    myMap.moveCamera(center);
                    myMap.animateCamera(zoom);
                    zoomb=false;
                }
            } catch (Exception e) {
                Log.d("EmergencyItem", e.getLocalizedMessage());
            }
        }
    }

    /** used upon resuming the application. 
     *
     */
    @Override
    public void onResume(){
        super.onResume();
//      if(provider == "network") {
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
//      } else if (provider == "gps") {
//          lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//      }
        Log.v(null, "Maps's onResume Method !!!");      
    }
    /**
     * Android onPause method. Clears any stored location in location manager.
     */
    @Override
    public void onPause(){
        super.onPause();
        lm.removeUpdates(locationListener);
        zoomb = true;
        Log.v(null, "Maps's onPause Method !!!");
    }

    /**
     * Android onSaveInstanceState method. Here, the
     * driving instructions, latitudes and longitudes
     * are stored.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(direction.getDirections() != null){
            Log.v("!NullDirection", "!NULL");
            outState.putStringArrayList("DIRECTIONS", direction.getDirections());
            Preferences.writeLatLng(this, Preferences.MLAT, currentmarker);
        } else {
            Log.v("NullDirection", "NULL");
        }
    }

    /**
     * 
     */
    @Override
    protected void onRestoreInstanceState(Bundle inputState){
        Log.v("INRESTORE", "onRestoreInstanceState");
        if(inputState != null){
            if(inputState.containsKey("DIRECTIONS")){
                itemlist.clear();
                //adapter.clear();
                adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,itemlist);
                ArrayList<String> tempitemlist = inputState.getStringArrayList("DIRECTIONS");
                Log.v("FIRST DIRECTION", Integer.toString(itemlist.size()));
                for(int i = 0; i < tempitemlist.size(); i++){
                    itemlist.add(tempitemlist.get(i));
                    adapter.notifyDataSetChanged();
                }
                directioncheck = true;
            }
            if(Preferences.readMarker(this, Preferences.MLAT) != null){
                LatLng pts = Preferences.readMarker(this, Preferences.MLAT);
                currentmarker = pts;
                direction.getmapsinfo(myMap, pts, mLoc, itemlist, adapter);
            }
        }
    }
}
这是地图类。

public class MainActivity extends Activity {

    /*
     * HOSPITAL, POLICE, FIRESTATION, and AMBULANCE are constant variables that are assigned
     * to their respective emergency itent. It helps us to draw icons and perform web services
     * related activities.
     */
    private static final int HOSPITAL = 1;
    private static final int POLICE = 2;
    private static final int FIRESTATION = 3;
    private static final int AMBULANCE = 4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(Preferences.readString(this, Preferences.NAME) == null){
            startActivity(new Intent(this, Registration.class));
            if(Preferences.readString(this, Preferences.NAME) == null){
                this.finish();
            }
        } else {
            setContentView(R.layout.activity_main);
        }       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    /**
     * This is the main screen of our application. This is the first screen shown after a user has registered.
     * The registration screen only shows if it is the users first time using the application.
     * @param v
     */
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.sos_button) {
            startActivity(new Intent(this, Sos.class));
        } else if (id == R.id.firestation_button) {
            Intent firestation = new Intent(this, Maps.class);
            firestation.putExtra("key", FIRESTATION);
            startActivity(firestation);
        } else if (id == R.id.hospital_button) {
            Intent hospital = new Intent(this, Maps.class);
            hospital.putExtra("key", HOSPITAL);
            startActivity(hospital);
        } else if (id == R.id.ambulance_button) {
            Intent ambulance = new Intent(this, Maps.class);
            ambulance.putExtra("key", AMBULANCE);
            startActivity(ambulance);
        } else if (id == R.id.police_button) {
            Log.v("Shravan", "Police");
            Intent police = new Intent(this, Maps.class);
            police.putExtra("key", POLICE);
            startActivity(police);
        } else if (id == R.id.bloodbank_button) {
            Log.v("Shravan", "BloodBank");
            startActivity(new Intent(this,BloodBank.class));
        } else if (id == R.id.emergencycontact_button) {
            try{
              StringBuilder number = new StringBuilder();
              number.append("tel:");
              number.append(Preferences.readString(this, Preferences.EM_NUMBER));
              Intent callIntent = new Intent (Intent.ACTION_CALL);
              callIntent.setData(Uri.parse(number.toString()));
              startActivity(callIntent);
            }catch (ActivityNotFoundException activityException) {
                Log.e("First Response", "Call failed");
            }
        } else if (id == R.id.home_button) {
            try{
              StringBuilder number = new StringBuilder();
              number.append("tel:");
              number.append(Preferences.readString(this, Preferences.PHONE_NUMBER));
              Intent callIntent = new Intent (Intent.ACTION_CALL);
              //callIntent.setData(Uri.parse("tel:5136523144"));
              callIntent.setData(Uri.parse(number.toString()));
              startActivity(callIntent);
            }catch (ActivityNotFoundException activityException) {
                Log.e("First Response", "Call failed");
            }
        } else if (id == R.id.settings_button) {
            startActivity(new Intent(this,Settings.class));
        }
    }

    /** used upon resuming the application. 
     *
     */
    public void onResume(){
        super.onResume();
        Log.v(null, "MainActivity's onResume Method !!!");
    }

    /**
     * an empty onPause method
     */
    public void onPause(){
        super.onPause();
        Log.v(null, "MainActivity's onPause Method !!!");
    }
    /**
     * Called before interrupt to save data.
     */
    protected void onSaveInstanceState (Bundle outState){
        super.onSaveInstanceState(outState);
        // nothing needs to be saved here since nothing is changed or being used. 
    }
    /**
     * Called during onResume() to restore data.
     */
    protected void onRestoreInstanceState (Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        // Restore session score
        // nothing needs to be restored here since nothing is used previously. 
    }
}
/**
 * In this activity, emergency icons are drawn according to the view that was clicked
 * from MainActivity. Icons are numbered in order of increasing distance 
 * from user's current location.
 *
 */
public class Maps extends FragmentActivity {
    private GoogleMap myMap;
    LocationManager lm;
    LocationListener locationListener;
    Location mLoc;
    int code;
    boolean zoomb = true;
    ArrayList<String> ambulances = new ArrayList<String>();
    boolean directioncheck = false;

    // LIST VIEW
    ListView listview;
    ArrayList<String> itemlist = new ArrayList<String>();
    ArrayAdapter<String> adapter;
    ArrayList<Marker> markerlist;

    Direction direction = new Direction();
    ArrayList<LatLng> pline = new ArrayList<LatLng>();
    LatLng currentmarker;
    Integer cid;

    String provider = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);


        /*
         * Check if any of the radios (Mobile Data or Wi-Fi) are on. 
         */
        final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if(telephonyManager.getDataState() == 0 && wifiManager.isWifiEnabled() == false && manager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) {
            AlertDialog.Builder ad = new AlertDialog.Builder(Maps.this);
            ad.setTitle("First-Responder");
            ad.setMessage("Your network and gps providers are off. Please enable one of them.");
            ad.setPositiveButton("Network", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    AlertDialog.Builder network = new AlertDialog.Builder(Maps.this);
                    network.setTitle("First-Responder");
                    network.setMessage("Please choose between Wi-Fi and Mobile Data");
                    network.setPositiveButton("Wi-Fi", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
                            startActivity(intent);
                            provider = "network";
                        }
                    });
                    network.setNegativeButton("Mobile Data", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent (android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
                            startActivity(intent);
                            provider = "network";
                        }
                    });
                    network.show();
                }
            });
            ad.setNegativeButton("GPS", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                    provider = "gps";
                }
            });
            ad.show();
        }

        if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED) {
            provider = "network";
        } else if (wifiManager.isWifiEnabled()) {
            provider = "network";
        } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = "gps";
        }

        listview = (ListView)findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,itemlist);
        listview.setAdapter(adapter);
        markerlist = new ArrayList<Marker>();

        FragmentManager myFragmentManager = getSupportFragmentManager();
        SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
        myMap = mySupportMapFragment.getMap();
        myMap.setMyLocationEnabled(true);
        myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener();
        Intent intent = getIntent();
        code = intent.getIntExtra("key", 0);

        if (provider != null) {
            mLoc = lm.getLastKnownLocation(provider);
        }

        if (mLoc != null) {
            query(mLoc);
        }

        listview.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                //Toast.makeText(getApplicationContext(), Integer.toString(markerlist.size()), Toast.LENGTH_LONG).show();
                LatLng point = markerlist.get(position).getPosition();
                CameraUpdate center = CameraUpdateFactory.newLatLng(point);
                myMap.animateCamera(center, 2000, null);
            }
        });
        myMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(final Marker marker) {
                // TODO Auto-generated method stub
                AlertDialog.Builder ad = new AlertDialog.Builder(Maps.this);
                ad.setTitle("First-Responder");
                ad.setMessage("Would you like directions?");
                ad.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick( DialogInterface dialog, int arg1) {
                        myMap.clear();
                        query(mLoc);
                        currentmarker = marker.getPosition();
                        LatLng pt = marker.getPosition();
                        direction.getmapsinfo(myMap, pt, mLoc, itemlist, adapter);
                        listview.setClickable(false);
                    }
                });
                ad.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        //ok, do nothing
                        dialog.cancel();
                    }
                });
                ad.show();
            }
        });
    }

    /**
     * This method takes in a parameter loc, which is the user's current location. Then, according to the view
     * pressed from MainActivity the according case is executed. The method performs a Google nearby search and
     * returns a JSON String for parsing.
     * @param loc
     */
    public void query(Location loc) {
        switch (code) {
        case 1:
            new GetHospitals()
                    .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                            + Double.toString(mLoc.getLatitude())
                            + ","
                            + Double.toString(mLoc.getLongitude())
                            + "&rankby=distance&types=hospital&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ");
            break;
        case 2:
            new GetHospitals()
                    .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                            + Double.toString(mLoc.getLatitude())
                            + ","
                            + Double.toString(mLoc.getLongitude())
                            + "&rankby=distance&types=police&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ");
            break;
        case 3:
            new GetHospitals()
                    .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                            + Double.toString(mLoc.getLatitude())
                            + ","
                            + Double.toString(mLoc.getLongitude())
                            + "&rankby=distance&types=fire_station&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ");
            break;
        case 4:
            Database db = new Database(Maps.this);
            LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude());
            ambulances = db.sort(point);
            placemarkers(ambulances);
            db.close();
            break;
        }
    }


    /**
     * Assigns a number according to distance the nearest ambulance.
     * @param ambulances
     */
    private void placemarkers(ArrayList<String> ambulances){
        Bitmap myWrittenBitmap;     
        for(int i = 0; i < ambulances.size(); i++){
            String item = ambulances.get(i);
            Marker m;
            myWrittenBitmap = customImage(i+1, R.drawable.ambulance_launcher);

            String[] values = item.split(",");
            String name = values[0];
            String number = values[1];
            String itemlat = values[2];
            String itemlong = values[3];

            LatLng point = new LatLng(Double.parseDouble(itemlat), Double.parseDouble(itemlong));
            m = myMap.addMarker(new MarkerOptions().position(point).title(name).snippet(number).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
            markerlist.add(m);
            if(!directioncheck){
                itemlist.add(Integer.toString(i+1)+"  "+ name);
                adapter.notifyDataSetChanged();
            }
        }
        LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude());
        CameraUpdate center = CameraUpdateFactory.newLatLng(point);
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
        myMap.moveCamera(center);
        myMap.animateCamera(zoom);
    }


    /**
     * This method takes in an index and a picture (represented as an int) 
     * and creates a canvas on which to paint and write the number on.
     * @param index
     * @param resource
     * @return bitmap
     */
    // adding custom images to markers.
    private Bitmap customImage(int index, int resource ){
        Bitmap bm;
        Bitmap myWrittenBitmap;
        Canvas canvas;
        Paint txtPaint;

        bm = BitmapFactory.decodeResource(getResources(), resource);
        myWrittenBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_4444);
        // create a Canvas on which to draw and a Paint to write text.
        canvas = new Canvas(myWrittenBitmap);
        txtPaint = new Paint();
        txtPaint.setColor(Color.RED);
        txtPaint.setTextSize(12);
        txtPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        txtPaint.setTypeface(Typeface.DEFAULT_BOLD);
        //draw ref bitmap then text on our canvas
        canvas.drawBitmap(bm, 0, 0, null);
        canvas.drawText(Integer.toString(index), 10,10 , txtPaint);
        return myWrittenBitmap;

    }

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null) {
                mLoc = new Location(loc);
                //query(mLoc);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            Context context = Maps.this;
            AlertDialog.Builder ad = new AlertDialog.Builder(context);
            ad.setTitle("Warning!");
            ad.setMessage("Provider: " + provider + " disabled");
            if(provider.equals("network")) {
                String button1String = "Enable network";
                ad.setPositiveButton(button1String, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                });
            }
            ad.show();
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.maps, menu);
        return true;
    }

    public String readConnectionString(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("ConnectionString", "Failed to connect");
            }
        } catch (Exception e) {
            Log.d("ConnectionString", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

    private class GetHospitals extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return readConnectionString(urls[0]);
        }

        protected void onPostExecute(String JSONString) {
            try {
                JSONObject jsonObject = new JSONObject(JSONString);
                JSONArray EmergencyItems = new JSONArray(
                        jsonObject.getString("results"));
                for (int i = 0; i < EmergencyItems.length(); i++) {
                    JSONObject EmergencyItem = EmergencyItems.getJSONObject(i);
                    Double lat = Double.parseDouble(EmergencyItem
                            .getJSONObject("geometry")
                            .getJSONObject("location").getString("lat"));
                    Double lng = Double.parseDouble(EmergencyItem
                            .getJSONObject("geometry")
                            .getJSONObject("location").getString("lng"));
                    LatLng point = new LatLng(lat,lng);
                    Bitmap myWrittenBitmap;
                    Marker m;
                    switch (code) {
                    case 1:
                        myWrittenBitmap = customImage(i+1, R.drawable.hsp_launcher);
                         m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
                        if(directioncheck == false){
                            itemlist.add(Integer.toString(i+1)+"  "+ EmergencyItem.getString("name"));
                            adapter.notifyDataSetChanged();
                        }
                        markerlist.add(m);
                        break;
                    case 2:
                        myWrittenBitmap = customImage(i+1, R.drawable.pol_launcher);
                        m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
                        if(directioncheck == false){
                            itemlist.add(Integer.toString(i+1)+"  "+ EmergencyItem.getString("name"));
                            adapter.notifyDataSetChanged();
                        }
                        markerlist.add(m);
                        break;
                    case 3:                     
                        myWrittenBitmap = customImage(i+1, R.drawable.fire_launcher);
                        m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap)));
                        if(directioncheck == false){
                            itemlist.add(Integer.toString(i+1)+"  "+ EmergencyItem.getString("name"));
                            adapter.notifyDataSetChanged();
                        }
                        markerlist.add(m);
                        break;
                    }
                }
                if(zoomb) {
                    LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude());
                    CameraUpdate center = CameraUpdateFactory.newLatLng(point);
                    CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
                    myMap.moveCamera(center);
                    myMap.animateCamera(zoom);
                    zoomb=false;
                }
            } catch (Exception e) {
                Log.d("EmergencyItem", e.getLocalizedMessage());
            }
        }
    }

    /** used upon resuming the application. 
     *
     */
    @Override
    public void onResume(){
        super.onResume();
//      if(provider == "network") {
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
//      } else if (provider == "gps") {
//          lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//      }
        Log.v(null, "Maps's onResume Method !!!");      
    }
    /**
     * Android onPause method. Clears any stored location in location manager.
     */
    @Override
    public void onPause(){
        super.onPause();
        lm.removeUpdates(locationListener);
        zoomb = true;
        Log.v(null, "Maps's onPause Method !!!");
    }

    /**
     * Android onSaveInstanceState method. Here, the
     * driving instructions, latitudes and longitudes
     * are stored.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(direction.getDirections() != null){
            Log.v("!NullDirection", "!NULL");
            outState.putStringArrayList("DIRECTIONS", direction.getDirections());
            Preferences.writeLatLng(this, Preferences.MLAT, currentmarker);
        } else {
            Log.v("NullDirection", "NULL");
        }
    }

    /**
     * 
     */
    @Override
    protected void onRestoreInstanceState(Bundle inputState){
        Log.v("INRESTORE", "onRestoreInstanceState");
        if(inputState != null){
            if(inputState.containsKey("DIRECTIONS")){
                itemlist.clear();
                //adapter.clear();
                adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,itemlist);
                ArrayList<String> tempitemlist = inputState.getStringArrayList("DIRECTIONS");
                Log.v("FIRST DIRECTION", Integer.toString(itemlist.size()));
                for(int i = 0; i < tempitemlist.size(); i++){
                    itemlist.add(tempitemlist.get(i));
                    adapter.notifyDataSetChanged();
                }
                directioncheck = true;
            }
            if(Preferences.readMarker(this, Preferences.MLAT) != null){
                LatLng pts = Preferences.readMarker(this, Preferences.MLAT);
                currentmarker = pts;
                direction.getmapsinfo(myMap, pts, mLoc, itemlist, adapter);
            }
        }
    }
}
/**
*在此活动中,将根据单击的视图绘制紧急图标
*来自主要活动。图标按距离增加的顺序编号
*从用户的当前位置。
*
*/
公共类映射扩展了碎片活动{
私人谷歌地图;
位置经理lm;
LocationListener LocationListener;
位置mLoc;
int代码;
布尔zoomb=true;
ArrayList救护车=新ArrayList();
布尔方向检查=false;
//列表视图
列表视图列表视图;
ArrayList itemlist=新建ArrayList();
阵列适配器;
ArrayList markerlist;
方向=新方向();
ArrayList pline=新的ArrayList();
板条电流标记;
整数cid;
字符串提供程序=”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
/*
*检查是否有任何收音机(移动数据或Wi-Fi)打开。
*/
最终WifiManager=(WifiManager)this.getSystemService(Context.WIFI_服务);
TelephonyManager TelephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_服务);
LocationManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
if(telephonyManager.getDataState()==0&&wifiManager.isWifiEnabled()==false&&manager.isProviderEnabled(LocationManager.GPS\u PROVIDER)==false){
AlertDialog.Builder ad=新建AlertDialog.Builder(Maps.this);
广告标题(“第一响应者”);
ad.setMessage(“您的网络和gps提供商已关闭。请启用其中一个。”);
ad.setPositiveButton(“网络”,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
//TODO自动生成的方法存根
AlertDialog.Builder网络=新建AlertDialog.Builder(Maps.this);
网络设置标题(“第一响应者”);
network.setMessage(“请在Wi-Fi和移动数据之间进行选择”);
network.setPositiveButton(“Wi-Fi”,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
//TODO自动生成的方法存根
意向意向=新意向(android.provider.Settings.ACTION\u WIFI\u设置);
星触觉(意向);
provider=“网络”;
}
});
network.setNegativeButton(“移动数据”,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
//TODO自动生成的方法存根
意向意向=新意向(android.provider.Settings.ACTION\u DATA\u ROAMING\u Settings);
星触觉(意向);
provider=“网络”;
}
});
network.show();
}
});
ad.setNegativeButton(“GPS”,新建对话框接口.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
//TODO自动生成的方法存根
意向意向=新意向(android.provider.Settings.ACTION\u LOCATION\u SOURCE\u Settings);
星触觉(意向);
provider=“gps”;
}
});
广告秀();
}
if(telephonyManager.getDataState()==telephonyManager.DATA\u已连接){
provider=“网络”;
}else if(wifiManager.isWifiEnabled()){
provider=“网络”;
}else if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
provider=“gps”;
}
listview=(listview)findViewById(R.id.listview);
adapter=newarrayadapter(这是android.R.layout.simple\u list\u item\u 1,itemlist);
setAdapter(适配器);
markerlist=newarraylist();
FragmentManager myFragmentManager=getSupportFragmentManager();
SupportMapFragment mySupportMapFragment=(SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap=mySupportMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
lm=(LocationManager)getSystemService(Context.LOCATION\u服务);
locationListener=新建MyLocationListener();
Intent=getIntent();
代码=intent.getIntExtra(“键”,0);
if(提供程序!=null){
mLoc=lm.getLastKnownLocation(提供者);
}
如果(mLoc!=null){
查询(mLoc);
}
setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父视图、视图、整型位置、,
长id){
//Toast.makeText(getApplicationContext(),Integer.toString(markerlist.size()),Toast.LENGTH_LONG.show();
LatLng point=markerlist.get(position).getPosition();
CameraUpdate center=CameraUpdateFactory.newLatLng(点);
animateCamera(中心,2000,空);
}
});
myMap.setOnInfoWindowClickListener(新的OnInfoWindowClickListener(){
@凌驾
公共信息窗口