2014-11-05 127 views
1

我正在嘗試創建一個只顯示屏幕座標的應用程序。清單文件中添加了以下權限。在android中獲取位置

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

以下是MainActivity.java

import com.example.location.R; 
import android.app.Activity; 
import android.content.ContentResolver; 
import android.content.Context; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.provider.Settings; 

public class MainActivity extends Activity { 

double latitude; 
double longitude; 

TextView lat, longi, loc, status; 

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

    lat = (TextView)findViewById(R.id.latitude); 
    longi = (TextView)findViewById(R.id.longitude); 
    status = (TextView)findViewById(R.id.status); 
    loc = (TextView)findViewById(R.id.location); 

    ContentResolver contentResolver = getBaseContext().getContentResolver(); 
    boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER); 

    if(gpsStatus){ 
     status.setText("GPS_PROVIDER is enabled."); 
     // This is to check if GPS_PROVIDER is enabled or not. 
     // This is working. 
    } 
} 

@Override 
protected void onResume(){ 
    super.onResume(); 
    loc.setText("Entered Resume method"); //This works as well. 
    final LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      latitude = location.getLatitude(); 
      longitude = location.getLongitude(); 

      String str_lat = String.valueOf(latitude); 
      String str_longi = String.valueOf(longitude); 

      lat.setText(str_lat); 
      longi.setText(str_longi); 
      loc.setText((CharSequence) location); 
     } 
     @Override 
     public void onStatusChanged(String provider, int status,Bundle extras) { 
      // TODO Auto-generated method stub 
     } 
     @Override 
     public void onProviderEnabled(String provider) { 
      // TODO Auto-generated method stub 
     } 
     @Override 
     public void onProviderDisabled(String provider) { 
      // TODO Auto-generated method stub 
     } 
    }; 
    final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    //Location Location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    //double altitude = Location.getAltitude(); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener); 
} 
} 

代碼的應用程序不列入的setText的緯度和經度的文本,當在模擬器中運行,我DONOT看到任何錯誤。我甚至沒有得到0.0,0.0的經度和緯度。

雖然運行在手機應用程序,幾秒鐘後,應用程序與對話框關閉「不幸的是,應用程序已停止」

以下是在logcat中的錯誤消息。

11-04 23:35:48.250: E/AndroidRuntime(1224): FATAL EXCEPTION: main 
11-04 23:35:48.250: E/AndroidRuntime(1224): Process: com.example.location, PID: 1224 
11-04 23:35:48.250: E/AndroidRuntime(1224): java.lang.ClassCastException: android.location.Location cannot be cast to java.lang.CharSequence 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at com.example.location.MainActivity$1.onLocationChanged(MainActivity.java:65) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:279) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:208) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:224) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at android.os.Handler.dispatchMessage(Handler.java:102) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at android.os.Looper.loop(Looper.java:136) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at android.app.ActivityThread.main(ActivityThread.java:5017) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at java.lang.reflect.Method.invokeNative(Native Method) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at java.lang.reflect.Method.invoke(Method.java:515) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
11-04 23:35:48.250: E/AndroidRuntime(1224):  at dalvik.system.NativeStart.main(Native Method) 

我是新來的android編程,所以kindle糾正我,如果我正在做任何愚蠢的錯誤,並幫助我學習。任何幫助調試這是非常感謝。

+0

這意味着您的位置對象爲空 – 2014-11-05 04:31:02

+0

請將您在Logcat中看到的錯誤發佈到「不幸,應用程序已停止」時出現。 http://stackoverflow.com/questions/2279647/how-to-emulate-gps-location-in-the-android-emulator是一個很好的指針,通過模擬器獲取位置值。 – 2014-11-05 04:33:02

+0

@VnyKumar:這真的有幫助,我試圖顯示作爲一個分析序列的整個位置的內容。那是錯誤。 – user3543477 2014-11-05 04:44:14

回答

0

嘗試這樣,

把這個代碼的OnCreate()

try { 
     LocationManager mlocManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); 
     LocationListner mListner = new LocationListner(); 
      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        try { 
         try { 
          mlocManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, mListner); 
         } catch (Throwable e) { 
         } 

         mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListner); 
        } catch (Throwable e) { 
        } 
        try { 
         mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mListner); 
        } catch (Throwable e) { 
        } 

       } 
      }); 
     } catch (Throwable e) { 
     } 

class LocationListner implements LocationListener { 

     @Override 
     public void onLocationChanged(Location location) { 
      latitude = location.getLatitude(); 
      longitude = location.getLongitude(); 

      String str_lat = String.valueOf(latitude); 
      String str_longi = String.valueOf(longitude); 

      lat.setText(str_lat); 
      longi.setText(str_longi); 
      loc.setText((CharSequence) location); 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     } 

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

    } 
0

嘗試用下面的代碼:

