Невозможно поднять тост широты и долготы - PullRequest
1 голос
/ 27 апреля 2011

Я работаю над приложением, которое отображает широту и долготу с помощью LocationManager и LocationListener.При запуске приложения появляется сообщение об ошибке «Извините, система процессов не отвечает».Это происходит, когда я задаю широту и долготу либо вручную из эмулятора управления в DDMS, либо из командной строки, используя telnet.

Java-код:

public class LocationFinder extends Activity {

private LocationManager locManager;
private LocationListener locListener;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    locListener = new MyLocationListener();

    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}

private class MyLocationListener implements LocationListener{

    @Override
    public void onLocationChanged(Location loc) {
        // TODO Auto-generated method stub

        if(loc != null){
            Toast.makeText(getBaseContext(), "Latitude: " +   loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

}

}

И яустановили следующие разрешения в manifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />

Эмулятор также включен hw.gps.

Я хотел бы знать, если что-то не так с моим кодом.Спасибо

Ответы [ 3 ]

0 голосов
/ 03 апреля 2013
  //  Des: Start Device's GPS and get current latitude and longitude
     public void GPS() throws IOException {

 //  Des: This is a background service and called after every 10 minutes and fetch                    latitude-longitude values
     background = new Thread(new Runnable() {
     @Override
     public void run() {             
     for (int i = 0; i < j; i++) {
        if (ProjectStaticVariable.GPSExit == true ) {
        try {
            Thread.sleep(600000);   //10 minutes
            mainhandler.sendMessage(mainhandler.obtainMessage());
            j++;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
         }
       }
    }
  }
});

background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {

//   Check Internet status
    isInternetPresent = cd.isConnectingToInternet();
    if (isInternetPresent) {

        lat_long_Service_flag = true;                   
        mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener(getApplicationContext());
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0,  mlocListener);

        mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    }
  }
 };
}

 //   Des: Location Listener through which we get current latitude and longitude
     public class MyLocationListener implements LocationListener {

     public MyLocationListener(Context mContext) {}

     public MyLocationListener(Runnable runnable) {}

     @Override
     public void onLocationChanged(Location loc) {

     longitude = loc.getLongitude();
     latitude = loc.getLatitude();
     final_latitude = Double.toString(latitude);
     final_longitude = Double.toString(longitude);

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
   }
0 голосов
/ 20 ноября 2013

У меня работает нормально.

Добавить еще одно разрешение для манифеста: использование-разрешения android: name = "android.permission.ACCESS_COARSE_LOCATION"

и попробуйте следующий сегмент кода:

 public class GPSTracker implements LocationListener{
    private final Context mContext;
    // flag for GPS status
    public boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;
     public GPSTracker(Context context) 
    {
        this.mContext = context;
        getLocation();
    }
    /**
     * Function to get the user's current location
     * 
     * @return
     */
    public Location getLocation() 
    {
        try {
            locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            Log.v("isGPSEnabled", "=" + isGPSEnabled);

            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            Log.v("isNetworkEnabled", "=" + isNetworkEnabled);

            if (isGPSEnabled == false && isNetworkEnabled == false) 
            {
                // no network provider is enabled
            } else 
            {
                this.canGetLocation = true;
                if (isNetworkEnabled) 
                {
                    location=null;
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) 
                    {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) 
                        {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) 
                {
                    location=null;
                    if (location == null) 
                    {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) 
                        {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) 
                            {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) 
        {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     * */
    public void stopUsingGPS() 
    {
        if (locationManager != null) 
        {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude() 
    {
        if (location != null) 
        {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() 
    {
        if (location != null) 
        {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * 
     * @return boolean
     * */
    public boolean canGetLocation() 
    {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() 
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",new DialogInterface.OnClickListener() 
        {
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
        {
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }
    @Override
    public void onLocationChanged(Location arg0) 
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String arg0) 
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) 
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) 
    {
        // TODO Auto-generated method stub

    }
0 голосов
/ 27 апреля 2011

Проверьте с помощью журнала, что вы получаете значения для широты и долготы.

Затем в Toast укажите это

 Toast.makeText(LocationFinder.this, "Latitude: " +   loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();

вместо

 Toast.makeText(getBaseContext(), "Latitude: " +   loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
...