当我将反向地理编码器功能放入服务类并尝试调用活动时,我得到空指针异常.. 这是我的班级
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String tempAddress;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
location = locationManager
.getLastKnownLocation(locationProvider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
String locationgps=LocationManager.GPS_PROVIDER;
location = locationManager
.getLastKnownLocation(locationgps);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS/Data roaming is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public String getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
double latitude=getLatitude();
double longitude=getLongitude();
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
Toast.makeText(getApplicationContext(),"I am at: "+strAddress.toString(),Toast.LENGTH_LONG).show();
// myAddress.setText("I am at: " +strAddress.toString());
tempAddress=strAddress.toString();
return tempAddress;
//Intent intent = new Intent("MyCustomIntent");
// add data to the Intent
// intent.putExtra("strAddress",strAddress.toString());
// intent.setAction("android.provider.Telephony.SMS_RECEIVED");
// sendBroadcast(intent);
// Intent intent = new Intent (Menu.this,IncomingSms.class);
// intent.putExtra("strAddress",strAddress.toString());
// sendBroadcast(intent);
}
else
Toast.makeText(getApplicationContext(), "No Location found", Toast.LENGTH_LONG).show();
//myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Tidak bisa Menerima Alamat ,, harap cek jaringan dan gps hp anda!", Toast.LENGTH_LONG).show();
showSettingsAlert();}
tempAddress="Could not Retrive Address!";
return tempAddress;
}
}
这是我的活动课程:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import javax.xml.transform.Templates;
import mo.locationtracking.GPSTracker;
import mo.sms.IncomingSms;
import info.MonitoringObjek.R;
import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
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 Menu extends Activity implements OnClickListener{
private Button bTambah;
private Button bLihat;
//private Button blokasi;
GPSTracker gps;
private TextView myAddress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
myAddress = (TextView)findViewById(info.MonitoringObjek.R.id.lokasisekarang);
// blokasi=(Button) findViewById(R.id.button_lokasi);
// blokasi.setOnClickListener(this);
bTambah = (Button) findViewById(R.id.button_tambah);
bTambah.setOnClickListener(this);
bLihat = (Button) findViewById(R.id.button_view);
bLihat.setOnClickListener(this);
// create class object
gps = new GPSTracker(Menu.this);
// check if GPS enabled
if(gps.canGetLocation()){
//double latitude = gps.getLatitude();
//double longitude = gps.getLongitude();
//Geocoder geocoder;
//myAddress.setText("Latitude: "+latitude+"Longitude: "+longitude);
String tempAddress=gps.getMyLocationAddress();
myAddress.setText("I am at: " +tempAddress);
gps.stopUsingGPS();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button_tambah :
Intent i = new Intent(this, CreateData.class);
startActivity(i);
break;
case R.id.button_view :
Intent i2 = new Intent(this, ViewData.class);
startActivity(i2);
break;
}
}
}
这是我的logcat:
05-28 14:47:14.187: E/Trace(5031): error opening trace file: No such file or directory (2)
05-28 14:47:14.688: E/AndroidRuntime(5031): FATAL EXCEPTION: main
05-28 14:47:14.688: E/AndroidRuntime(5031): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.MonitoringObjek/mo.database.Menu}: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.access$600(ActivityThread.java:137)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Handler.dispatchMessage(Handler.java:99)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Looper.loop(Looper.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.main(ActivityThread.java:4786)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invokeNative(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invoke(Method.java:511)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
05-28 14:47:14.688: E/AndroidRuntime(5031): at dalvik.system.NativeStart.main(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): Caused by: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.Geocoder.<init>(Geocoder.java:83)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.locationtracking.GPSTracker.getMyLocationAddress(GPSTracker.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.database.Menu.onCreate(Menu.java:54)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Activity.performCreate(Activity.java:5008)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
05-28 14:47:14.688: E/AndroidRuntime(5031): ... 11 more
我在this post中看到地理编码器必须在活动中创建内部声明..是否在服务类中声明是不可能的?我需要地理编码器仍然更新,即使我的应用程序已关闭..
答案 0 :(得分:0)
Android应用程序的位置并不是那么准确你可以用get方法调用google api webservice并解析json结果你可以得到Area Block city street等 它比默认值更准确