获取 Android 位置并返回“未知”或当提供者不可用时为 null

发布于 2024-11-27 06:35:41 字数 5797 浏览 1 评论 0原文

我正在使用 这个脚本由 Fedor 编写,但我想要一点不同:当 GPS 和网络提供商都不可用时,我希望应用程序返回 null 或“未知” 细绳。我修改了脚本,但是当我运行时,它强制关闭,logcat 说:

在此处输入图像描述

我有以下内容代码:

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 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:

enter image description here

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

}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

望笑 2024-12-04 06:35:41

希望这有帮助:

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

希望这有帮助

Hope this helps:

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

Add the above code in your OnCreate method

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

Hope this helpss

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文