获取Android的位置,并返回"未知"或空当供应商不可用 [英] Getting Android Location and return "unknown" or null when providers are unavailable

查看:155
本文介绍了获取Android的位置,并返回"未知"或空当供应商不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用<一个href=\"http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-an/3145655#3145655\">this由费多尔脚本但我想有点区别:当GPS和网络提供商不可用,我想应用返回null或未知字符串。我修改剧本,但是当我运行,它强制关闭时,logcat的说:

I'm using this script by Fedor but I want a little difference: When both GPS and Network Provider is unavailable, I want to app to return null or "unknown" string. I modified the script, but when I run, it force closes, the logcat says:

我有以下的codeS:

I have the following codes:

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,任何帮助非常感谢! :)

I'm kinda new to java and android, many thanks for any help! :)

推荐答案

希望这有助于:

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();
        }

添加上述code在onCreate方法

Add the above code in your OnCreate method

和出onCreate方法的创建下面的类

and out of the onCreate method create a following class

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

希望这helpss

Hope this helpss

这篇关于获取Android的位置,并返回&QUOT;未知&QUOT;或空当供应商不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