public static LocationManager mlocManager; 
public static LocationListener mListner; 
private String lat; 
public String longi; 

//Just call this method from onCreate(). 
private void getLatitudeAndLongitude() { 
     try { 
      mlocManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); 
      mListner = new LocationListener() { 
       @Override 
       public void onLocationChanged(Location location) { 
        setLatitude("" + location.getLatitude()); 
        setLongitude("" + location.getLongitude()); 
       } 

       @Override 
       public void onStatusChanged(String s, int i, Bundle bundle) { 

       } 

       @Override 
       public void onProviderEnabled(String s) { 

       } 

       @Override 
       public void onProviderDisabled(String s) { 

       } 
      }; 

      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        try { 
         try { 
          mlocManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, mListner); 
         } catch (Throwable e) { 
          e.printStackTrace(); 
         } 

         mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListner); 
        } catch (Throwable e) { 
         e.printStackTrace(); 
        } 
        try { 
         mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mListner); 
        } catch (Throwable e) { 
         e.printStackTrace(); 
        } 

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

public void setLatitude(String latitide) { 
     lat = latitide; 
    } 

    public void setLongitude(String longitude) { 
     longi = longitude; 
    } 

    public String getLatitude() { 
     if (lat != null) { 
      return lat; 
     } 
     Location loc = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (loc == null) { 
      loc = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
      if (loc == null) { 
       loc = mlocManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 
      } 
      if (loc != null) { 
       return "" + loc.getLatitude(); 
      } 
     } else { 
      return "" + loc.getLatitude(); 
     } 
     return "0"; 
    } 

    public String getLongitude() { 
     if (longi != null) { 
      return longi; 
     } 
     Location loc = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (loc == null) { 
      loc = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
      if (loc == null) { 
       loc = mlocManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 
      } 
      if (loc != null) { 
       return "" + loc.getLongitude(); 
      } 
     } else { 
      return "" + loc.getLongitude(); 
     } 
     return "0"; 
    } 
1

嘗試這個類的位置

import com.arco.util.location.GPSTracker; 
import com.arco.util.location.LocationUtils; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesClient; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.location.LocationClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 

public class MYActivity extends Activity implements OnClickListener, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener { 

    // Global variable to hold the current location 
    Location mCurrentLocation; 
    // Request to connect to Location Services 
    private LocationRequest mLocationRequest; 
    // Stores the current instantiation of the location client in this object 
    private LocationClient mLocationClient; 

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

     // Create a new global location parameters object 
     mLocationRequest = LocationRequest.create(); 
     // Set the update interval 
     mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS); 
     // Use high accuracy 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     // Set the interval ceiling to one minute 
     mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS); 
     mLocationClient = new LocationClient(this, this, this); 




    } // End OnCreate() 



    @Override 
    public void onStart() { 
     super.onStart(); 
     mLocationClient.connect(); 
    } 

    @Override 
    public void onStop() { 
     mLocationClient.disconnect(); 
     super.onStop(); 
    } 

    /** 
    * Verify that Google Play services is available before making a request. 
    */ 
    private boolean servicesConnected() { 

     // Check that Google Play services is available 
     int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 

     // If Google Play services is available 
     if (ConnectionResult.SUCCESS == resultCode) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult mConnectionResult) { 

     if (mConnectionResult.hasResolution()) { 
      try { 
       // Start an Activity that tries to resolve the error 
       mConnectionResult.startResolutionForResult(this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST); 
      } catch (IntentSender.SendIntentException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    @Override 
    public void onConnected(Bundle connectionHint) { 
     try { 
      if (servicesConnected()) { 
       mLocationClient.requestLocationUpdates(mLocationRequest, this); 
       // Get the current location 
       Location currentLocation = mLocationClient.getLastLocation(); 
       if (currentLocation != null) { 
        mCurrentLocation = currentLocation; 
       } 
       mCurrentLocation.getLatitude(); 
       mCurrentLocation.getLongitude() 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onDisconnected() { 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     mCurrentLocation = location; 
    } 
} 
1

@Moradiya Akash,@Karan Mavadhiya,@pratt:謝謝你的幫助。我試圖顯示位置的內容作爲charequence在行

loc.setText((CharSequence) location); 

一旦我刪除它,應用程序工作正常。感謝Vny Kumar幫助我自己調試代碼,從長遠來看這會對我有所幫助。 :)

+0

很高興它的工作..快樂編碼 – 2014-11-05 05:26:12

+0

將位置對象轉換爲CharSequence是主要問題,因爲它們之間沒有繼承關係。 Logcat幫助我們更輕鬆地找到我們的問題。所以試着先找出Logcat說的。 – Sayem 2014-11-05 08:47:39

+0

@Sayem:是的,我將使用logcat來查找變量中的內容。 – user3543477 2014-11-05 19:33:21