您正在使用简单的Android应用程序,显示用户的地址,但这个应用程序正在模拟器中工作,但当我在移动设备安装它显示力close.please帮助我提前感谢
package com.gps.com;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class main extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
public Location location;
public TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
tv= (TextView)findViewById(R.id.tv);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
showCurrentLocation();
}
});
}
public void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(main.this, message,
Toast.LENGTH_LONG).show();
}
try {
List<Address> addresses;
Geocoder gc = new Geocoder(this, Locale.ENGLISH);
addresses = gc.getFromLocation(location.getLatitude(),location.getLongitude(), 1);
if(addresses != null) {
Address currentAddr = addresses.get(0);
StringBuilder sb = new StringBuilder("Address:\n");
for(int i=0; i<currentAddr.getMaxAddressLineIndex(); i++) {
sb.append(currentAddr.getAddressLine(i)).append("\n");
}
tv.setText(sb.toString());
}
} catch(IOException e) {
tv.setText("Something is mistake the error is"+e);
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(main.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(main.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(main.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(main.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
答案 0 :(得分:2)
这一行
addresses = gc.getFromLocation(location.getLatitude(),location.getLongitude(), 1);
可能会给你一个Nullpointer异常,因为它在if-block之外,是未处理的,因为你只是在特定的try-block中捕获IOException。 这可能不是解决你遇到的问题的方法,但我认为无论如何我都会指出它。
答案 1 :(得分:1)
这也是一个明显的建议,但你不能以编程方式打开GPS,你必须手动完成。您是否已确认手机中的GPS已开启?
答案 2 :(得分:0)
我也有同样的问题。在manifest.xml中尝试此代码。它为我工作。
MainActivity:
public class WhereIActivity extends MapActivity {
// MapController mc;
MapView myMapView;
MapController mapController;
GeoPoint point;
MyPositionOverlay positionOverlay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_where_i);
MapView myMapView=(MapView)findViewById(R.id.myMapView);
mapController=myMapView.getController();
myMapView.displayZoomControls(false);
mapController.setZoom(17);
positionOverlay=new MyPositionOverlay();
List<Overlay> overlays=myMapView.getOverlays();
overlays.add(positionOverlay);
// myMapView.setSatellite(true);
myMapView.setStreetView(true);
myMapView.setTraffic(true);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
// String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String latLong;
TextView myLocation;
myLocation = (TextView) findViewById(R.id.myLocation);
String addressString = "no address found";
if(location!=null) {
positionOverlay.setLocation(location);
Double geoLat=location.getLatitude()*1E6;
Double geoLng=location.getLongitude()*1E6;
GeoPoint point=new GeoPoint(geoLat.intValue(),geoLng.intValue());
mapController.animateTo(point);
double lat = location.getLatitude();
double lon = location.getLongitude();
latLong = "Lat:" + lat + "\nLong:" + lon;
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this,Locale.getDefault());
try {
List<Address> addresses= gc.getFromLocation(lattitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if(addresses.size()>0) {
Address address=addresses.get(0);
for(int i=0;i<address.getMaxAddressLineIndex();i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch (Exception e) {
}
} else {
latLong = " NO Location Found ";
}
myLocation.setText("Current Position is :\n"+ latLong + "\n"+ addressString );
}
MyPositionOverlay:
public class MyPositionOverlay extends Overlay {
Location location;
private final int mRadius=5;
@Override
public void draw(Canvas canvas,MapView mapView,boolean shadow){
Projection projection=mapView.getProjection();
if(shadow==false){
Double latitude=location.getLatitude()*1E6;
Double longitude=location.getLongitude()*1E6;
GeoPoint geoPoint;
geoPoint=new GeoPoint(latitude.intValue(),longitude.intValue());
Point point=new Point();
projection.toPixels(geoPoint, point);
RectF oval=new RectF(point.x - mRadius,point.y - mRadius,point.x + mRadius,point.y + mRadius);
Paint paint=new Paint();
paint.setARGB(250, 255, 255, 255);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
Paint backPaint=new Paint();
backPaint.setARGB(175, 50, 50, 50);
backPaint.setAntiAlias(true);
RectF backRect=new RectF(point.x + 2 + mRadius, point.y - 3*mRadius,point.x + 65, point.y + mRadius);
canvas.drawOval(oval, paint);
canvas.drawRoundRect(backRect, 5, 5, backPaint);
canvas.drawText("Here I Am", point.x + 2*mRadius, point.y, paint);
}
super.draw(canvas, mapView, shadow);
}
@Override
public boolean onTap(GeoPoint point,MapView mapView){
return false;
}
public Location getLocation(){
return location;
}
public void setLocation(Location location){
this.location=location;
}
}
main.xml中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".WhereIActivity" >
<com.google.android.maps.MapView
android:id="@+id/myMapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0_MW1zfGUXAZ2cAEBaB62GeWv0FoZODowBf1WYg"
/>
<TextView
android:id="@+id/myLocation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".WhereIActivity"
android:gravity="center_horizontal"
android:textStyle="bold"
android:textSize="14sp"
android:typeface="sans"
android:textColor="#0099CC"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
manifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.wherei"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="com.google.android.maps"></uses-library>
<activity
android:name=".WhereIActivity"
android:label="@string/title_activity_where_i" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
</manifest>