2013年10月15日 星期二

GPS 範例

首先要先將權限打開
 <uses-permission  android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

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

在Layout 中放入4個TextView

 <TextView    
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/longitude" />
 
  <TextView    
    android:id="@+id/longitude"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
     />
 
  <TextView    
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/latitude" />
 
  <TextView    
    android:id="@+id/latitude"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
     />
    
在主程式中 繼承了Activity 並實作LocationListener 
public class MainActivity extends Activity implements LocationListener ,在LocationListener 中有幾個方法需實作。

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
getLocation(location);
}

@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
}

在onCreate 中呼叫Init 函數來判斷GPS 或網路是否被打開,如果沒被打開則應用
Settings.ACTION_LOCATION_SOURCE_SETTINGS 來把介面用intent帶到android的設定頁面。
如果GPS 或網路被打開應用
Location location=lms.getLastKnownLocation(GPS_PROVIDER); 來抓取目前位置
Double longitude=location.getLongitude();
Double latitude=location.getLatitude();
longtitudeTv.setText(String.valueOf(longitude));
latitudeTv.setText(String.valueOf(latitude));





沒有留言:

張貼留言