现在的位置: 首页 > 综合 > 正文

Location managers, providers, and listeners

2017年12月24日 ⁄ 综合 ⁄ 共 7872字 ⁄ 字号 评论关闭

The LocationManager class is the gateway into all the location related services on Android. It’s a system service that allows you to access location providers, set up location

update listeners and proximity alerts, and more. The LocationProvider class, on the other hand, is provides location data. LocationListener instances use specified providers to asynchronously return location updates to applications.

The LocationManager can be used to query for a list of available location providers, get a reference to a provider by name or capability criteria, get the last-known location
for a named provider (which may be null, or very old), register for several types of location updates and alerts, and more.

we’re using the following manifest permission:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.locationinfo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Main"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ProviderDetail" />
		<activity android:name=".GetLocationWithGPS" />
    </application>
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" 
	android:layout_width="fill_parent"
	android:layout_height="fill_parent" 
	android:gravity="center_horizontal">
	<TextView android:id="@+id/title" 
	    android:layout_width="wrap_content"
		android:layout_height="wrap_content" 
		android:layout_marginTop="5dp"
		android:layout_marginBottom="20dp" 
		android:text="Current Location Providers"
		android:textAppearance="?android:attr/textAppearanceLarge" />
	<ListView 
	    android:id="@+id/location_providers"
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" />
	<Button 
	    android:id="@+id/getloc_button" 
	    android:layout_width="wrap_content"
		android:layout_height="wrap_content" 
		android:layout_marginTop="20dp"
		android:layout_marginBottom="10dp" 
		android:text="Get current location via GPS"
		android:textAppearance="?android:attr/textAppearanceMedium" />	
</LinearLayout>

title_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" 
	android:layout_width="fill_parent"
	android:layout_height="fill_parent" 
	android:gravity="center_horizontal">
	<TextView android:id="@+id/title" 
	    android:layout_width="wrap_content"
		android:layout_height="wrap_content" 
		android:layout_marginTop="5dp"
		android:layout_marginBottom="20dp" 
		android:textAppearance="?android:attr/textAppearanceLarge" />
	<ScrollView android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:layout_margin="5dp"
		android:orientation="vertical">
	<TextView android:id="@+id/detail" 
	    android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginBottom="5dp"
		android:layout_marginTop="30dp" 
		android:textAppearance="?android:attr/textAppearanceMedium" />
	</ScrollView>
</LinearLayout>

The Main Activity of the LocationInfo application

public class Main extends Activity implements OnItemClickListener {
	 public static final String LOG_TAG = "LocationInfo";
	 public static final String PROVIDER_NAME = "PROVIDER_NAME";
	 private LocationManager locationMgr;//include locationManager
	 private ListView providersList;
	 private Button getLoc;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //instantiate LocationManager
        locationMgr=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //use Manager to get list of providers
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,locationMgr.getAllProviders());
        providersList=(ListView)findViewById(R.id.location_providers);
        providersList.setAdapter(adapter);
        //assign ListView click Listener
        providersList.setOnItemClickListener(this);
        getLoc=(Button)findViewById(R.id.getloc_button);
        getLoc.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(Main.this,GetLocationWithGPS.class));
			}
        });
    }
    //implement ListView click listener
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		TextView textView=(TextView)view;
		String providerName=textView.getText().toString();
		Intent intent=new Intent(Main.this,ProviderDetail.class);
		intent.putExtra(PROVIDER_NAME, providerName);
		startActivity(intent);
	}

}

Once you select a provider to use, you’ll get a reference to it via the manager, which you can use to get the last-known location and probe its capabilities. The capabilities
include how accurate it is, whether it’s free, how much power it uses, whether it includes altitude and bearing, and so on.

ProviderDetail.java

//NOTE that "network" provider will always return null for getLastKnownLocation
//if settings->location and security->Use wireless networks is NOT CHECKED (very often it's not)
public class ProviderDetail extends Activity {
	private LocationManager locationMgr;
	private TextView title;
	private TextView detail;
	
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.title_detail);
		locationMgr=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
		title=(TextView)findViewById(R.id.title);
		detail=(TextView)findViewById(R.id.detail);
	}
	
	protected void onResume(){
		super.onResume();
		
		//get ProviderName from intent
		String providerName=getIntent().getStringExtra("PROVIDER_NAME");
		//get LastKnownLocation 
		Location lastLocation=locationMgr.getLastKnownLocation(providerName);
		//get LocationProvider by name
		LocationProvider provider=locationMgr.getProvider(providerName);
		StringBuilder sb=new StringBuilder();
		  sb.append("location manager data");
	      sb.append("\n--------------------------------");
	      if (lastLocation != null) {
	         sb.append("\n");
	         Printer printer = new StringBuilderPrinter(sb);
	         lastLocation.dump(printer, "last location: ");
	      } else {
	         sb.append("\nlast location: null\n");
	      }
	     
	      sb.append("\n");
	      sb.append("\nprovider properties");
	      sb.append("\n--------------------------------");
	      //query provider capabilities
	      sb.append("\naccuracy: " + provider.getAccuracy());
	      sb.append("\npower requirement: " + provider.getPowerRequirement());
	      sb.append("\nhas monetary cost: " + provider.hasMonetaryCost());
	      sb.append("\nsupports altitude: " + provider.supportsAltitude());
	      sb.append("\nsupports bearing: " + provider.supportsBearing());
	      sb.append("\nsupports speed: " + provider.supportsSpeed());
	      sb.append("\nrequires cell: " + provider.requiresCell());
	      sb.append("\nrequires network: " + provider.requiresNetwork());
	      
	      // extra details for GpsStatus if provider is GPS
	      if (providerName.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
	         GpsStatus gpsStatus = locationMgr.getGpsStatus(null);
	         sb.append("\ngps status");
	         sb.append("\n--------------------------------");
	         sb.append("\ntime to first fix: " + gpsStatus.getTimeToFirstFix());
	         sb.append("\nmax satellites: " + gpsStatus.getMaxSatellites());
	         ArrayList<GpsSatellite> satellites = new ArrayList<GpsSatellite>();
	         for (GpsSatellite satellite : gpsStatus.getSatellites()) {
	            satellites.add(satellite);
	         }
	         sb.append("\ncurrent satellites: " + satellites.size());
	         if (satellites.size() > 0) {
	            for (GpsSatellite satellite : satellites) {
	               sb.append("\nsatellite: " + satellite.getPrn());
	               sb.append("\n   azimuth " + satellite.getAzimuth());
	               sb.append("\n   elevation " + satellite.getElevation());
	               sb.append("\n   signal to noise ratio " + satellite.getSnr());
	            }
	         }
	      }
	      title.setText("Provider: " + providerName);
	      detail.setText(sb.toString());
	}
	
}

To get your current location or be notified of location changes on an ongoing basis, establish a LocationListener. In essence, a LocationListener is registered using one
of several LocationManager methods that allow you to pass in the name of the provider you want to use, along with a callback listener (and a few other properties, such
as time and distance, as needed).

抱歉!评论已关闭.