各位大佬,我是大二学生。最近在看《第一行代码(第一版)》时,看到GPS定位时按着书上代码打的,但是却显示工程发生错误,检查了一下代码,未能发现错误。特此求助。
注明:已在AndroidMainFest中声明网络权限和位置权限。
package com.example.school_pet;
import java.util.List;
import android.app.Activity;
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.widget.Toast;
public class test_location extends Activity{
private TextView positionTextView;
private LocationManager locationManager;
private String provider;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.location_test);
positionTextView=(TextView)findViewById(R.id.show_location);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//获取所有可用的位置提供器
List<String>providerList=locationManager.getProviders(true);
if(providerList.contains(LocationManager.GPS_PROVIDER)){
provider=LocationManager.GPS_PROVIDER;
}else if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
provider=LocationManager.NETWORK_PROVIDER;
}else {
Toast.makeText(this, "No location provider to use.",Toast.LENGTH_SHORT).show();
return;
}
Location location=locationManager.getLastKnownLocation(provider);
if(location !=null)
{showLocation(location);}
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
}
protected void onDestroy(){
super.onDestroy();
if(locationManager!=null){
locationManager.removeUpdates(locationListener);
}
}
LocationListener locationListener=new LocationListener(){
public void onStatusChanged(String provider,int status,Bundle extras){
}
public void onProviderEnabled(String provider){
}
public void onProviderDisabled(String provider){
}
public void onLocationChanged(Location location){
showLocation(location);
}
};
private void showLocation(Location location){
String currentPosition="latitude is"+location.getLatitude()+"\n"+"longitude is "+location.getLongitude();
positionTextView.setText(currentPosition);
}
}