【问题标题】:Unable to toast latitude and longitude无法吐司经纬度
【发布时间】:2013-11-28 19:17:28
【问题描述】:

我正在开发一个应用程序,该应用程序使用 LocationManager 和 LocationListener 来显示纬度和经度。在运行该应用程序时,会显示一条错误消息“抱歉,进程系统没有响应。”。当我从 DDMS 下的模拟器控制或使用 telnet 从命令提示符手动提供 lat 和 long 时,就会发生这种情况。

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。

我想知道我的代码是否有问题。 谢谢

【问题讨论】:

  • 不知道确切但尝试将 Toast.makeText()... 中的第一个参数更改为 getApplicationContext().....
  • 删除 MyLocationListener 中的 @Overrides 有影响吗?

标签: android locationmanager


【解决方案1】:

通过使用日志检查您是否正在获取纬度和经度值..

然后在 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();

【讨论】:

    【解决方案2】:
      //  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) {
        }
       }
    

    【讨论】:

      【解决方案3】:

      它适合我。

      再添加 1 个清单权限:uses-permission 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
      
          }
      

      【讨论】:

        猜你喜欢
        • 2020-04-08
        • 2016-06-16
        • 2013-12-09
        • 2020-06-28
        • 2013-09-09
        • 2013-06-23
        • 1970-01-01
        • 2020-07-18
        • 2014-01-15
        相关资源
        最近更新 更多