获取Android位置并返回“unknown”或提供商不可用时为null

时间:2011-08-01 04:22:52

标签: android networking gps location

我正在使用this script by Fedor,但我想要一点点差异:当GPS和网络提供商都不可用时,我想让app返回null或“unknown”字符串。我修改了脚本,但是当我运行时,强制关闭,logcat说:

enter image description here

我有以下代码:

MyLocation.java

package com.example.GetALocation2;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);

        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 20000);

        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             /*
             Location net_loc=null, gps_loc=null;


             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);


             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             */

             locationResult.gotLocation( null );
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

GetALocation2.java

package com.example.GetALocation2;

import com.example.GetALocation2.MyLocation.LocationResult;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class GetALocation2 extends Activity {

    Double latitude;
    TextView tv;
    MyLocation myLocation = new MyLocation();


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "This is the start!", Toast.LENGTH_SHORT).show();
        locationClick();
    }


    private void locationClick() {
        myLocation.getLocation(this, locationResult);
    }

    public LocationResult locationResult = new LocationResult(){
        @Override
        public void gotLocation(final Location location){
            //Got the location!

                if( location == null ){
                    Toast.makeText(getBaseContext(), "Location is unknown.", Toast.LENGTH_SHORT).show();
                }else{
                    GetALocation2.this.latitude = location.getLatitude();
                    Toast.makeText(getBaseContext(), "I got the location! >>> " + location.getLatitude(), Toast.LENGTH_SHORT).show();
                }
            };
    };

}

我是java和android的新手,非常感谢任何帮助! :)

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助:

private LocationManager lm; 
private LocationListener ll;
public static String latitude;
public static String longitude;
double lat,lon;


  lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

        if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
//                      Toast.makeText(this,"GPS PROVIDER", Toast.LENGTH_LONG).show();
            ll = new GpsListener(); 
            //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0,ll);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, ll);

        }else if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
//              Toast.makeText(this,"NETWORK PROVIDER.", Toast.LENGTH_LONG).show();
            ll = new GpsListener();
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,0, ll);

        }else{
            Toast.makeText(this,"GPS is disabled.", Toast.LENGTH_LONG).show();
            prog.dismiss();
        }

在OnCreate方法中添加以上代码

并且在onCreate方法之外创建以下类

private class GpsListener implements LocationListener 
 {

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        float acc=-1;
        if(location!=null) {
            Toast.makeText(HomeScreen.hs,"Location Found", Toast.LENGTH_LONG).show();
            System.out.println("IN IF PART");

            if(location.hasAccuracy())
                    acc = location.getAccuracy();

            lat = location.getLatitude();
            lon = location.getLongitude();
            isLocFound=true;
            latitude = Double.toString(lat);
            longitude = Double.toString(lon);

            System.out.println("1)"+acc+" 2) "+latitude+" 3) "+longitude);

            lm.removeUpdates(ll);
            lm = null;

            stopSelf();
            //stopForeground(true);

        }else{
            Toast.makeText(HomeScreen.hs,"No Location Found", Toast.LENGTH_LONG).show();
            System.out.println("IN ELSE PART..");
        }

        prog.dismiss();
    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }


}//end of Class

希望这个帮助